blob: 8998968d8c901264b3c720270fe92f85e4232f67 [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) {
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000148 if (Sym.GlobalDynIndex != -1U)
George Rimar90cd0a82015-12-01 19:20:26 +0000149 return false;
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000150 Sym.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 {
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000190 return this->getVA() + B.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 {
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000196 return B.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
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000534// Add symbols to this symbol hash table. Note that this function
535// destructively sort a given vector -- which is needed because
536// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000537template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000538void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000539 std::vector<std::pair<SymbolBody *, size_t>> &V) {
540 auto Mid = std::stable_partition(V.begin(), V.end(),
541 [](std::pair<SymbolBody *, size_t> &P) {
George Rimar71a0a402016-06-08 12:57:14 +0000542 return P.first->isUndefined();
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000543 });
544 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000545 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000546 for (auto I = Mid, E = V.end(); I != E; ++I) {
547 SymbolBody *B = I->first;
548 size_t StrOff = I->second;
549 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
550 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000551
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000552 unsigned NBuckets = calcNBuckets(Symbols.size());
553 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000554 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000555 return L.Hash % NBuckets < R.Hash % NBuckets;
556 });
557
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000558 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000559 for (const SymbolData &Sym : Symbols)
560 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000561}
562
563template <class ELFT>
Rui Ueyamaace4f902016-05-24 04:25:47 +0000564DynamicSection<ELFT>::DynamicSection()
565 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000566 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000567 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000568 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000569
570 // .dynamic section is not writable on MIPS.
571 // See "Special Section" in Chapter 4 in the following document:
572 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
573 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000574 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000575}
576
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000577template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000578 if (this->Header.sh_size)
579 return; // Already finalized.
580
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000581 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000582 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000583
Rafael Espindolae2c24612016-01-29 01:24:25 +0000584 auto Add = [=](Entry E) { Entries.push_back(E); };
585
586 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000587 // DynStrTab and doing this here allows this function to set DT_STRSZ.
588 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000589 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
590 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rui Ueyamaace4f902016-05-24 04:25:47 +0000591 for (const std::unique_ptr<SharedFile<ELFT>> &F :
592 Symtab<ELFT>::X->getSharedFiles())
Rafael Espindolade069362016-01-25 21:32:04 +0000593 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000594 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
595 if (!Config->SoName.empty())
596 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
597
Rafael Espindolade069362016-01-25 21:32:04 +0000598 Out<ELFT>::DynStrTab->finalize();
599
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000600 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000601 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000602 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
603 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
604 Add({IsRela ? DT_RELAENT : DT_RELENT,
605 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000606 }
George Rimar648a2c32015-10-20 08:54:27 +0000607 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000608 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
609 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
610 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
611 Out<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000612 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000613 }
614
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000615 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
616 Add({DT_SYMENT, sizeof(Elf_Sym)});
617 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
618 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000619 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000620 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000621 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000622 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000623
Rafael Espindolade069362016-01-25 21:32:04 +0000624 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000625 Add({DT_PREINIT_ARRAY, PreInitArraySec});
626 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000627 }
628 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000629 Add({DT_INIT_ARRAY, InitArraySec});
630 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000631 }
632 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000633 Add({DT_FINI_ARRAY, FiniArraySec});
634 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000635 }
636
Rui Ueyamaace4f902016-05-24 04:25:47 +0000637 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000638 Add({DT_INIT, B});
Rui Ueyamaace4f902016-05-24 04:25:47 +0000639 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000640 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000641
Rafael Espindolade069362016-01-25 21:32:04 +0000642 uint32_t DtFlags = 0;
643 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000644 if (Config->Bsymbolic)
645 DtFlags |= DF_SYMBOLIC;
646 if (Config->ZNodelete)
647 DtFlags1 |= DF_1_NODELETE;
648 if (Config->ZNow) {
649 DtFlags |= DF_BIND_NOW;
650 DtFlags1 |= DF_1_NOW;
651 }
652 if (Config->ZOrigin) {
653 DtFlags |= DF_ORIGIN;
654 DtFlags1 |= DF_1_ORIGIN;
655 }
656
657 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000658 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000659 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000660 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000661
Ed Mastef5d3cf62016-01-06 15:52:27 +0000662 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000663 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000664
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000665 if (size_t NeedNum = Out<ELFT>::VerNeed->getNeedNum()) {
666 Add({DT_VERSYM, Out<ELFT>::VerSym});
667 Add({DT_VERNEED, Out<ELFT>::VerNeed});
668 Add({DT_VERNEEDNUM, NeedNum});
669 }
670
Igor Kudrin304860a2015-11-12 04:39:49 +0000671 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000672 Add({DT_MIPS_RLD_VERSION, 1});
673 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
674 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
675 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
676 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000677 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000678 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000679 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000680 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
681 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000682 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000683 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000684 }
685
Rafael Espindolade069362016-01-25 21:32:04 +0000686 // +1 for DT_NULL
687 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000688}
689
690template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000691 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
692
Rafael Espindolade069362016-01-25 21:32:04 +0000693 for (const Entry &E : Entries) {
694 P->d_tag = E.Tag;
695 switch (E.Kind) {
696 case Entry::SecAddr:
697 P->d_un.d_ptr = E.OutSec->getVA();
698 break;
699 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000700 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000701 break;
702 case Entry::PlainInt:
703 P->d_un.d_val = E.Val;
704 break;
705 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000706 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000707 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000708}
709
710template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000711EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyamade9777a2016-05-23 16:30:41 +0000712 : OutputSectionBase<ELFT>(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
George Rimarf6bc65a2016-01-15 13:34:52 +0000713
Rui Ueyama95a232e2016-05-23 01:45:05 +0000714// .eh_frame_hdr contains a binary search table of pointers to FDEs.
715// Each entry of the search table consists of two values,
716// the starting PC from where FDEs covers, and the FDE's address.
717// It is sorted by PC.
George Rimarf6bc65a2016-01-15 13:34:52 +0000718template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
719 const endianness E = ELFT::TargetEndianness;
720
Rui Ueyamae75e9332016-05-23 03:00:33 +0000721 // Sort the FDE list by their PC and uniqueify. Usually there is only
722 // one FDE for a PC (i.e. function), but if ICF merges two functions
723 // into one, there can be more than one FDEs pointing to the address.
724 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
725 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
726 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
727 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
Peter Collingbournec98de132016-04-11 16:40:08 +0000728
Rui Ueyama1b2936f2016-05-23 01:31:10 +0000729 Buf[0] = 1;
730 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
731 Buf[2] = DW_EH_PE_udata4;
732 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama3b31e672016-05-23 16:24:16 +0000733 write32<E>(Buf + 4, Out<ELFT>::EhFrame->getVA() - this->getVA() - 4);
Rui Ueyamae75e9332016-05-23 03:00:33 +0000734 write32<E>(Buf + 8, Fdes.size());
George Rimarf6bc65a2016-01-15 13:34:52 +0000735 Buf += 12;
736
Rui Ueyamae75e9332016-05-23 03:00:33 +0000737 uintX_t VA = this->getVA();
738 for (FdeData &Fde : Fdes) {
739 write32<E>(Buf, Fde.Pc - VA);
740 write32<E>(Buf + 4, Fde.FdeVA - VA);
George Rimarf6bc65a2016-01-15 13:34:52 +0000741 Buf += 8;
742 }
743}
744
Rui Ueyamade9777a2016-05-23 16:30:41 +0000745template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
746 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
747 this->Header.sh_size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
748}
749
George Rimarf6bc65a2016-01-15 13:34:52 +0000750template <class ELFT>
Rui Ueyamae75e9332016-05-23 03:00:33 +0000751void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
752 Fdes.push_back({Pc, FdeVA});
George Rimarf6bc65a2016-01-15 13:34:52 +0000753}
754
George Rimarf6bc65a2016-01-15 13:34:52 +0000755template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000756OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
757 : OutputSectionBase<ELFT>(Name, Type, Flags) {
758 if (Type == SHT_RELA)
759 this->Header.sh_entsize = sizeof(Elf_Rela);
760 else if (Type == SHT_REL)
761 this->Header.sh_entsize = sizeof(Elf_Rel);
762}
763
764template <class ELFT> void OutputSection<ELFT>::finalize() {
765 uint32_t Type = this->Header.sh_type;
766 if (Type != SHT_RELA && Type != SHT_REL)
767 return;
768 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
769 // sh_info for SHT_REL[A] sections should contain the section header index of
770 // the section to which the relocation applies.
771 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
772 this->Header.sh_info = S->OutSec->SectionIndex;
773}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000774
775template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000776void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000777 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000778 auto *S = cast<InputSection<ELFT>>(C);
779 Sections.push_back(S);
780 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000781 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000782}
783
Rui Ueyamac4185702016-02-10 23:20:42 +0000784// If an input string is in the form of "foo.N" where N is a number,
785// return N. Otherwise, returns 65536, which is one greater than the
786// lowest priority.
787static int getPriority(StringRef S) {
788 size_t Pos = S.rfind('.');
789 if (Pos == StringRef::npos)
790 return 65536;
791 int V;
792 if (S.substr(Pos + 1).getAsInteger(10, V))
793 return 65536;
794 return V;
795}
796
Rafael Espindola56004c52016-04-07 14:22:09 +0000797template <class ELFT>
798void OutputSection<ELFT>::forEachInputSection(
Rui Ueyama10803512016-05-22 00:25:30 +0000799 std::function<void(InputSectionBase<ELFT> *)> F) {
Rafael Espindola56004c52016-04-07 14:22:09 +0000800 for (InputSection<ELFT> *S : Sections)
801 F(S);
Rui Ueyama5af83682016-02-11 23:41:38 +0000802}
803
Rui Ueyamac4185702016-02-10 23:20:42 +0000804// Sorts input sections by section name suffixes, so that .foo.N comes
805// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000806// We want to keep the original order if the priorities are the same
807// because the compiler keeps the original initialization order in a
808// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000809// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000810template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000811 // Sort sections by priority.
812 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000813 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
814
Rui Ueyamac4185702016-02-10 23:20:42 +0000815 std::vector<Pair> V;
816 for (InputSection<ELFT> *S : Sections)
817 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000818 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000819 Sections.clear();
820 for (Pair &P : V)
821 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000822}
Rui Ueyamac4185702016-02-10 23:20:42 +0000823
Rui Ueyama5af83682016-02-11 23:41:38 +0000824// Returns true if S matches /Filename.?\.o$/.
825static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
826 if (!S.endswith(".o"))
827 return false;
828 S = S.drop_back(2);
829 if (S.endswith(Filename))
830 return true;
831 return !S.empty() && S.drop_back().endswith(Filename);
832}
833
834static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
835static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
836
837// .ctors and .dtors are sorted by this priority from highest to lowest.
838//
839// 1. The section was contained in crtbegin (crtbegin contains
840// some sentinel value in its .ctors and .dtors so that the runtime
841// can find the beginning of the sections.)
842//
843// 2. The section has an optional priority value in the form of ".ctors.N"
844// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
845// they are compared as string rather than number.
846//
847// 3. The section is just ".ctors" or ".dtors".
848//
849// 4. The section was contained in crtend, which contains an end marker.
850//
851// In an ideal world, we don't need this function because .init_array and
852// .ctors are duplicate features (and .init_array is newer.) However, there
853// are too many real-world use cases of .ctors, so we had no choice to
854// support that with this rather ad-hoc semantics.
855template <class ELFT>
856static bool compCtors(const InputSection<ELFT> *A,
857 const InputSection<ELFT> *B) {
858 bool BeginA = isCrtbegin(A->getFile()->getName());
859 bool BeginB = isCrtbegin(B->getFile()->getName());
860 if (BeginA != BeginB)
861 return BeginA;
862 bool EndA = isCrtend(A->getFile()->getName());
863 bool EndB = isCrtend(B->getFile()->getName());
864 if (EndA != EndB)
865 return EndB;
866 StringRef X = A->getSectionName();
867 StringRef Y = B->getSectionName();
868 assert(X.startswith(".ctors") || X.startswith(".dtors"));
869 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
870 X = X.substr(6);
871 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000872 if (X.empty() && Y.empty())
873 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000874 return X < Y;
875}
876
877// Sorts input sections by the special rules for .ctors and .dtors.
878// Unfortunately, the rules are different from the one for .{init,fini}_array.
879// Read the comment above.
880template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
881 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +0000882}
883
George Rimare2ee72b2016-02-26 14:48:31 +0000884static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
885 size_t I = 0;
886 for (; I + A.size() < Size; I += A.size())
887 memcpy(Buf + I, A.data(), A.size());
888 memcpy(Buf + I, A.data(), Size - I);
889}
890
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000891template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama07320e42016-04-20 20:13:41 +0000892 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
George Rimare2ee72b2016-02-26 14:48:31 +0000893 if (!Filler.empty())
894 fill(Buf, this->getSize(), Filler);
Rui Ueyamae9809502016-03-11 04:23:12 +0000895 if (Config->Threads) {
896 parallel_for_each(Sections.begin(), Sections.end(),
897 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
898 } else {
899 for (InputSection<ELFT> *C : Sections)
900 C->writeTo(Buf);
901 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000902}
903
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000904template <class ELFT>
Rui Ueyamaf86cb902016-05-23 15:12:41 +0000905EhOutputSection<ELFT>::EhOutputSection()
Rui Ueyama3b31e672016-05-23 16:24:16 +0000906 : OutputSectionBase<ELFT>(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000907
908template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000909void EhOutputSection<ELFT>::forEachInputSection(
Rafael Espindola56004c52016-04-07 14:22:09 +0000910 std::function<void(InputSectionBase<ELFT> *)> F) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000911 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola56004c52016-04-07 14:22:09 +0000912 F(S);
913}
914
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000915// Returns the first relocation that points to a region
916// between Begin and Begin+Size.
917template <class IntTy, class RelTy>
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000918static const RelTy *getReloc(IntTy Begin, IntTy Size, ArrayRef<RelTy> &Rels) {
919 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
920 if (I->r_offset < Begin)
921 continue;
922
923 // Truncate Rels for fast access. That means we expect that the
924 // relocations are sorted and we are looking up symbols in
925 // sequential order. It is naturally satisfied for .eh_frame.
926 Rels = Rels.slice(I - Rels.begin());
927 if (I->r_offset < Begin + Size)
928 return I;
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000929 return nullptr;
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000930 }
931 Rels = ArrayRef<RelTy>();
932 return nullptr;
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000933}
934
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000935// Search for an existing CIE record or create a new one.
936// CIE records from input object files are uniquified by their contents
937// and where their relocations point to.
938template <class ELFT>
939template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000940CieRecord *EhOutputSection<ELFT>::addCie(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000941 EhInputSection<ELFT> *Sec,
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000942 ArrayRef<RelTy> &Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000943 const endianness E = ELFT::TargetEndianness;
Rui Ueyamad8849272016-05-25 16:37:01 +0000944 if (read32<E>(Piece.data().data() + 4) != 0)
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000945 fatal("CIE expected at beginning of .eh_frame: " + Sec->getSectionName());
946
947 SymbolBody *Personality = nullptr;
948 if (const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels))
949 Personality = &Sec->getFile()->getRelocTargetSym(*Rel);
950
951 // Search for an existing CIE by CIE contents/relocation target pair.
Rui Ueyamad8849272016-05-25 16:37:01 +0000952 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000953
954 // If not found, create a new one.
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000955 if (Cie->Piece == nullptr) {
956 Cie->Piece = &Piece;
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000957 Cies.push_back(Cie);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000958 }
959 return Cie;
960}
961
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000962// There is one FDE per function. Returns true if a given FDE
963// points to a live function.
964template <class ELFT>
965template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000966bool EhOutputSection<ELFT>::isFdeLive(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000967 EhInputSection<ELFT> *Sec,
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000968 ArrayRef<RelTy> &Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000969 const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels);
970 if (!Rel)
971 fatal("FDE doesn't reference another section");
972 SymbolBody &B = Sec->getFile()->getRelocTargetSym(*Rel);
973 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
974 if (!D || !D->Section)
975 return false;
976 InputSectionBase<ELFT> *Target = D->Section->Repl;
977 return Target && Target->Live;
978}
979
980// .eh_frame is a sequence of CIE or FDE records. In general, there
981// is one CIE record per input object file which is followed by
982// a list of FDEs. This function searches an existing CIE or create a new
983// one and associates FDEs to the CIE.
Rui Ueyamac0c92602016-02-05 22:56:03 +0000984template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +0000985template <class RelTy>
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000986void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +0000987 ArrayRef<RelTy> Rels) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000988 const endianness E = ELFT::TargetEndianness;
Rafael Espindola820f4bb2016-05-24 15:17:47 +0000989
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000990 DenseMap<size_t, CieRecord *> OffsetToCie;
Rafael Espindola5ee9e7f2016-05-24 19:14:09 +0000991 for (SectionPiece &Piece : Sec->Pieces) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000992 // The empty record is the end marker.
Rui Ueyamad8849272016-05-25 16:37:01 +0000993 if (Piece.size() == 4)
Rafael Espindola5ee9e7f2016-05-24 19:14:09 +0000994 return;
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000995
996 size_t Offset = Piece.InputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +0000997 uint32_t ID = read32<E>(Piece.data().data() + 4);
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000998 if (ID == 0) {
999 OffsetToCie[Offset] = addCie(Piece, Sec, Rels);
1000 continue;
1001 }
1002
1003 uint32_t CieOffset = Offset + 4 - ID;
1004 CieRecord *Cie = OffsetToCie[CieOffset];
1005 if (!Cie)
1006 fatal("invalid CIE reference");
1007
1008 if (!isFdeLive(Piece, Sec, Rels))
1009 continue;
1010 Cie->FdePieces.push_back(&Piece);
Rui Ueyamade9777a2016-05-23 16:30:41 +00001011 NumFdes++;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001012 }
1013}
1014
1015template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001016void EhOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001017 auto *Sec = cast<EhInputSection<ELFT>>(C);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001018 Sec->OutSec = this;
1019 this->updateAlign(Sec->Align);
1020 Sections.push_back(Sec);
1021
1022 // .eh_frame is a sequence of CIE or FDE records. This function
1023 // splits it into pieces so that we can call
1024 // SplitInputSection::getSectionPiece on the section.
Rui Ueyama88abd9b2016-05-22 23:53:00 +00001025 Sec->split();
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001026 if (Sec->Pieces.empty())
1027 return;
1028
1029 if (const Elf_Shdr *RelSec = Sec->RelocSection) {
1030 ELFFile<ELFT> &Obj = Sec->getFile()->getObj();
1031 if (RelSec->sh_type == SHT_RELA)
1032 addSectionAux(Sec, Obj.relas(RelSec));
1033 else
1034 addSectionAux(Sec, Obj.rels(RelSec));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001035 return;
1036 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001037 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001038}
1039
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001040template <class ELFT>
Rui Ueyama644ac652016-05-22 00:17:11 +00001041static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1042 memcpy(Buf, D.data(), D.size());
Rui Ueyamac0449a62016-05-21 18:10:13 +00001043
1044 // Fix the size field. -4 since size does not include the size field itself.
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001045 const endianness E = ELFT::TargetEndianness;
Rui Ueyama644ac652016-05-22 00:17:11 +00001046 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
Rafael Espindola56004c52016-04-07 14:22:09 +00001047}
1048
Rui Ueyama1e479c22016-05-23 15:07:59 +00001049template <class ELFT> void EhOutputSection<ELFT>::finalize() {
Rafael Espindola56004c52016-04-07 14:22:09 +00001050 if (Finalized)
1051 return;
1052 Finalized = true;
1053
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001054 size_t Off = 0;
1055 for (CieRecord *Cie : Cies) {
1056 Cie->Piece->OutputOff = Off;
1057 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001058
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001059 for (SectionPiece *Fde : Cie->FdePieces) {
1060 Fde->OutputOff = Off;
1061 Off += alignTo(Fde->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001062 }
1063 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001064 this->Header.sh_size = Off;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001065}
1066
Rui Ueyamae75e9332016-05-23 03:00:33 +00001067template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1068 const endianness E = ELFT::TargetEndianness;
1069 switch (Size) {
1070 case DW_EH_PE_udata2:
1071 return read16<E>(Buf);
1072 case DW_EH_PE_udata4:
1073 return read32<E>(Buf);
1074 case DW_EH_PE_udata8:
1075 return read64<E>(Buf);
1076 case DW_EH_PE_absptr:
1077 if (ELFT::Is64Bits)
1078 return read64<E>(Buf);
1079 return read32<E>(Buf);
1080 }
1081 fatal("unknown FDE size encoding");
1082}
1083
1084// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1085// We need it to create .eh_frame_hdr section.
1086template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001087typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
Rui Ueyamae75e9332016-05-23 03:00:33 +00001088 uint8_t Enc) {
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001089 // The starting address to which this FDE applies is
Rui Ueyamae75e9332016-05-23 03:00:33 +00001090 // stored at FDE + 8 byte.
1091 size_t Off = FdeOff + 8;
1092 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1093 if ((Enc & 0x70) == DW_EH_PE_absptr)
1094 return Addr;
1095 if ((Enc & 0x70) == DW_EH_PE_pcrel)
1096 return Addr + this->getVA() + Off;
1097 fatal("unknown FDE size relative encoding");
1098}
1099
Rui Ueyama1e479c22016-05-23 15:07:59 +00001100template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001101 const endianness E = ELFT::TargetEndianness;
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001102 for (CieRecord *Cie : Cies) {
1103 size_t CieOffset = Cie->Piece->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001104 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001105
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001106 for (SectionPiece *Fde : Cie->FdePieces) {
1107 size_t Off = Fde->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001108 writeCieFde<ELFT>(Buf + Off, Fde->data());
Rafael Espindola56004c52016-04-07 14:22:09 +00001109
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001110 // FDE's second word should have the offset to an associated CIE.
1111 // Write it.
1112 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001113 }
1114 }
1115
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001116 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola22ef9562016-04-13 01:40:19 +00001117 S->relocate(Buf, nullptr);
Rui Ueyamae75e9332016-05-23 03:00:33 +00001118
1119 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001120 // to get a FDE from an address to which FDE is applied. So here
Rui Ueyamae75e9332016-05-23 03:00:33 +00001121 // we obtain two addresses and pass them to EhFrameHdr object.
Rui Ueyama3b31e672016-05-23 16:24:16 +00001122 if (Out<ELFT>::EhFrameHdr) {
1123 for (CieRecord *Cie : Cies) {
Rui Ueyamad8849272016-05-25 16:37:01 +00001124 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->data());
Rui Ueyama3b31e672016-05-23 16:24:16 +00001125 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyama6de2e682016-05-24 02:08:38 +00001126 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rui Ueyama3b31e672016-05-23 16:24:16 +00001127 uintX_t FdeVA = this->getVA() + Fde->OutputOff;
1128 Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1129 }
Rui Ueyamae75e9332016-05-23 03:00:33 +00001130 }
1131 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001132}
1133
1134template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001135MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001136 uintX_t Flags, uintX_t Alignment)
1137 : OutputSectionBase<ELFT>(Name, Type, Flags),
1138 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001139
1140template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001141 if (shouldTailMerge()) {
1142 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001143 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001144 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001145 }
Rui Ueyama31f9f612016-05-06 00:52:08 +00001146 for (const std::pair<CachedHash<StringRef>, size_t> &P : Builder.getMap()) {
1147 StringRef Data = P.first.Val;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001148 memcpy(Buf + P.second, Data.data(), Data.size());
1149 }
1150}
1151
Rui Ueyama34dc99e2016-05-22 01:15:32 +00001152static StringRef toStringRef(ArrayRef<uint8_t> A) {
1153 return {(const char *)A.data(), A.size()};
1154}
1155
Rafael Espindolac159c962015-10-19 21:00:02 +00001156template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001157void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama10803512016-05-22 00:25:30 +00001158 auto *Sec = cast<MergeInputSection<ELFT>>(C);
1159 Sec->OutSec = this;
1160 this->updateAlign(Sec->Align);
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001161 this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize;
Rui Ueyama406b4692016-05-27 14:39:13 +00001162 Sections.push_back(Sec);
Rafael Espindolac159c962015-10-19 21:00:02 +00001163
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001164 bool IsString = this->Header.sh_flags & SHF_STRINGS;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001165
Rui Ueyamab7eda282016-05-24 02:10:28 +00001166 for (SectionPiece &Piece : Sec->Pieces) {
Rui Ueyama3ea87272016-05-22 00:13:04 +00001167 if (!Piece.Live)
Rafael Espindola0b9531c2016-04-22 22:09:35 +00001168 continue;
Rui Ueyamad8849272016-05-25 16:37:01 +00001169 uintX_t OutputOffset = Builder.add(toStringRef(Piece.data()));
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001170 if (!IsString || !shouldTailMerge())
1171 Piece.OutputOff = OutputOffset;
Rafael Espindolac159c962015-10-19 21:00:02 +00001172 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001173}
1174
1175template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001176unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1177 return Builder.getOffset(Val);
1178}
1179
1180template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1181 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1182}
1183
1184template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1185 if (shouldTailMerge())
1186 Builder.finalize();
1187 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001188}
1189
Rui Ueyama406b4692016-05-27 14:39:13 +00001190template <class ELFT> void MergeOutputSection<ELFT>::finalizePieces() {
1191 for (MergeInputSection<ELFT> *Sec : Sections)
1192 Sec->finalizePieces();
1193}
1194
Rafael Espindolac159c962015-10-19 21:00:02 +00001195template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001196StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001197 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1198 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001199 Dynamic(Dynamic) {
1200 this->Header.sh_addralign = 1;
1201}
1202
Rafael Espindolae2c24612016-01-29 01:24:25 +00001203// Adds a string to the string table. If HashIt is true we hash and check for
1204// duplicates. It is optional because the name of global symbols are already
1205// uniqued and hashing them again has a big cost for a small value: uniquing
1206// them with some other string that happens to be the same.
1207template <class ELFT>
1208unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1209 if (HashIt) {
1210 auto R = StringMap.insert(std::make_pair(S, Size));
1211 if (!R.second)
1212 return R.first->second;
1213 }
1214 unsigned Ret = Size;
1215 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001216 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001217 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001218}
1219
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001220template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001221 // ELF string tables start with NUL byte, so advance the pointer by one.
1222 ++Buf;
1223 for (StringRef S : Strings) {
1224 memcpy(Buf, S.data(), S.size());
1225 Buf += S.size() + 1;
1226 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001227}
1228
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001229template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001230SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamaace4f902016-05-24 04:25:47 +00001231 StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001232 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1233 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001234 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rui Ueyamaace4f902016-05-24 04:25:47 +00001235 StrTabSec(StrTabSec) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001236 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001237 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001238}
1239
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001240// Orders symbols according to their positions in the GOT,
1241// in compliance with MIPS ABI rules.
1242// See "Global Offset Table" in Chapter 5 in the following document
1243// for detailed description:
1244// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001245static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1246 const std::pair<SymbolBody *, unsigned> &R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001247 // Sort entries related to non-local preemptible symbols by GOT indexes.
1248 // All other entries go to the first part of GOT in arbitrary order.
1249 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible();
1250 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible();
1251 if (LIsInLocalGot || RIsInLocalGot)
1252 return !RIsInLocalGot;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001253 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001254}
1255
Rafael Espindolabadd3972016-04-08 15:30:56 +00001256static uint8_t getSymbolBinding(SymbolBody *Body) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001257 Symbol *S = Body->symbol();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001258 uint8_t Visibility = S->Visibility;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001259 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1260 return STB_LOCAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001261 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
Rafael Espindolabadd3972016-04-08 15:30:56 +00001262 return STB_GLOBAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001263 return S->Binding;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001264}
1265
Rui Ueyama0db335f2015-10-07 16:58:54 +00001266template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001267 if (this->Header.sh_size)
1268 return; // Already finalized.
1269
Rui Ueyama0db335f2015-10-07 16:58:54 +00001270 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001271 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001272 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001273
George Rimar58941ee2016-02-25 08:23:37 +00001274 if (Config->Relocatable) {
1275 size_t I = NumLocals;
1276 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1277 P.first->DynsymIndex = ++I;
1278 return;
1279 }
1280
Igor Kudrinab665fc2015-10-20 21:47:58 +00001281 if (!StrTabSec.isDynamic()) {
1282 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001283 [](const std::pair<SymbolBody *, unsigned> &L,
1284 const std::pair<SymbolBody *, unsigned> &R) {
1285 return getSymbolBinding(L.first) == STB_LOCAL &&
1286 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001287 });
1288 return;
1289 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001290 if (Out<ELFT>::GnuHashTab)
1291 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1292 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001293 else if (Config->EMachine == EM_MIPS)
1294 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001295 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001296 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001297 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001298}
1299
1300template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001301void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1302 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001303}
1304
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001305template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001306 Buf += sizeof(Elf_Sym);
1307
1308 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1309 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001310 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1311 writeLocalSymbols(Buf);
1312
1313 writeGlobalSymbols(Buf);
1314}
1315
1316template <class ELFT>
1317void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1318 // Iterate over all input object files to copy their local symbols
1319 // to the output symbol table pointed by Buf.
Rui Ueyamaace4f902016-05-24 04:25:47 +00001320 for (const std::unique_ptr<ObjectFile<ELFT>> &File :
1321 Symtab<ELFT>::X->getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001322 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1323 File->KeptLocalSyms) {
1324 const DefinedRegular<ELFT> &Body = *P.first;
1325 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001326 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001327
1328 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001329 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001330 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001331 } else {
Rafael Espindolac159c962015-10-19 21:00:02 +00001332 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1333 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001334 ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001335 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001336 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001337 ESym->st_size = Body.template getSize<ELFT>();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001338 ESym->setBindingAndType(STB_LOCAL, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001339 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001340 }
1341 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001342}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001343
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001344template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001345void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001346 // Write the internal symbol table contents to the output symbol table
1347 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001348 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001349 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001350 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001351 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001352
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001353 uint8_t Type = Body->Type;
1354 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001355
Igor Kudrin853b88d2015-10-20 20:52:14 +00001356 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001357 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001358 ESym->st_name = StrOff;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001359 ESym->setVisibility(Body->symbol()->Visibility);
Rui Ueyamab5a69702016-02-01 21:00:35 +00001360 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001361
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001362 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001363 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001364 else if (isa<DefinedRegular<ELFT>>(Body))
1365 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001366
1367 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1368 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1369 // distinguish such symbols and MIPS lazy-binding stubs.
1370 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1371 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1372 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001373 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001374 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001375 }
1376}
1377
Igor Kudrin853b88d2015-10-20 20:52:14 +00001378template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001379const OutputSectionBase<ELFT> *
1380SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1381 switch (Sym->kind()) {
1382 case SymbolBody::DefinedSyntheticKind:
Peter Collingbourne6a422592016-05-03 01:21:08 +00001383 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001384 case SymbolBody::DefinedRegularKind: {
Rafael Espindola5ffa13c2016-04-15 00:15:02 +00001385 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001386 if (D.Section)
1387 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001388 break;
1389 }
1390 case SymbolBody::DefinedCommonKind:
1391 return Out<ELFT>::Bss;
1392 case SymbolBody::SharedKind:
1393 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1394 return Out<ELFT>::Bss;
1395 break;
Peter Collingbourne60976ed2016-04-27 00:05:06 +00001396 case SymbolBody::UndefinedKind:
Rui Ueyamaf8baa662016-04-07 19:24:51 +00001397 case SymbolBody::LazyArchiveKind:
1398 case SymbolBody::LazyObjectKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001399 break;
1400 case SymbolBody::DefinedBitcodeKind:
Davide Italianof6523ae2016-03-29 02:20:10 +00001401 llvm_unreachable("should have been replaced");
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001402 }
1403 return nullptr;
1404}
1405
1406template <class ELFT>
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001407VersionTableSection<ELFT>::VersionTableSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001408 : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001409 this->Header.sh_addralign = sizeof(uint16_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001410}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001411
1412template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1413 this->Header.sh_size =
1414 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
1415 this->Header.sh_entsize = sizeof(Elf_Versym);
George Rimar8b3c5f22016-06-06 08:04:53 +00001416 // At the moment of june 2016 GNU docs does not mention that sh_link field
1417 // should be set, but Sun docs do. Also readelf relies on this field.
1418 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001419}
1420
1421template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1422 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1423 for (const std::pair<SymbolBody *, size_t> &P :
1424 Out<ELFT>::DynSymTab->getSymbols()) {
1425 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(P.first))
1426 OutVersym->vs_index = SS->VersionId;
1427 else
George Rimard50a1452016-06-08 11:40:24 +00001428 OutVersym->vs_index = VER_NDX_GLOBAL;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001429 ++OutVersym;
1430 }
1431}
1432
1433template <class ELFT>
1434VersionNeedSection<ELFT>::VersionNeedSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001435 : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001436 this->Header.sh_addralign = sizeof(uint32_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001437}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001438
1439template <class ELFT>
1440void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1441 if (!SS->Verdef) {
George Rimar56efb3492016-06-08 11:49:01 +00001442 SS->VersionId = VER_NDX_GLOBAL;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001443 return;
1444 }
1445 SharedFile<ELFT> *F = SS->File;
1446 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1447 // to create one by adding it to our needed list and creating a dynstr entry
1448 // for the soname.
1449 if (F->VerdefMap.empty())
1450 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1451 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1452 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1453 // prepare to create one by allocating a version identifier and creating a
1454 // dynstr entry for the version name.
1455 if (NV.Index == 0) {
1456 NV.StrTab = Out<ELFT>::DynStrTab->addString(
1457 SS->File->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1458 NV.Index = NextIndex++;
1459 }
1460 SS->VersionId = NV.Index;
1461}
1462
1463template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1464 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1465 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1466 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1467
1468 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1469 // Create an Elf_Verneed for this DSO.
1470 Verneed->vn_version = 1;
1471 Verneed->vn_cnt = P.first->VerdefMap.size();
1472 Verneed->vn_file = P.second;
1473 Verneed->vn_aux =
1474 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1475 Verneed->vn_next = sizeof(Elf_Verneed);
1476 ++Verneed;
1477
1478 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1479 // VerdefMap, which will only contain references to needed version
1480 // definitions. Each Elf_Vernaux is based on the information contained in
1481 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1482 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1483 // data structures within a single input file.
1484 for (auto &NV : P.first->VerdefMap) {
1485 Vernaux->vna_hash = NV.first->vd_hash;
1486 Vernaux->vna_flags = 0;
1487 Vernaux->vna_other = NV.second.Index;
1488 Vernaux->vna_name = NV.second.StrTab;
1489 Vernaux->vna_next = sizeof(Elf_Vernaux);
1490 ++Vernaux;
1491 }
1492
1493 Vernaux[-1].vna_next = 0;
1494 }
1495 Verneed[-1].vn_next = 0;
1496}
1497
1498template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1499 this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1500 this->Header.sh_info = Needed.size();
1501 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1502 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1503 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1504 this->Header.sh_size = Size;
1505}
1506
1507template <class ELFT>
Rui Ueyama3a41be22016-04-07 22:49:21 +00001508BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1509 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1510 HashSize(HashSize) {
1511 // 16 bytes for the note section header.
1512 this->Header.sh_size = 16 + HashSize;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001513}
1514
1515template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1516 const endianness E = ELFT::TargetEndianness;
1517 write32<E>(Buf, 4); // Name size
Rui Ueyama3a41be22016-04-07 22:49:21 +00001518 write32<E>(Buf + 4, HashSize); // Content size
Rui Ueyama634ddf02016-03-11 20:51:53 +00001519 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1520 memcpy(Buf + 12, "GNU", 4); // Name string
1521 HashBuf = Buf + 16;
1522}
1523
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001524template <class ELFT>
1525void BuildIdFnv1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
Rui Ueyama634ddf02016-03-11 20:51:53 +00001526 const endianness E = ELFT::TargetEndianness;
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001527
1528 // 64-bit FNV-1 hash
1529 uint64_t Hash = 0xcbf29ce484222325;
1530 for (ArrayRef<uint8_t> Buf : Bufs) {
1531 for (uint8_t B : Buf) {
1532 Hash *= 0x100000001b3;
1533 Hash ^= B;
1534 }
1535 }
Rui Ueyama3a41be22016-04-07 22:49:21 +00001536 write64<E>(this->HashBuf, Hash);
1537}
1538
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001539template <class ELFT>
1540void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1541 llvm::MD5 Hash;
1542 for (ArrayRef<uint8_t> Buf : Bufs)
1543 Hash.update(Buf);
Rui Ueyama3a41be22016-04-07 22:49:21 +00001544 MD5::MD5Result Res;
1545 Hash.final(Res);
1546 memcpy(this->HashBuf, Res, 16);
Rui Ueyama634ddf02016-03-11 20:51:53 +00001547}
1548
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001549template <class ELFT>
1550void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1551 llvm::SHA1 Hash;
1552 for (ArrayRef<uint8_t> Buf : Bufs)
1553 Hash.update(Buf);
Rui Ueyamad86ec302016-04-07 23:51:56 +00001554 memcpy(this->HashBuf, Hash.final().data(), 20);
1555}
1556
Rui Ueyama634ddf02016-03-11 20:51:53 +00001557template <class ELFT>
Rui Ueyama9194db72016-05-13 21:55:56 +00001558BuildIdHexstring<ELFT>::BuildIdHexstring()
1559 : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
1560
1561template <class ELFT>
1562void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1563 memcpy(this->HashBuf, Config->BuildIdVector.data(),
1564 Config->BuildIdVector.size());
1565}
1566
1567template <class ELFT>
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001568MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1569 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1570 this->Header.sh_addralign = 4;
1571 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1572 this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1573}
1574
1575template <class ELFT>
1576void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1577 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
Simon Atanasyan4ee29182016-04-27 05:31:28 +00001578 R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
Rui Ueyama70eed362016-01-06 22:42:43 +00001579 R->ri_gprmask = GprMask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001580}
1581
1582template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001583void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama70eed362016-01-06 22:42:43 +00001584 // Copy input object file's .reginfo gprmask to output.
Rui Ueyama40845e62015-12-26 05:51:07 +00001585 auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
Rui Ueyama70eed362016-01-06 22:42:43 +00001586 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan84bb3552016-05-26 20:46:01 +00001587 S->OutSec = this;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001588}
1589
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001590template <class ELFT>
1591MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection()
1592 : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS,
1593 SHF_ALLOC | SHF_MIPS_NOSTRIP) {
1594 this->Header.sh_addralign = 8;
1595 this->Header.sh_entsize = 1;
1596 this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1597}
1598
1599template <class ELFT>
1600void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1601 auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf);
1602 Opt->kind = ODK_REGINFO;
1603 Opt->size = this->Header.sh_size;
1604 Opt->section = 0;
1605 Opt->info = 0;
1606 auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt));
1607 Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1608 Reg->ri_gprmask = GprMask;
1609}
1610
1611template <class ELFT>
1612void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1613 auto *S = cast<MipsOptionsInputSection<ELFT>>(C);
1614 if (S->Reginfo)
1615 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan84bb3552016-05-26 20:46:01 +00001616 S->OutSec = this;
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001617}
1618
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001619namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001620namespace elf {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001621template class OutputSectionBase<ELF32LE>;
1622template class OutputSectionBase<ELF32BE>;
1623template class OutputSectionBase<ELF64LE>;
1624template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001625
George Rimarf6bc65a2016-01-15 13:34:52 +00001626template class EhFrameHeader<ELF32LE>;
1627template class EhFrameHeader<ELF32BE>;
1628template class EhFrameHeader<ELF64LE>;
1629template class EhFrameHeader<ELF64BE>;
1630
George Rimar648a2c32015-10-20 08:54:27 +00001631template class GotPltSection<ELF32LE>;
1632template class GotPltSection<ELF32BE>;
1633template class GotPltSection<ELF64LE>;
1634template class GotPltSection<ELF64BE>;
1635
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001636template class GotSection<ELF32LE>;
1637template class GotSection<ELF32BE>;
1638template class GotSection<ELF64LE>;
1639template class GotSection<ELF64BE>;
1640
1641template class PltSection<ELF32LE>;
1642template class PltSection<ELF32BE>;
1643template class PltSection<ELF64LE>;
1644template class PltSection<ELF64BE>;
1645
1646template class RelocationSection<ELF32LE>;
1647template class RelocationSection<ELF32BE>;
1648template class RelocationSection<ELF64LE>;
1649template class RelocationSection<ELF64BE>;
1650
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001651template class InterpSection<ELF32LE>;
1652template class InterpSection<ELF32BE>;
1653template class InterpSection<ELF64LE>;
1654template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001655
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001656template class GnuHashTableSection<ELF32LE>;
1657template class GnuHashTableSection<ELF32BE>;
1658template class GnuHashTableSection<ELF64LE>;
1659template class GnuHashTableSection<ELF64BE>;
1660
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001661template class HashTableSection<ELF32LE>;
1662template class HashTableSection<ELF32BE>;
1663template class HashTableSection<ELF64LE>;
1664template class HashTableSection<ELF64BE>;
1665
1666template class DynamicSection<ELF32LE>;
1667template class DynamicSection<ELF32BE>;
1668template class DynamicSection<ELF64LE>;
1669template class DynamicSection<ELF64BE>;
1670
1671template class OutputSection<ELF32LE>;
1672template class OutputSection<ELF32BE>;
1673template class OutputSection<ELF64LE>;
1674template class OutputSection<ELF64BE>;
1675
Rui Ueyama1e479c22016-05-23 15:07:59 +00001676template class EhOutputSection<ELF32LE>;
1677template class EhOutputSection<ELF32BE>;
1678template class EhOutputSection<ELF64LE>;
1679template class EhOutputSection<ELF64BE>;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001680
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001681template class MipsReginfoOutputSection<ELF32LE>;
1682template class MipsReginfoOutputSection<ELF32BE>;
1683template class MipsReginfoOutputSection<ELF64LE>;
1684template class MipsReginfoOutputSection<ELF64BE>;
1685
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001686template class MipsOptionsOutputSection<ELF32LE>;
1687template class MipsOptionsOutputSection<ELF32BE>;
1688template class MipsOptionsOutputSection<ELF64LE>;
1689template class MipsOptionsOutputSection<ELF64BE>;
1690
Rafael Espindolac159c962015-10-19 21:00:02 +00001691template class MergeOutputSection<ELF32LE>;
1692template class MergeOutputSection<ELF32BE>;
1693template class MergeOutputSection<ELF64LE>;
1694template class MergeOutputSection<ELF64BE>;
1695
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001696template class StringTableSection<ELF32LE>;
1697template class StringTableSection<ELF32BE>;
1698template class StringTableSection<ELF64LE>;
1699template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001700
1701template class SymbolTableSection<ELF32LE>;
1702template class SymbolTableSection<ELF32BE>;
1703template class SymbolTableSection<ELF64LE>;
1704template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001705
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001706template class VersionTableSection<ELF32LE>;
1707template class VersionTableSection<ELF32BE>;
1708template class VersionTableSection<ELF64LE>;
1709template class VersionTableSection<ELF64BE>;
1710
1711template class VersionNeedSection<ELF32LE>;
1712template class VersionNeedSection<ELF32BE>;
1713template class VersionNeedSection<ELF64LE>;
1714template class VersionNeedSection<ELF64BE>;
1715
Rui Ueyama634ddf02016-03-11 20:51:53 +00001716template class BuildIdSection<ELF32LE>;
1717template class BuildIdSection<ELF32BE>;
1718template class BuildIdSection<ELF64LE>;
1719template class BuildIdSection<ELF64BE>;
Rui Ueyama3a41be22016-04-07 22:49:21 +00001720
1721template class BuildIdFnv1<ELF32LE>;
1722template class BuildIdFnv1<ELF32BE>;
1723template class BuildIdFnv1<ELF64LE>;
1724template class BuildIdFnv1<ELF64BE>;
1725
1726template class BuildIdMd5<ELF32LE>;
1727template class BuildIdMd5<ELF32BE>;
1728template class BuildIdMd5<ELF64LE>;
1729template class BuildIdMd5<ELF64BE>;
Rui Ueyamad86ec302016-04-07 23:51:56 +00001730
1731template class BuildIdSha1<ELF32LE>;
1732template class BuildIdSha1<ELF32BE>;
1733template class BuildIdSha1<ELF64LE>;
1734template class BuildIdSha1<ELF64BE>;
Rui Ueyama9194db72016-05-13 21:55:56 +00001735
1736template class BuildIdHexstring<ELF32LE>;
1737template class BuildIdHexstring<ELF32BE>;
1738template class BuildIdHexstring<ELF64LE>;
1739template class BuildIdHexstring<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001740}
1741}