blob: e2a33a9c04b4578e6af40b211c56b21822565b4b [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"
Rui Ueyamaf5febef2016-05-24 02:55:45 +000012#include "EhFrame.h"
George Rimare2ee72b2016-02-26 14:48:31 +000013#include "LinkerScript.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000014#include "SymbolTable.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000015#include "Target.h"
Rui Ueyamae9809502016-03-11 04:23:12 +000016#include "lld/Core/Parallel.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000017#include "llvm/Support/Dwarf.h"
Rui Ueyama3a41be22016-04-07 22:49:21 +000018#include "llvm/Support/MD5.h"
Igor Kudrin1b0d7062015-10-22 08:21:35 +000019#include "llvm/Support/MathExtras.h"
Rui Ueyamad86ec302016-04-07 23:51:56 +000020#include "llvm/Support/SHA1.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000021#include <map>
Rafael Espindola5805c4f2015-09-21 21:38:08 +000022
Rafael Espindola5805c4f2015-09-21 21:38:08 +000023using namespace llvm;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +000024using namespace llvm::dwarf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000025using namespace llvm::object;
Rafael Espindolaa6627382015-10-06 23:56:53 +000026using namespace llvm::support::endian;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000027using namespace llvm::ELF;
28
29using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000030using namespace lld::elf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000031
George Rimar12737b72016-02-25 08:40:26 +000032static bool isAlpha(char C) {
33 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
34}
35
36static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
37
38// Returns true if S is valid as a C language identifier.
Rafael Espindolae0df00b2016-02-28 00:25:54 +000039bool elf::isValidCIdentifier(StringRef S) {
Rui Ueyamadad77c52016-02-26 15:42:06 +000040 return !S.empty() && isAlpha(S[0]) &&
41 std::all_of(S.begin() + 1, S.end(), isAlnum);
George Rimar12737b72016-02-25 08:40:26 +000042}
43
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000044template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +000045OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
46 uintX_t Flags)
Rafael Espindola5805c4f2015-09-21 21:38:08 +000047 : Name(Name) {
Sean Silva580c1b62016-04-20 04:26:16 +000048 memset(&Header, 0, sizeof(Elf_Shdr));
Rui Ueyamad97e5c42016-01-07 18:33:11 +000049 Header.sh_type = Type;
50 Header.sh_flags = Flags;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000051}
52
Rafael Espindola35c6af32015-09-25 17:19:10 +000053template <class ELFT>
Rui Ueyamac63c1db2016-03-13 06:50:33 +000054void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
55 *Shdr = Header;
56}
57
58template <class ELFT>
George Rimar648a2c32015-10-20 08:54:27 +000059GotPltSection<ELFT>::GotPltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000060 : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
George Rimar648a2c32015-10-20 08:54:27 +000061 this->Header.sh_addralign = sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000062}
63
Rafael Espindola67d72c02016-03-11 12:06:30 +000064template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
65 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
66 Entries.push_back(&Sym);
George Rimar648a2c32015-10-20 08:54:27 +000067}
68
69template <class ELFT> bool GotPltSection<ELFT>::empty() const {
Igor Kudrin351b41d2015-11-16 17:44:08 +000070 return Entries.empty();
George Rimar648a2c32015-10-20 08:54:27 +000071}
72
George Rimar648a2c32015-10-20 08:54:27 +000073template <class ELFT> void GotPltSection<ELFT>::finalize() {
Igor Kudrin351b41d2015-11-16 17:44:08 +000074 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +000075 (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000076}
77
78template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +000079 Target->writeGotPltHeader(Buf);
Rui Ueyama724d6252016-01-29 01:49:32 +000080 Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000081 for (const SymbolBody *B : Entries) {
Rui Ueyamab5a69702016-02-01 21:00:35 +000082 Target->writeGotPlt(Buf, B->getPltVA<ELFT>());
George Rimar648a2c32015-10-20 08:54:27 +000083 Buf += sizeof(uintX_t);
84 }
85}
86
87template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +000088GotSection<ELFT>::GotSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000089 : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
Igor Kudrin15cd9ff2015-11-06 07:43:03 +000090 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +000091 this->Header.sh_flags |= SHF_MIPS_GPREL;
Rui Ueyama5f551ae2015-10-14 14:02:06 +000092 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +000093}
94
Rafael Espindola67d72c02016-03-11 12:06:30 +000095template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +000096 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanbea20c32016-03-23 09:28:02 +000097 // For "true" local symbols which can be referenced from the same module
98 // only compiler creates two instructions for address loading:
99 //
100 // lw $8, 0($gp) # R_MIPS_GOT16
101 // addi $8, $8, 0 # R_MIPS_LO16
102 //
103 // The first instruction loads high 16 bits of the symbol address while
104 // the second adds an offset. That allows to reduce number of required
105 // GOT entries because only one global offset table entry is necessary
106 // for every 64 KBytes of local data. So for local symbols we need to
107 // allocate number of GOT entries to hold all required "page" addresses.
108 //
109 // All global symbols (hidden and regular) considered by compiler uniformly.
110 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
111 // to load address of the symbol. So for each such symbol we need to
112 // allocate dedicated GOT entry to store its address.
113 //
114 // If a symbol is preemptible we need help of dynamic linker to get its
115 // final address. The corresponding GOT entries are allocated in the
116 // "global" part of GOT. Entries for non preemptible global symbol allocated
117 // in the "local" part of GOT.
118 //
119 // See "Global Offset Table" in Chapter 5:
120 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyand2980d32016-03-29 14:07:22 +0000121 if (Sym.isLocal()) {
122 // At this point we do not know final symbol value so to reduce number
123 // of allocated GOT entries do the following trick. Save all output
124 // sections referenced by GOT relocations. Then later in the `finalize`
125 // method calculate number of "pages" required to cover all saved output
126 // section and allocate appropriate number of GOT entries.
127 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
128 MipsOutSections.insert(OutSec);
129 return;
130 }
131 if (!Sym.isPreemptible()) {
132 // In case of non-local symbols require an entry in the local part
133 // of MIPS GOT, we set GotIndex to 1 just to accent that this symbol
134 // has the GOT entry and escape creation more redundant GOT entries.
135 // FIXME (simon): We can try to store such symbols in the `Entries`
136 // container. But in that case we have to sort out that container
137 // and update GotIndex assigned to symbols.
138 Sym.GotIndex = 1;
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +0000139 ++MipsLocalEntries;
140 return;
141 }
142 }
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) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000148 if (Sym.symbol()->GlobalDynIndex != -1U)
George Rimar90cd0a82015-12-01 19:20:26 +0000149 return false;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000150 Sym.symbol()->GlobalDynIndex = 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
Rafael Espindola58cd5db2016-04-19 22:46:03 +0000170GotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000171 // Initialize the entry by the %hi(EntryValue) expression
172 // but without right-shifting.
Rafael Espindola58cd5db2016-04-19 22:46:03 +0000173 return getMipsLocalEntryOffset((EntryValue + 0x8000) & ~0xffff);
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000174}
175
176template <class ELFT>
177typename GotSection<ELFT>::uintX_t
Rafael Espindola58cd5db2016-04-19 22:46:03 +0000178GotSection<ELFT>::getMipsLocalEntryOffset(uintX_t EntryValue) {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000179 // Take into account MIPS GOT header.
180 // See comment in the GotSection::writeTo.
181 size_t NewIndex = MipsLocalGotPos.size() + 2;
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000182 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
183 assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries);
George Rimar71e64b22016-05-11 09:41:15 +0000184 return (uintX_t)P.first->second * sizeof(uintX_t) - MipsGPOffset;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000185}
186
Igor Kudrin304860a2015-11-12 04:39:49 +0000187template <class ELFT>
George Rimar90cd0a82015-12-01 19:20:26 +0000188typename GotSection<ELFT>::uintX_t
189GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000190 return this->getVA() + B.symbol()->GlobalDynIndex * sizeof(uintX_t);
George Rimar90cd0a82015-12-01 19:20:26 +0000191}
192
193template <class ELFT>
Rafael Espindola74031ba2016-04-07 15:20:56 +0000194typename GotSection<ELFT>::uintX_t
195GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000196 return B.symbol()->GlobalDynIndex * sizeof(uintX_t);
Rafael Espindola74031ba2016-04-07 15:20:56 +0000197}
198
199template <class ELFT>
Igor Kudrin304860a2015-11-12 04:39:49 +0000200const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
201 return Entries.empty() ? nullptr : Entries.front();
202}
203
204template <class ELFT>
205unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000206 return MipsLocalEntries;
Igor Kudrin304860a2015-11-12 04:39:49 +0000207}
208
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000209template <class ELFT> void GotSection<ELFT>::finalize() {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000210 if (Config->EMachine == EM_MIPS)
211 // Take into account MIPS GOT header.
212 // See comment in the GotSection::writeTo.
213 MipsLocalEntries += 2;
Simon Atanasyand2980d32016-03-29 14:07:22 +0000214 for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
215 // Calculate an upper bound of MIPS GOT entries required to store page
216 // addresses of local symbols. We assume the worst case - each 64kb
217 // page of the output section has at least one GOT relocation against it.
218 // Add 0x8000 to the section's size because the page address stored
219 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
220 MipsLocalEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
221 }
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000222 this->Header.sh_size = (MipsLocalEntries + Entries.size()) * sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000223}
224
Rafael Espindolaa6627382015-10-06 23:56:53 +0000225template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000226 if (Config->EMachine == EM_MIPS) {
227 // Set the MSB of the second GOT slot. This is not required by any
228 // MIPS ABI documentation, though.
229 //
230 // There is a comment in glibc saying that "The MSB of got[1] of a
231 // gnu object is set to identify gnu objects," and in GNU gold it
232 // says "the second entry will be used by some runtime loaders".
233 // But how this field is being used is unclear.
234 //
235 // We are not really willing to mimic other linkers behaviors
236 // without understanding why they do that, but because all files
237 // generated by GNU tools have this special GOT value, and because
238 // we've been doing this for years, it is probably a safe bet to
239 // keep doing this for now. We really need to revisit this to see
240 // if we had to do this.
241 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
242 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
243 }
Rui Ueyama5cbf5d22016-02-02 02:29:03 +0000244 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000245 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
246 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
247 }
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000248 Buf += MipsLocalEntries * sizeof(uintX_t);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000249 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000250 uint8_t *Entry = Buf;
251 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000252 if (!B)
253 continue;
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000254 // MIPS has special rules to fill up GOT entries.
255 // See "Global Offset Table" in Chapter 5 in the following document
256 // for detailed description:
257 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
258 // As the first approach, we can just store addresses for all symbols.
Rui Ueyamac4466602016-03-13 19:48:18 +0000259 if (Config->EMachine != EM_MIPS && B->isPreemptible())
Rafael Espindolaa6627382015-10-06 23:56:53 +0000260 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000261 uintX_t VA = B->getVA<ELFT>();
Rafael Espindolae782f672015-10-07 03:56:05 +0000262 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000263 }
264}
265
Rafael Espindola35c6af32015-09-25 17:19:10 +0000266template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000267PltSection<ELFT>::PltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000268 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000269 this->Header.sh_addralign = 16;
270}
271
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000272template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000273 // At beginning of PLT, we have code to call the dynamic linker
274 // to resolve dynsyms at runtime. Write such code.
275 Target->writePltZero(Buf);
Rui Ueyamaf57a5902016-05-20 21:39:07 +0000276 size_t Off = Target->PltZeroSize;
277
George Rimarfb5d7f22015-11-26 19:58:51 +0000278 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000279 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000280 unsigned RelOff = I.second;
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000281 uint64_t Got = B->getGotPltVA<ELFT>();
Rui Ueyama242ddf42015-10-12 18:56:36 +0000282 uint64_t Plt = this->getVA() + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000283 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000284 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000285 }
286}
287
Rafael Espindola67d72c02016-03-11 12:06:30 +0000288template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
289 Sym.PltIndex = Entries.size();
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000290 unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000291 Entries.push_back(std::make_pair(&Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000292}
293
George Rimar648a2c32015-10-20 08:54:27 +0000294template <class ELFT> void PltSection<ELFT>::finalize() {
Rui Ueyama724d6252016-01-29 01:49:32 +0000295 this->Header.sh_size =
Rui Ueyama62515452016-01-29 03:00:32 +0000296 Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000297}
298
299template <class ELFT>
George Rimarc191acf2016-05-10 15:47:57 +0000300RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000301 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
George Rimarc191acf2016-05-10 15:47:57 +0000302 SHF_ALLOC),
303 Sort(Sort) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000304 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000305 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000306}
307
George Rimar5828c232015-11-30 17:49:19 +0000308template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000309void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000310 Relocs.push_back(Reloc);
311}
312
George Rimarc191acf2016-05-10 15:47:57 +0000313template <class ELFT, class RelTy>
314static bool compRelocations(const RelTy &A, const RelTy &B) {
315 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
316}
317
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000318template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarc191acf2016-05-10 15:47:57 +0000319 uint8_t *BufBegin = Buf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000320 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rui Ueyama614be592016-03-13 05:23:40 +0000321 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000322 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rafael Espindolade9857e2016-02-04 21:33:05 +0000323 SymbolBody *Sym = Rel.Sym;
Rui Ueyamab0210e832016-01-26 00:24:57 +0000324
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000325 if (Config->Rela)
Rui Ueyama614be592016-03-13 05:23:40 +0000326 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend;
Rafael Espindola74031ba2016-04-07 15:20:56 +0000327 P->r_offset = Rel.OffsetInSec + Rel.OffsetSec->getVA();
Rafael Espindolade9857e2016-02-04 21:33:05 +0000328 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
329 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000330 }
George Rimarc191acf2016-05-10 15:47:57 +0000331
332 if (Sort) {
333 if (Config->Rela)
334 std::stable_sort((Elf_Rela *)BufBegin,
335 (Elf_Rela *)BufBegin + Relocs.size(),
336 compRelocations<ELFT, Elf_Rela>);
337 else
338 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
339 compRelocations<ELFT, Elf_Rel>);
340 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000341}
342
George Rimar77b77792015-11-25 22:15:01 +0000343template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rui Ueyama5a0b2f72016-02-05 19:13:18 +0000344 return this->Header.sh_entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000345}
346
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000347template <class ELFT> void RelocationSection<ELFT>::finalize() {
George Rimara07ff662015-12-21 10:12:06 +0000348 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
349 : Out<ELFT>::DynSymTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000350 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
351}
352
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000353template <class ELFT>
354InterpSection<ELFT>::InterpSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000355 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000356 this->Header.sh_size = Config->DynamicLinker.size() + 1;
357 this->Header.sh_addralign = 1;
358}
359
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000360template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1e720b92016-03-13 06:50:34 +0000361 StringRef S = Config->DynamicLinker;
362 memcpy(Buf, S.data(), S.size());
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000363}
364
Rafael Espindola35c6af32015-09-25 17:19:10 +0000365template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000366HashTableSection<ELFT>::HashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000367 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000368 this->Header.sh_entsize = sizeof(Elf_Word);
369 this->Header.sh_addralign = sizeof(Elf_Word);
370}
371
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000372static uint32_t hashSysv(StringRef Name) {
Rui Ueyama5f1eee1a2015-10-15 21:27:17 +0000373 uint32_t H = 0;
374 for (char C : Name) {
375 H = (H << 4) + C;
376 uint32_t G = H & 0xf0000000;
377 if (G)
378 H ^= G >> 24;
379 H &= ~G;
380 }
381 return H;
382}
383
Rui Ueyama0db335f2015-10-07 16:58:54 +0000384template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000385 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000386
George Rimare9e1d322016-02-18 15:17:01 +0000387 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000388 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000389
390 // Create as many buckets as there are symbols.
391 // FIXME: This is simplistic. We can try to optimize it, but implementing
392 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000393 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000394 this->Header.sh_size = NumEntries * sizeof(Elf_Word);
395}
396
397template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000398 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000399 auto *P = reinterpret_cast<Elf_Word *>(Buf);
400 *P++ = NumSymbols; // nbucket
401 *P++ = NumSymbols; // nchain
402
403 Elf_Word *Buckets = P;
404 Elf_Word *Chains = P + NumSymbols;
405
Rafael Espindolae2c24612016-01-29 01:24:25 +0000406 for (const std::pair<SymbolBody *, unsigned> &P :
407 Out<ELFT>::DynSymTab->getSymbols()) {
408 SymbolBody *Body = P.first;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000409 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000410 unsigned I = Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000411 uint32_t Hash = hashSysv(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000412 Chains[I] = Buckets[Hash];
413 Buckets[Hash] = I;
414 }
415}
416
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000417static uint32_t hashGnu(StringRef Name) {
418 uint32_t H = 5381;
419 for (uint8_t C : Name)
420 H = (H << 5) + H + C;
421 return H;
422}
423
424template <class ELFT>
425GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000426 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000427 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000428 this->Header.sh_addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000429}
430
431template <class ELFT>
432unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
433 if (!NumHashed)
434 return 0;
435
436 // These values are prime numbers which are not greater than 2^(N-1) + 1.
437 // In result, for any particular NumHashed we return a prime number
438 // which is not greater than NumHashed.
439 static const unsigned Primes[] = {
440 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
441 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
442
443 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
444 array_lengthof(Primes) - 1)];
445}
446
447// Bloom filter estimation: at least 8 bits for each hashed symbol.
448// GNU Hash table requirement: it should be a power of 2,
449// the minimum value is 1, even for an empty table.
450// Expected results for a 32-bit target:
451// calcMaskWords(0..4) = 1
452// calcMaskWords(5..8) = 2
453// calcMaskWords(9..16) = 4
454// For a 64-bit target:
455// calcMaskWords(0..8) = 1
456// calcMaskWords(9..16) = 2
457// calcMaskWords(17..32) = 4
458template <class ELFT>
459unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
460 if (!NumHashed)
461 return 1;
462 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
463}
464
465template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000466 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000467 NBuckets = calcNBuckets(NumHashed);
468 MaskWords = calcMaskWords(NumHashed);
469 // Second hash shift estimation: just predefined values.
470 Shift2 = ELFT::Is64Bits ? 6 : 5;
471
472 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
473 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header
474 + sizeof(Elf_Off) * MaskWords // Bloom Filter
475 + sizeof(Elf_Word) * NBuckets // Hash Buckets
476 + sizeof(Elf_Word) * NumHashed; // Hash Values
477}
478
479template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
480 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000481 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000482 return;
483 writeBloomFilter(Buf);
484 writeHashTable(Buf);
485}
486
487template <class ELFT>
488void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
489 auto *P = reinterpret_cast<Elf_Word *>(Buf);
490 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000491 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000492 *P++ = MaskWords;
493 *P++ = Shift2;
494 Buf = reinterpret_cast<uint8_t *>(P);
495}
496
497template <class ELFT>
498void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
499 unsigned C = sizeof(Elf_Off) * 8;
500
501 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000502 for (const SymbolData &Sym : Symbols) {
503 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
504 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
505 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000506 Masks[Pos] |= V;
507 }
508 Buf += sizeof(Elf_Off) * MaskWords;
509}
510
511template <class ELFT>
512void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
513 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
514 Elf_Word *Values = Buckets + NBuckets;
515
516 int PrevBucket = -1;
517 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000518 for (const SymbolData &Sym : Symbols) {
519 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000520 assert(PrevBucket <= Bucket);
521 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000522 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000523 PrevBucket = Bucket;
524 if (I > 0)
525 Values[I - 1] |= 1;
526 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000527 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000528 ++I;
529 }
530 if (I > 0)
531 Values[I - 1] |= 1;
532}
533
Rafael Espindola31f88882015-11-02 14:33:11 +0000534static bool includeInGnuHashTable(SymbolBody *B) {
Rui Ueyamac112c1b2016-01-29 02:17:01 +0000535 // Assume that includeInDynsym() is already checked.
Rafael Espindola31f88882015-11-02 14:33:11 +0000536 return !B->isUndefined();
537}
538
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000539// Add symbols to this symbol hash table. Note that this function
540// destructively sort a given vector -- which is needed because
541// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000542template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000543void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000544 std::vector<std::pair<SymbolBody *, size_t>> &V) {
545 auto Mid = std::stable_partition(V.begin(), V.end(),
546 [](std::pair<SymbolBody *, size_t> &P) {
547 return !includeInGnuHashTable(P.first);
548 });
549 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000550 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000551 for (auto I = Mid, E = V.end(); I != E; ++I) {
552 SymbolBody *B = I->first;
553 size_t StrOff = I->second;
554 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
555 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000556
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000557 unsigned NBuckets = calcNBuckets(Symbols.size());
558 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000559 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000560 return L.Hash % NBuckets < R.Hash % NBuckets;
561 });
562
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000563 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000564 for (const SymbolData &Sym : Symbols)
565 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000566}
567
568template <class ELFT>
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000569DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000570 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE),
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000571 SymTab(SymTab) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000572 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000573 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000574 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000575
576 // .dynamic section is not writable on MIPS.
577 // See "Special Section" in Chapter 4 in the following document:
578 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
579 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000580 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000581}
582
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000583template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000584 if (this->Header.sh_size)
585 return; // Already finalized.
586
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000587 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000588 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000589
Rafael Espindolae2c24612016-01-29 01:24:25 +0000590 auto Add = [=](Entry E) { Entries.push_back(E); };
591
592 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000593 // DynStrTab and doing this here allows this function to set DT_STRSZ.
594 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000595 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
596 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rafael Espindolade069362016-01-25 21:32:04 +0000597 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
598 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000599 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
600 if (!Config->SoName.empty())
601 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
602
Rafael Espindolade069362016-01-25 21:32:04 +0000603 Out<ELFT>::DynStrTab->finalize();
604
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000605 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000606 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000607 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
608 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
609 Add({IsRela ? DT_RELAENT : DT_RELENT,
610 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000611 }
George Rimar648a2c32015-10-20 08:54:27 +0000612 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000613 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
614 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
615 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
616 Out<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000617 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000618 }
619
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000620 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
621 Add({DT_SYMENT, sizeof(Elf_Sym)});
622 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
623 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000624 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000625 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000626 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000627 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000628
Rafael Espindolade069362016-01-25 21:32:04 +0000629 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000630 Add({DT_PREINIT_ARRAY, PreInitArraySec});
631 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000632 }
633 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000634 Add({DT_INIT_ARRAY, InitArraySec});
635 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000636 }
637 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000638 Add({DT_FINI_ARRAY, FiniArraySec});
639 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000640 }
641
Rui Ueyama304d1352016-01-25 21:47:25 +0000642 if (SymbolBody *B = SymTab.find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000643 Add({DT_INIT, B});
Rui Ueyama304d1352016-01-25 21:47:25 +0000644 if (SymbolBody *B = SymTab.find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000645 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000646
Rafael Espindolade069362016-01-25 21:32:04 +0000647 uint32_t DtFlags = 0;
648 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000649 if (Config->Bsymbolic)
650 DtFlags |= DF_SYMBOLIC;
651 if (Config->ZNodelete)
652 DtFlags1 |= DF_1_NODELETE;
653 if (Config->ZNow) {
654 DtFlags |= DF_BIND_NOW;
655 DtFlags1 |= DF_1_NOW;
656 }
657 if (Config->ZOrigin) {
658 DtFlags |= DF_ORIGIN;
659 DtFlags1 |= DF_1_ORIGIN;
660 }
661
662 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000663 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000664 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000665 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000666
Ed Mastef5d3cf62016-01-06 15:52:27 +0000667 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000668 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000669
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000670 if (size_t NeedNum = Out<ELFT>::VerNeed->getNeedNum()) {
671 Add({DT_VERSYM, Out<ELFT>::VerSym});
672 Add({DT_VERNEED, Out<ELFT>::VerNeed});
673 Add({DT_VERNEEDNUM, NeedNum});
674 }
675
Igor Kudrin304860a2015-11-12 04:39:49 +0000676 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000677 Add({DT_MIPS_RLD_VERSION, 1});
678 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
679 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
680 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
681 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000682 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000683 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000684 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000685 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
686 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000687 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000688 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000689 }
690
Rafael Espindolade069362016-01-25 21:32:04 +0000691 // +1 for DT_NULL
692 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000693}
694
695template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000696 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
697
Rafael Espindolade069362016-01-25 21:32:04 +0000698 for (const Entry &E : Entries) {
699 P->d_tag = E.Tag;
700 switch (E.Kind) {
701 case Entry::SecAddr:
702 P->d_un.d_ptr = E.OutSec->getVA();
703 break;
704 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000705 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000706 break;
707 case Entry::PlainInt:
708 P->d_un.d_val = E.Val;
709 break;
710 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000711 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000712 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000713}
714
715template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000716EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyamade9777a2016-05-23 16:30:41 +0000717 : OutputSectionBase<ELFT>(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
George Rimarf6bc65a2016-01-15 13:34:52 +0000718
Rui Ueyama95a232e2016-05-23 01:45:05 +0000719// .eh_frame_hdr contains a binary search table of pointers to FDEs.
720// Each entry of the search table consists of two values,
721// the starting PC from where FDEs covers, and the FDE's address.
722// It is sorted by PC.
George Rimarf6bc65a2016-01-15 13:34:52 +0000723template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
724 const endianness E = ELFT::TargetEndianness;
725
Rui Ueyamae75e9332016-05-23 03:00:33 +0000726 // Sort the FDE list by their PC and uniqueify. Usually there is only
727 // one FDE for a PC (i.e. function), but if ICF merges two functions
728 // into one, there can be more than one FDEs pointing to the address.
729 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
730 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
731 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
732 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
Peter Collingbournec98de132016-04-11 16:40:08 +0000733
Rui Ueyama1b2936f2016-05-23 01:31:10 +0000734 Buf[0] = 1;
735 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
736 Buf[2] = DW_EH_PE_udata4;
737 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama3b31e672016-05-23 16:24:16 +0000738 write32<E>(Buf + 4, Out<ELFT>::EhFrame->getVA() - this->getVA() - 4);
Rui Ueyamae75e9332016-05-23 03:00:33 +0000739 write32<E>(Buf + 8, Fdes.size());
George Rimarf6bc65a2016-01-15 13:34:52 +0000740 Buf += 12;
741
Rui Ueyamae75e9332016-05-23 03:00:33 +0000742 uintX_t VA = this->getVA();
743 for (FdeData &Fde : Fdes) {
744 write32<E>(Buf, Fde.Pc - VA);
745 write32<E>(Buf + 4, Fde.FdeVA - VA);
George Rimarf6bc65a2016-01-15 13:34:52 +0000746 Buf += 8;
747 }
748}
749
Rui Ueyamade9777a2016-05-23 16:30:41 +0000750template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
751 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
752 this->Header.sh_size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
753}
754
George Rimarf6bc65a2016-01-15 13:34:52 +0000755template <class ELFT>
Rui Ueyamae75e9332016-05-23 03:00:33 +0000756void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
757 Fdes.push_back({Pc, FdeVA});
George Rimarf6bc65a2016-01-15 13:34:52 +0000758}
759
George Rimarf6bc65a2016-01-15 13:34:52 +0000760template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000761OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
762 : OutputSectionBase<ELFT>(Name, Type, Flags) {
763 if (Type == SHT_RELA)
764 this->Header.sh_entsize = sizeof(Elf_Rela);
765 else if (Type == SHT_REL)
766 this->Header.sh_entsize = sizeof(Elf_Rel);
767}
768
769template <class ELFT> void OutputSection<ELFT>::finalize() {
770 uint32_t Type = this->Header.sh_type;
771 if (Type != SHT_RELA && Type != SHT_REL)
772 return;
773 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
774 // sh_info for SHT_REL[A] sections should contain the section header index of
775 // the section to which the relocation applies.
776 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
777 this->Header.sh_info = S->OutSec->SectionIndex;
778}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000779
780template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000781void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000782 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000783 auto *S = cast<InputSection<ELFT>>(C);
784 Sections.push_back(S);
785 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000786 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000787}
788
Rui Ueyamac4185702016-02-10 23:20:42 +0000789// If an input string is in the form of "foo.N" where N is a number,
790// return N. Otherwise, returns 65536, which is one greater than the
791// lowest priority.
792static int getPriority(StringRef S) {
793 size_t Pos = S.rfind('.');
794 if (Pos == StringRef::npos)
795 return 65536;
796 int V;
797 if (S.substr(Pos + 1).getAsInteger(10, V))
798 return 65536;
799 return V;
800}
801
Rafael Espindola56004c52016-04-07 14:22:09 +0000802template <class ELFT>
803void OutputSection<ELFT>::forEachInputSection(
Rui Ueyama10803512016-05-22 00:25:30 +0000804 std::function<void(InputSectionBase<ELFT> *)> F) {
Rafael Espindola56004c52016-04-07 14:22:09 +0000805 for (InputSection<ELFT> *S : Sections)
806 F(S);
Rui Ueyama5af83682016-02-11 23:41:38 +0000807}
808
Rui Ueyamac4185702016-02-10 23:20:42 +0000809// Sorts input sections by section name suffixes, so that .foo.N comes
810// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000811// We want to keep the original order if the priorities are the same
812// because the compiler keeps the original initialization order in a
813// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000814// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000815template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000816 // Sort sections by priority.
817 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000818 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
819
Rui Ueyamac4185702016-02-10 23:20:42 +0000820 std::vector<Pair> V;
821 for (InputSection<ELFT> *S : Sections)
822 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000823 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000824 Sections.clear();
825 for (Pair &P : V)
826 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000827}
Rui Ueyamac4185702016-02-10 23:20:42 +0000828
Rui Ueyama5af83682016-02-11 23:41:38 +0000829// Returns true if S matches /Filename.?\.o$/.
830static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
831 if (!S.endswith(".o"))
832 return false;
833 S = S.drop_back(2);
834 if (S.endswith(Filename))
835 return true;
836 return !S.empty() && S.drop_back().endswith(Filename);
837}
838
839static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
840static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
841
842// .ctors and .dtors are sorted by this priority from highest to lowest.
843//
844// 1. The section was contained in crtbegin (crtbegin contains
845// some sentinel value in its .ctors and .dtors so that the runtime
846// can find the beginning of the sections.)
847//
848// 2. The section has an optional priority value in the form of ".ctors.N"
849// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
850// they are compared as string rather than number.
851//
852// 3. The section is just ".ctors" or ".dtors".
853//
854// 4. The section was contained in crtend, which contains an end marker.
855//
856// In an ideal world, we don't need this function because .init_array and
857// .ctors are duplicate features (and .init_array is newer.) However, there
858// are too many real-world use cases of .ctors, so we had no choice to
859// support that with this rather ad-hoc semantics.
860template <class ELFT>
861static bool compCtors(const InputSection<ELFT> *A,
862 const InputSection<ELFT> *B) {
863 bool BeginA = isCrtbegin(A->getFile()->getName());
864 bool BeginB = isCrtbegin(B->getFile()->getName());
865 if (BeginA != BeginB)
866 return BeginA;
867 bool EndA = isCrtend(A->getFile()->getName());
868 bool EndB = isCrtend(B->getFile()->getName());
869 if (EndA != EndB)
870 return EndB;
871 StringRef X = A->getSectionName();
872 StringRef Y = B->getSectionName();
873 assert(X.startswith(".ctors") || X.startswith(".dtors"));
874 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
875 X = X.substr(6);
876 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000877 if (X.empty() && Y.empty())
878 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000879 return X < Y;
880}
881
882// Sorts input sections by the special rules for .ctors and .dtors.
883// Unfortunately, the rules are different from the one for .{init,fini}_array.
884// Read the comment above.
885template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
886 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +0000887}
888
George Rimare2ee72b2016-02-26 14:48:31 +0000889static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
890 size_t I = 0;
891 for (; I + A.size() < Size; I += A.size())
892 memcpy(Buf + I, A.data(), A.size());
893 memcpy(Buf + I, A.data(), Size - I);
894}
895
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000896template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama07320e42016-04-20 20:13:41 +0000897 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
George Rimare2ee72b2016-02-26 14:48:31 +0000898 if (!Filler.empty())
899 fill(Buf, this->getSize(), Filler);
Rui Ueyamae9809502016-03-11 04:23:12 +0000900 if (Config->Threads) {
901 parallel_for_each(Sections.begin(), Sections.end(),
902 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
903 } else {
904 for (InputSection<ELFT> *C : Sections)
905 C->writeTo(Buf);
906 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000907}
908
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000909template <class ELFT>
Rui Ueyamaf86cb902016-05-23 15:12:41 +0000910EhOutputSection<ELFT>::EhOutputSection()
Rui Ueyama3b31e672016-05-23 16:24:16 +0000911 : OutputSectionBase<ELFT>(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000912
913template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000914void EhOutputSection<ELFT>::forEachInputSection(
Rafael Espindola56004c52016-04-07 14:22:09 +0000915 std::function<void(InputSectionBase<ELFT> *)> F) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000916 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola56004c52016-04-07 14:22:09 +0000917 F(S);
918}
919
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000920// Returns the first relocation that points to a region
921// between Begin and Begin+Size.
922template <class IntTy, class RelTy>
923static const RelTy *getReloc(IntTy Begin, IntTy Size, ArrayRef<RelTy> Rels) {
924 size_t I = 0;
925 size_t E = Rels.size();
926 while (I != E && Rels[I].r_offset < Begin)
927 ++I;
928 if (I == E || Begin + Size <= Rels[I].r_offset)
929 return nullptr;
930 return &Rels[I];
931}
932
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000933// Search for an existing CIE record or create a new one.
934// CIE records from input object files are uniquified by their contents
935// and where their relocations point to.
936template <class ELFT>
937template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000938CieRecord *EhOutputSection<ELFT>::addCie(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000939 EhInputSection<ELFT> *Sec,
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000940 ArrayRef<RelTy> Rels) {
941 const endianness E = ELFT::TargetEndianness;
942 if (read32<E>(Piece.Data.data() + 4) != 0)
943 fatal("CIE expected at beginning of .eh_frame: " + Sec->getSectionName());
944
945 SymbolBody *Personality = nullptr;
946 if (const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels))
947 Personality = &Sec->getFile()->getRelocTargetSym(*Rel);
948
949 // Search for an existing CIE by CIE contents/relocation target pair.
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000950 CieRecord *Cie = &CieMap[{Piece.Data, Personality}];
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000951
952 // If not found, create a new one.
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000953 if (Cie->Piece == nullptr) {
954 Cie->Piece = &Piece;
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000955 Cies.push_back(Cie);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000956 }
957 return Cie;
958}
959
960template <class ELFT> static void validateFde(SectionPiece &Piece) {
961 // We assume that all FDEs refer the first CIE in the same object file.
962 const endianness E = ELFT::TargetEndianness;
963 uint32_t ID = read32<E>(Piece.Data.data() + 4);
964 if (Piece.InputOff + 4 - ID != 0)
965 fatal("invalid CIE reference");
966}
967
968// There is one FDE per function. Returns true if a given FDE
969// points to a live function.
970template <class ELFT>
971template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000972bool EhOutputSection<ELFT>::isFdeLive(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000973 EhInputSection<ELFT> *Sec,
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000974 ArrayRef<RelTy> Rels) {
975 const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels);
976 if (!Rel)
977 fatal("FDE doesn't reference another section");
978 SymbolBody &B = Sec->getFile()->getRelocTargetSym(*Rel);
979 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
980 if (!D || !D->Section)
981 return false;
982 InputSectionBase<ELFT> *Target = D->Section->Repl;
983 return Target && Target->Live;
984}
985
986// .eh_frame is a sequence of CIE or FDE records. In general, there
987// is one CIE record per input object file which is followed by
988// a list of FDEs. This function searches an existing CIE or create a new
989// one and associates FDEs to the CIE.
Rui Ueyamac0c92602016-02-05 22:56:03 +0000990template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +0000991template <class RelTy>
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000992void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +0000993 ArrayRef<RelTy> Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000994 SectionPiece &CiePiece = Sec->Pieces[0];
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000995 CieRecord *Cie = addCie(CiePiece, Sec, Rels);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000996
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000997 for (size_t I = 1, End = Sec->Pieces.size(); I != End; ++I) {
998 SectionPiece &FdePiece = Sec->Pieces[I];
999 validateFde<ELFT>(FdePiece);
1000 if (!isFdeLive(FdePiece, Sec, Rels))
1001 continue;
Rui Ueyamae2060aa2016-05-22 23:52:56 +00001002 Cie->FdePieces.push_back(&FdePiece);
Rui Ueyamade9777a2016-05-23 16:30:41 +00001003 NumFdes++;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001004 }
1005}
1006
1007template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001008void EhOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001009 auto *Sec = cast<EhInputSection<ELFT>>(C);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001010 Sec->OutSec = this;
1011 this->updateAlign(Sec->Align);
1012 Sections.push_back(Sec);
1013
1014 // .eh_frame is a sequence of CIE or FDE records. This function
1015 // splits it into pieces so that we can call
1016 // SplitInputSection::getSectionPiece on the section.
Rui Ueyama88abd9b2016-05-22 23:53:00 +00001017 Sec->split();
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001018 if (Sec->Pieces.empty())
1019 return;
1020
1021 if (const Elf_Shdr *RelSec = Sec->RelocSection) {
1022 ELFFile<ELFT> &Obj = Sec->getFile()->getObj();
1023 if (RelSec->sh_type == SHT_RELA)
1024 addSectionAux(Sec, Obj.relas(RelSec));
1025 else
1026 addSectionAux(Sec, Obj.rels(RelSec));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001027 return;
1028 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001029 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001030}
1031
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001032template <class ELFT>
Rui Ueyama644ac652016-05-22 00:17:11 +00001033static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1034 memcpy(Buf, D.data(), D.size());
Rui Ueyamac0449a62016-05-21 18:10:13 +00001035
1036 // Fix the size field. -4 since size does not include the size field itself.
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001037 const endianness E = ELFT::TargetEndianness;
Rui Ueyama644ac652016-05-22 00:17:11 +00001038 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
Rafael Espindola56004c52016-04-07 14:22:09 +00001039}
1040
Rui Ueyama1e479c22016-05-23 15:07:59 +00001041template <class ELFT> void EhOutputSection<ELFT>::finalize() {
Rafael Espindola56004c52016-04-07 14:22:09 +00001042 if (Finalized)
1043 return;
1044 Finalized = true;
1045
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001046 size_t Off = 0;
1047 for (CieRecord *Cie : Cies) {
1048 Cie->Piece->OutputOff = Off;
1049 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001050
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001051 for (SectionPiece *Fde : Cie->FdePieces) {
1052 Fde->OutputOff = Off;
1053 Off += alignTo(Fde->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001054 }
1055 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001056 this->Header.sh_size = Off;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001057}
1058
Rui Ueyamae75e9332016-05-23 03:00:33 +00001059template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1060 const endianness E = ELFT::TargetEndianness;
1061 switch (Size) {
1062 case DW_EH_PE_udata2:
1063 return read16<E>(Buf);
1064 case DW_EH_PE_udata4:
1065 return read32<E>(Buf);
1066 case DW_EH_PE_udata8:
1067 return read64<E>(Buf);
1068 case DW_EH_PE_absptr:
1069 if (ELFT::Is64Bits)
1070 return read64<E>(Buf);
1071 return read32<E>(Buf);
1072 }
1073 fatal("unknown FDE size encoding");
1074}
1075
1076// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1077// We need it to create .eh_frame_hdr section.
1078template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001079typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
Rui Ueyamae75e9332016-05-23 03:00:33 +00001080 uint8_t Enc) {
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001081 // The starting address to which this FDE applies is
Rui Ueyamae75e9332016-05-23 03:00:33 +00001082 // stored at FDE + 8 byte.
1083 size_t Off = FdeOff + 8;
1084 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1085 if ((Enc & 0x70) == DW_EH_PE_absptr)
1086 return Addr;
1087 if ((Enc & 0x70) == DW_EH_PE_pcrel)
1088 return Addr + this->getVA() + Off;
1089 fatal("unknown FDE size relative encoding");
1090}
1091
Rui Ueyama1e479c22016-05-23 15:07:59 +00001092template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001093 const endianness E = ELFT::TargetEndianness;
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001094 for (CieRecord *Cie : Cies) {
1095 size_t CieOffset = Cie->Piece->OutputOff;
1096 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->Data);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001097
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001098 for (SectionPiece *Fde : Cie->FdePieces) {
1099 size_t Off = Fde->OutputOff;
1100 writeCieFde<ELFT>(Buf + Off, Fde->Data);
Rafael Espindola56004c52016-04-07 14:22:09 +00001101
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001102 // FDE's second word should have the offset to an associated CIE.
1103 // Write it.
1104 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001105 }
1106 }
1107
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001108 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola22ef9562016-04-13 01:40:19 +00001109 S->relocate(Buf, nullptr);
Rui Ueyamae75e9332016-05-23 03:00:33 +00001110
1111 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001112 // to get a FDE from an address to which FDE is applied. So here
Rui Ueyamae75e9332016-05-23 03:00:33 +00001113 // we obtain two addresses and pass them to EhFrameHdr object.
Rui Ueyama3b31e672016-05-23 16:24:16 +00001114 if (Out<ELFT>::EhFrameHdr) {
1115 for (CieRecord *Cie : Cies) {
Rui Ueyama6de2e682016-05-24 02:08:38 +00001116 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->Data);
Rui Ueyama3b31e672016-05-23 16:24:16 +00001117 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyama6de2e682016-05-24 02:08:38 +00001118 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rui Ueyama3b31e672016-05-23 16:24:16 +00001119 uintX_t FdeVA = this->getVA() + Fde->OutputOff;
1120 Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1121 }
Rui Ueyamae75e9332016-05-23 03:00:33 +00001122 }
1123 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001124}
1125
1126template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001127MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001128 uintX_t Flags, uintX_t Alignment)
1129 : OutputSectionBase<ELFT>(Name, Type, Flags),
1130 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001131
1132template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001133 if (shouldTailMerge()) {
1134 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001135 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001136 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001137 }
Rui Ueyama31f9f612016-05-06 00:52:08 +00001138 for (const std::pair<CachedHash<StringRef>, size_t> &P : Builder.getMap()) {
1139 StringRef Data = P.first.Val;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001140 memcpy(Buf + P.second, Data.data(), Data.size());
1141 }
1142}
1143
Rui Ueyama34dc99e2016-05-22 01:15:32 +00001144static StringRef toStringRef(ArrayRef<uint8_t> A) {
1145 return {(const char *)A.data(), A.size()};
1146}
1147
Rafael Espindolac159c962015-10-19 21:00:02 +00001148template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001149void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama10803512016-05-22 00:25:30 +00001150 auto *Sec = cast<MergeInputSection<ELFT>>(C);
1151 Sec->OutSec = this;
1152 this->updateAlign(Sec->Align);
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001153 this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize;
Rafael Espindolac159c962015-10-19 21:00:02 +00001154
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001155 bool IsString = this->Header.sh_flags & SHF_STRINGS;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001156
Rui Ueyamab7eda282016-05-24 02:10:28 +00001157 for (SectionPiece &Piece : Sec->Pieces) {
Rui Ueyama3ea87272016-05-22 00:13:04 +00001158 if (!Piece.Live)
Rafael Espindola0b9531c2016-04-22 22:09:35 +00001159 continue;
Rui Ueyama34dc99e2016-05-22 01:15:32 +00001160 uintX_t OutputOffset = Builder.add(toStringRef(Piece.Data));
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001161 if (!IsString || !shouldTailMerge())
1162 Piece.OutputOff = OutputOffset;
Rafael Espindolac159c962015-10-19 21:00:02 +00001163 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001164}
1165
1166template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001167unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1168 return Builder.getOffset(Val);
1169}
1170
1171template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1172 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1173}
1174
1175template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1176 if (shouldTailMerge())
1177 Builder.finalize();
1178 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001179}
1180
1181template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001182StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001183 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1184 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001185 Dynamic(Dynamic) {
1186 this->Header.sh_addralign = 1;
1187}
1188
Rafael Espindolae2c24612016-01-29 01:24:25 +00001189// Adds a string to the string table. If HashIt is true we hash and check for
1190// duplicates. It is optional because the name of global symbols are already
1191// uniqued and hashing them again has a big cost for a small value: uniquing
1192// them with some other string that happens to be the same.
1193template <class ELFT>
1194unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1195 if (HashIt) {
1196 auto R = StringMap.insert(std::make_pair(S, Size));
1197 if (!R.second)
1198 return R.first->second;
1199 }
1200 unsigned Ret = Size;
1201 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001202 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001203 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001204}
1205
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001206template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001207 // ELF string tables start with NUL byte, so advance the pointer by one.
1208 ++Buf;
1209 for (StringRef S : Strings) {
1210 memcpy(Buf, S.data(), S.size());
1211 Buf += S.size() + 1;
1212 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001213}
1214
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001215template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001216SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001217 SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001218 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1219 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001220 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001221 StrTabSec(StrTabSec), Table(Table) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001222 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001223 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001224}
1225
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001226// Orders symbols according to their positions in the GOT,
1227// in compliance with MIPS ABI rules.
1228// See "Global Offset Table" in Chapter 5 in the following document
1229// for detailed description:
1230// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001231static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1232 const std::pair<SymbolBody *, unsigned> &R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001233 // Sort entries related to non-local preemptible symbols by GOT indexes.
1234 // All other entries go to the first part of GOT in arbitrary order.
1235 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible();
1236 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible();
1237 if (LIsInLocalGot || RIsInLocalGot)
1238 return !RIsInLocalGot;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001239 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001240}
1241
Rafael Espindolabadd3972016-04-08 15:30:56 +00001242static uint8_t getSymbolBinding(SymbolBody *Body) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001243 Symbol *S = Body->symbol();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001244 uint8_t Visibility = S->Visibility;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001245 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1246 return STB_LOCAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001247 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
Rafael Espindolabadd3972016-04-08 15:30:56 +00001248 return STB_GLOBAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001249 return S->Binding;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001250}
1251
Rui Ueyama0db335f2015-10-07 16:58:54 +00001252template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001253 if (this->Header.sh_size)
1254 return; // Already finalized.
1255
Rui Ueyama0db335f2015-10-07 16:58:54 +00001256 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001257 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001258 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001259
George Rimar58941ee2016-02-25 08:23:37 +00001260 if (Config->Relocatable) {
1261 size_t I = NumLocals;
1262 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1263 P.first->DynsymIndex = ++I;
1264 return;
1265 }
1266
Igor Kudrinab665fc2015-10-20 21:47:58 +00001267 if (!StrTabSec.isDynamic()) {
1268 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001269 [](const std::pair<SymbolBody *, unsigned> &L,
1270 const std::pair<SymbolBody *, unsigned> &R) {
1271 return getSymbolBinding(L.first) == STB_LOCAL &&
1272 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001273 });
1274 return;
1275 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001276 if (Out<ELFT>::GnuHashTab)
1277 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1278 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001279 else if (Config->EMachine == EM_MIPS)
1280 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001281 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001282 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001283 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001284}
1285
1286template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001287void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1288 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001289}
1290
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001291template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001292 Buf += sizeof(Elf_Sym);
1293
1294 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1295 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001296 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1297 writeLocalSymbols(Buf);
1298
1299 writeGlobalSymbols(Buf);
1300}
1301
1302template <class ELFT>
1303void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1304 // Iterate over all input object files to copy their local symbols
1305 // to the output symbol table pointed by Buf.
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001306 for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001307 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1308 File->KeptLocalSyms) {
1309 const DefinedRegular<ELFT> &Body = *P.first;
1310 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001311 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001312
1313 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001314 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001315 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001316 } else {
Rafael Espindolac159c962015-10-19 21:00:02 +00001317 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1318 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001319 ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001320 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001321 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001322 ESym->st_size = Body.template getSize<ELFT>();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001323 ESym->setBindingAndType(STB_LOCAL, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001324 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001325 }
1326 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001327}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001328
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001329template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001330void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001331 // Write the internal symbol table contents to the output symbol table
1332 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001333 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001334 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001335 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001336 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001337
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001338 uint8_t Type = Body->Type;
1339 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001340
Igor Kudrin853b88d2015-10-20 20:52:14 +00001341 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001342 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001343 ESym->st_name = StrOff;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001344 ESym->setVisibility(Body->symbol()->Visibility);
Rui Ueyamab5a69702016-02-01 21:00:35 +00001345 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001346
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001347 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001348 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001349 else if (isa<DefinedRegular<ELFT>>(Body))
1350 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001351
1352 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1353 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1354 // distinguish such symbols and MIPS lazy-binding stubs.
1355 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1356 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1357 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001358 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001359 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001360 }
1361}
1362
Igor Kudrin853b88d2015-10-20 20:52:14 +00001363template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001364const OutputSectionBase<ELFT> *
1365SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1366 switch (Sym->kind()) {
1367 case SymbolBody::DefinedSyntheticKind:
Peter Collingbourne6a422592016-05-03 01:21:08 +00001368 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001369 case SymbolBody::DefinedRegularKind: {
Rafael Espindola5ffa13c2016-04-15 00:15:02 +00001370 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001371 if (D.Section)
1372 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001373 break;
1374 }
1375 case SymbolBody::DefinedCommonKind:
1376 return Out<ELFT>::Bss;
1377 case SymbolBody::SharedKind:
1378 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1379 return Out<ELFT>::Bss;
1380 break;
Peter Collingbourne60976ed2016-04-27 00:05:06 +00001381 case SymbolBody::UndefinedKind:
Rui Ueyamaf8baa662016-04-07 19:24:51 +00001382 case SymbolBody::LazyArchiveKind:
1383 case SymbolBody::LazyObjectKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001384 break;
1385 case SymbolBody::DefinedBitcodeKind:
Davide Italianof6523ae2016-03-29 02:20:10 +00001386 llvm_unreachable("should have been replaced");
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001387 }
1388 return nullptr;
1389}
1390
1391template <class ELFT>
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001392VersionTableSection<ELFT>::VersionTableSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001393 : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001394 this->Header.sh_addralign = sizeof(uint16_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001395}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001396
1397template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1398 this->Header.sh_size =
1399 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
1400 this->Header.sh_entsize = sizeof(Elf_Versym);
1401}
1402
1403template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1404 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1405 for (const std::pair<SymbolBody *, size_t> &P :
1406 Out<ELFT>::DynSymTab->getSymbols()) {
1407 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(P.first))
1408 OutVersym->vs_index = SS->VersionId;
1409 else
1410 // The reserved identifier for a non-versioned global symbol.
1411 OutVersym->vs_index = 1;
1412 ++OutVersym;
1413 }
1414}
1415
1416template <class ELFT>
1417VersionNeedSection<ELFT>::VersionNeedSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001418 : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001419 this->Header.sh_addralign = sizeof(uint32_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001420}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001421
1422template <class ELFT>
1423void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1424 if (!SS->Verdef) {
1425 // The reserved identifier for a non-versioned global symbol.
1426 SS->VersionId = 1;
1427 return;
1428 }
1429 SharedFile<ELFT> *F = SS->File;
1430 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1431 // to create one by adding it to our needed list and creating a dynstr entry
1432 // for the soname.
1433 if (F->VerdefMap.empty())
1434 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1435 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1436 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1437 // prepare to create one by allocating a version identifier and creating a
1438 // dynstr entry for the version name.
1439 if (NV.Index == 0) {
1440 NV.StrTab = Out<ELFT>::DynStrTab->addString(
1441 SS->File->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1442 NV.Index = NextIndex++;
1443 }
1444 SS->VersionId = NV.Index;
1445}
1446
1447template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1448 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1449 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1450 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1451
1452 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1453 // Create an Elf_Verneed for this DSO.
1454 Verneed->vn_version = 1;
1455 Verneed->vn_cnt = P.first->VerdefMap.size();
1456 Verneed->vn_file = P.second;
1457 Verneed->vn_aux =
1458 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1459 Verneed->vn_next = sizeof(Elf_Verneed);
1460 ++Verneed;
1461
1462 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1463 // VerdefMap, which will only contain references to needed version
1464 // definitions. Each Elf_Vernaux is based on the information contained in
1465 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1466 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1467 // data structures within a single input file.
1468 for (auto &NV : P.first->VerdefMap) {
1469 Vernaux->vna_hash = NV.first->vd_hash;
1470 Vernaux->vna_flags = 0;
1471 Vernaux->vna_other = NV.second.Index;
1472 Vernaux->vna_name = NV.second.StrTab;
1473 Vernaux->vna_next = sizeof(Elf_Vernaux);
1474 ++Vernaux;
1475 }
1476
1477 Vernaux[-1].vna_next = 0;
1478 }
1479 Verneed[-1].vn_next = 0;
1480}
1481
1482template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1483 this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1484 this->Header.sh_info = Needed.size();
1485 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1486 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1487 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1488 this->Header.sh_size = Size;
1489}
1490
1491template <class ELFT>
Rui Ueyama3a41be22016-04-07 22:49:21 +00001492BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1493 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1494 HashSize(HashSize) {
1495 // 16 bytes for the note section header.
1496 this->Header.sh_size = 16 + HashSize;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001497}
1498
1499template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1500 const endianness E = ELFT::TargetEndianness;
1501 write32<E>(Buf, 4); // Name size
Rui Ueyama3a41be22016-04-07 22:49:21 +00001502 write32<E>(Buf + 4, HashSize); // Content size
Rui Ueyama634ddf02016-03-11 20:51:53 +00001503 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1504 memcpy(Buf + 12, "GNU", 4); // Name string
1505 HashBuf = Buf + 16;
1506}
1507
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001508template <class ELFT>
1509void BuildIdFnv1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
Rui Ueyama634ddf02016-03-11 20:51:53 +00001510 const endianness E = ELFT::TargetEndianness;
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001511
1512 // 64-bit FNV-1 hash
1513 uint64_t Hash = 0xcbf29ce484222325;
1514 for (ArrayRef<uint8_t> Buf : Bufs) {
1515 for (uint8_t B : Buf) {
1516 Hash *= 0x100000001b3;
1517 Hash ^= B;
1518 }
1519 }
Rui Ueyama3a41be22016-04-07 22:49:21 +00001520 write64<E>(this->HashBuf, Hash);
1521}
1522
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001523template <class ELFT>
1524void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1525 llvm::MD5 Hash;
1526 for (ArrayRef<uint8_t> Buf : Bufs)
1527 Hash.update(Buf);
Rui Ueyama3a41be22016-04-07 22:49:21 +00001528 MD5::MD5Result Res;
1529 Hash.final(Res);
1530 memcpy(this->HashBuf, Res, 16);
Rui Ueyama634ddf02016-03-11 20:51:53 +00001531}
1532
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001533template <class ELFT>
1534void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1535 llvm::SHA1 Hash;
1536 for (ArrayRef<uint8_t> Buf : Bufs)
1537 Hash.update(Buf);
Rui Ueyamad86ec302016-04-07 23:51:56 +00001538 memcpy(this->HashBuf, Hash.final().data(), 20);
1539}
1540
Rui Ueyama634ddf02016-03-11 20:51:53 +00001541template <class ELFT>
Rui Ueyama9194db72016-05-13 21:55:56 +00001542BuildIdHexstring<ELFT>::BuildIdHexstring()
1543 : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
1544
1545template <class ELFT>
1546void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1547 memcpy(this->HashBuf, Config->BuildIdVector.data(),
1548 Config->BuildIdVector.size());
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);
Simon Atanasyan4ee29182016-04-27 05:31:28 +00001562 R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
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
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001573template <class ELFT>
1574MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection()
1575 : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS,
1576 SHF_ALLOC | SHF_MIPS_NOSTRIP) {
1577 this->Header.sh_addralign = 8;
1578 this->Header.sh_entsize = 1;
1579 this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1580}
1581
1582template <class ELFT>
1583void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1584 auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf);
1585 Opt->kind = ODK_REGINFO;
1586 Opt->size = this->Header.sh_size;
1587 Opt->section = 0;
1588 Opt->info = 0;
1589 auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt));
1590 Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1591 Reg->ri_gprmask = GprMask;
1592}
1593
1594template <class ELFT>
1595void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1596 auto *S = cast<MipsOptionsInputSection<ELFT>>(C);
1597 if (S->Reginfo)
1598 GprMask |= S->Reginfo->ri_gprmask;
1599}
1600
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001601namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001602namespace elf {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001603template class OutputSectionBase<ELF32LE>;
1604template class OutputSectionBase<ELF32BE>;
1605template class OutputSectionBase<ELF64LE>;
1606template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001607
George Rimarf6bc65a2016-01-15 13:34:52 +00001608template class EhFrameHeader<ELF32LE>;
1609template class EhFrameHeader<ELF32BE>;
1610template class EhFrameHeader<ELF64LE>;
1611template class EhFrameHeader<ELF64BE>;
1612
George Rimar648a2c32015-10-20 08:54:27 +00001613template class GotPltSection<ELF32LE>;
1614template class GotPltSection<ELF32BE>;
1615template class GotPltSection<ELF64LE>;
1616template class GotPltSection<ELF64BE>;
1617
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001618template class GotSection<ELF32LE>;
1619template class GotSection<ELF32BE>;
1620template class GotSection<ELF64LE>;
1621template class GotSection<ELF64BE>;
1622
1623template class PltSection<ELF32LE>;
1624template class PltSection<ELF32BE>;
1625template class PltSection<ELF64LE>;
1626template class PltSection<ELF64BE>;
1627
1628template class RelocationSection<ELF32LE>;
1629template class RelocationSection<ELF32BE>;
1630template class RelocationSection<ELF64LE>;
1631template class RelocationSection<ELF64BE>;
1632
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001633template class InterpSection<ELF32LE>;
1634template class InterpSection<ELF32BE>;
1635template class InterpSection<ELF64LE>;
1636template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001637
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001638template class GnuHashTableSection<ELF32LE>;
1639template class GnuHashTableSection<ELF32BE>;
1640template class GnuHashTableSection<ELF64LE>;
1641template class GnuHashTableSection<ELF64BE>;
1642
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001643template class HashTableSection<ELF32LE>;
1644template class HashTableSection<ELF32BE>;
1645template class HashTableSection<ELF64LE>;
1646template class HashTableSection<ELF64BE>;
1647
1648template class DynamicSection<ELF32LE>;
1649template class DynamicSection<ELF32BE>;
1650template class DynamicSection<ELF64LE>;
1651template class DynamicSection<ELF64BE>;
1652
1653template class OutputSection<ELF32LE>;
1654template class OutputSection<ELF32BE>;
1655template class OutputSection<ELF64LE>;
1656template class OutputSection<ELF64BE>;
1657
Rui Ueyama1e479c22016-05-23 15:07:59 +00001658template class EhOutputSection<ELF32LE>;
1659template class EhOutputSection<ELF32BE>;
1660template class EhOutputSection<ELF64LE>;
1661template class EhOutputSection<ELF64BE>;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001662
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001663template class MipsReginfoOutputSection<ELF32LE>;
1664template class MipsReginfoOutputSection<ELF32BE>;
1665template class MipsReginfoOutputSection<ELF64LE>;
1666template class MipsReginfoOutputSection<ELF64BE>;
1667
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001668template class MipsOptionsOutputSection<ELF32LE>;
1669template class MipsOptionsOutputSection<ELF32BE>;
1670template class MipsOptionsOutputSection<ELF64LE>;
1671template class MipsOptionsOutputSection<ELF64BE>;
1672
Rafael Espindolac159c962015-10-19 21:00:02 +00001673template class MergeOutputSection<ELF32LE>;
1674template class MergeOutputSection<ELF32BE>;
1675template class MergeOutputSection<ELF64LE>;
1676template class MergeOutputSection<ELF64BE>;
1677
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001678template class StringTableSection<ELF32LE>;
1679template class StringTableSection<ELF32BE>;
1680template class StringTableSection<ELF64LE>;
1681template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001682
1683template class SymbolTableSection<ELF32LE>;
1684template class SymbolTableSection<ELF32BE>;
1685template class SymbolTableSection<ELF64LE>;
1686template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001687
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001688template class VersionTableSection<ELF32LE>;
1689template class VersionTableSection<ELF32BE>;
1690template class VersionTableSection<ELF64LE>;
1691template class VersionTableSection<ELF64BE>;
1692
1693template class VersionNeedSection<ELF32LE>;
1694template class VersionNeedSection<ELF32BE>;
1695template class VersionNeedSection<ELF64LE>;
1696template class VersionNeedSection<ELF64BE>;
1697
Rui Ueyama634ddf02016-03-11 20:51:53 +00001698template class BuildIdSection<ELF32LE>;
1699template class BuildIdSection<ELF32BE>;
1700template class BuildIdSection<ELF64LE>;
1701template class BuildIdSection<ELF64BE>;
Rui Ueyama3a41be22016-04-07 22:49:21 +00001702
1703template class BuildIdFnv1<ELF32LE>;
1704template class BuildIdFnv1<ELF32BE>;
1705template class BuildIdFnv1<ELF64LE>;
1706template class BuildIdFnv1<ELF64BE>;
1707
1708template class BuildIdMd5<ELF32LE>;
1709template class BuildIdMd5<ELF32BE>;
1710template class BuildIdMd5<ELF64LE>;
1711template class BuildIdMd5<ELF64BE>;
Rui Ueyamad86ec302016-04-07 23:51:56 +00001712
1713template class BuildIdSha1<ELF32LE>;
1714template class BuildIdSha1<ELF32BE>;
1715template class BuildIdSha1<ELF64LE>;
1716template class BuildIdSha1<ELF64BE>;
Rui Ueyama9194db72016-05-13 21:55:56 +00001717
1718template class BuildIdHexstring<ELF32LE>;
1719template class BuildIdHexstring<ELF32BE>;
1720template class BuildIdHexstring<ELF64LE>;
1721template class BuildIdHexstring<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001722}
1723}