blob: 2b180c97b104afa8f1d89caa56afcad6e086fa63 [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 Ueyamac9fee5f2016-06-16 16:14:50 +000082 Target->writeGotPlt(Buf, *B);
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.
George Rimar687138c2015-11-13 16:28:53 +0000152 Entries.push_back(nullptr);
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000153 Entries.push_back(&Sym);
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 Atanasyan311b4b12016-06-10 12:26:28 +0000210 size_t EntriesNum = Entries.size();
211 if (Config->EMachine == EM_MIPS) {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000212 // Take into account MIPS GOT header.
213 // See comment in the GotSection::writeTo.
214 MipsLocalEntries += 2;
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000215 for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
216 // Calculate an upper bound of MIPS GOT entries required to store page
217 // addresses of local symbols. We assume the worst case - each 64kb
218 // page of the output section has at least one GOT relocation against it.
219 // Add 0x8000 to the section's size because the page address stored
220 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
221 MipsLocalEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
222 }
223 EntriesNum += MipsLocalEntries;
Simon Atanasyand2980d32016-03-29 14:07:22 +0000224 }
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000225 this->Header.sh_size = EntriesNum * sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000226}
227
Rafael Espindolaa6627382015-10-06 23:56:53 +0000228template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000229 if (Config->EMachine == EM_MIPS) {
230 // Set the MSB of the second GOT slot. This is not required by any
231 // MIPS ABI documentation, though.
232 //
233 // There is a comment in glibc saying that "The MSB of got[1] of a
234 // gnu object is set to identify gnu objects," and in GNU gold it
235 // says "the second entry will be used by some runtime loaders".
236 // But how this field is being used is unclear.
237 //
238 // We are not really willing to mimic other linkers behaviors
239 // without understanding why they do that, but because all files
240 // generated by GNU tools have this special GOT value, and because
241 // we've been doing this for years, it is probably a safe bet to
242 // keep doing this for now. We really need to revisit this to see
243 // if we had to do this.
244 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
245 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000246 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
247 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
248 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
249 }
250 Buf += MipsLocalEntries * sizeof(uintX_t);
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000251 }
Rafael Espindolaa6627382015-10-06 23:56:53 +0000252 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000253 uint8_t *Entry = Buf;
254 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000255 if (!B)
256 continue;
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000257 // MIPS has special rules to fill up GOT entries.
258 // See "Global Offset Table" in Chapter 5 in the following document
259 // for detailed description:
260 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
261 // As the first approach, we can just store addresses for all symbols.
Rui Ueyamac4466602016-03-13 19:48:18 +0000262 if (Config->EMachine != EM_MIPS && B->isPreemptible())
Rafael Espindolaa6627382015-10-06 23:56:53 +0000263 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000264 uintX_t VA = B->getVA<ELFT>();
Rafael Espindolae782f672015-10-07 03:56:05 +0000265 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000266 }
267}
268
Rafael Espindola35c6af32015-09-25 17:19:10 +0000269template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000270PltSection<ELFT>::PltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000271 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000272 this->Header.sh_addralign = 16;
273}
274
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000275template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000276 // At beginning of PLT, we have code to call the dynamic linker
277 // to resolve dynsyms at runtime. Write such code.
278 Target->writePltZero(Buf);
Rui Ueyamaf57a5902016-05-20 21:39:07 +0000279 size_t Off = Target->PltZeroSize;
280
George Rimarfb5d7f22015-11-26 19:58:51 +0000281 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000282 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000283 unsigned RelOff = I.second;
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000284 uint64_t Got = B->getGotPltVA<ELFT>();
Rui Ueyama242ddf42015-10-12 18:56:36 +0000285 uint64_t Plt = this->getVA() + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000286 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000287 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000288 }
289}
290
Rafael Espindola67d72c02016-03-11 12:06:30 +0000291template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
292 Sym.PltIndex = Entries.size();
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000293 unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000294 Entries.push_back(std::make_pair(&Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000295}
296
George Rimar648a2c32015-10-20 08:54:27 +0000297template <class ELFT> void PltSection<ELFT>::finalize() {
Rui Ueyama724d6252016-01-29 01:49:32 +0000298 this->Header.sh_size =
Rui Ueyama62515452016-01-29 03:00:32 +0000299 Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000300}
301
302template <class ELFT>
George Rimarc191acf2016-05-10 15:47:57 +0000303RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000304 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
George Rimarc191acf2016-05-10 15:47:57 +0000305 SHF_ALLOC),
306 Sort(Sort) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000307 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000308 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000309}
310
George Rimar5828c232015-11-30 17:49:19 +0000311template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000312void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000313 Relocs.push_back(Reloc);
314}
315
George Rimarc191acf2016-05-10 15:47:57 +0000316template <class ELFT, class RelTy>
317static bool compRelocations(const RelTy &A, const RelTy &B) {
318 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
319}
320
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000321template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarc191acf2016-05-10 15:47:57 +0000322 uint8_t *BufBegin = Buf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000323 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rui Ueyama614be592016-03-13 05:23:40 +0000324 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000325 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rafael Espindolade9857e2016-02-04 21:33:05 +0000326 SymbolBody *Sym = Rel.Sym;
Rui Ueyamab0210e832016-01-26 00:24:57 +0000327
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000328 if (Config->Rela)
Rui Ueyama614be592016-03-13 05:23:40 +0000329 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend;
Rafael Espindola74031ba2016-04-07 15:20:56 +0000330 P->r_offset = Rel.OffsetInSec + Rel.OffsetSec->getVA();
Rafael Espindolade9857e2016-02-04 21:33:05 +0000331 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
332 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000333 }
George Rimarc191acf2016-05-10 15:47:57 +0000334
335 if (Sort) {
336 if (Config->Rela)
337 std::stable_sort((Elf_Rela *)BufBegin,
338 (Elf_Rela *)BufBegin + Relocs.size(),
339 compRelocations<ELFT, Elf_Rela>);
340 else
341 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
342 compRelocations<ELFT, Elf_Rel>);
343 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000344}
345
George Rimar77b77792015-11-25 22:15:01 +0000346template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rui Ueyama5a0b2f72016-02-05 19:13:18 +0000347 return this->Header.sh_entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000348}
349
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000350template <class ELFT> void RelocationSection<ELFT>::finalize() {
George Rimara07ff662015-12-21 10:12:06 +0000351 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
352 : Out<ELFT>::DynSymTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000353 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
354}
355
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000356template <class ELFT>
357InterpSection<ELFT>::InterpSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000358 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000359 this->Header.sh_size = Config->DynamicLinker.size() + 1;
360 this->Header.sh_addralign = 1;
361}
362
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000363template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1e720b92016-03-13 06:50:34 +0000364 StringRef S = Config->DynamicLinker;
365 memcpy(Buf, S.data(), S.size());
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000366}
367
Rafael Espindola35c6af32015-09-25 17:19:10 +0000368template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000369HashTableSection<ELFT>::HashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000370 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000371 this->Header.sh_entsize = sizeof(Elf_Word);
372 this->Header.sh_addralign = sizeof(Elf_Word);
373}
374
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000375static uint32_t hashSysv(StringRef Name) {
Rui Ueyama5f1eee1a2015-10-15 21:27:17 +0000376 uint32_t H = 0;
377 for (char C : Name) {
378 H = (H << 4) + C;
379 uint32_t G = H & 0xf0000000;
380 if (G)
381 H ^= G >> 24;
382 H &= ~G;
383 }
384 return H;
385}
386
Rui Ueyama0db335f2015-10-07 16:58:54 +0000387template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000388 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000389
George Rimare9e1d322016-02-18 15:17:01 +0000390 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000391 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000392
393 // Create as many buckets as there are symbols.
394 // FIXME: This is simplistic. We can try to optimize it, but implementing
395 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000396 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000397 this->Header.sh_size = NumEntries * sizeof(Elf_Word);
398}
399
400template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000401 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000402 auto *P = reinterpret_cast<Elf_Word *>(Buf);
403 *P++ = NumSymbols; // nbucket
404 *P++ = NumSymbols; // nchain
405
406 Elf_Word *Buckets = P;
407 Elf_Word *Chains = P + NumSymbols;
408
Rafael Espindolae2c24612016-01-29 01:24:25 +0000409 for (const std::pair<SymbolBody *, unsigned> &P :
410 Out<ELFT>::DynSymTab->getSymbols()) {
411 SymbolBody *Body = P.first;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000412 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000413 unsigned I = Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000414 uint32_t Hash = hashSysv(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000415 Chains[I] = Buckets[Hash];
416 Buckets[Hash] = I;
417 }
418}
419
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000420static uint32_t hashGnu(StringRef Name) {
421 uint32_t H = 5381;
422 for (uint8_t C : Name)
423 H = (H << 5) + H + C;
424 return H;
425}
426
427template <class ELFT>
428GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000429 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000430 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000431 this->Header.sh_addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000432}
433
434template <class ELFT>
435unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
436 if (!NumHashed)
437 return 0;
438
439 // These values are prime numbers which are not greater than 2^(N-1) + 1.
440 // In result, for any particular NumHashed we return a prime number
441 // which is not greater than NumHashed.
442 static const unsigned Primes[] = {
443 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
444 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
445
446 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
447 array_lengthof(Primes) - 1)];
448}
449
450// Bloom filter estimation: at least 8 bits for each hashed symbol.
451// GNU Hash table requirement: it should be a power of 2,
452// the minimum value is 1, even for an empty table.
453// Expected results for a 32-bit target:
454// calcMaskWords(0..4) = 1
455// calcMaskWords(5..8) = 2
456// calcMaskWords(9..16) = 4
457// For a 64-bit target:
458// calcMaskWords(0..8) = 1
459// calcMaskWords(9..16) = 2
460// calcMaskWords(17..32) = 4
461template <class ELFT>
462unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
463 if (!NumHashed)
464 return 1;
465 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
466}
467
468template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000469 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000470 NBuckets = calcNBuckets(NumHashed);
471 MaskWords = calcMaskWords(NumHashed);
472 // Second hash shift estimation: just predefined values.
473 Shift2 = ELFT::Is64Bits ? 6 : 5;
474
475 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
476 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header
477 + sizeof(Elf_Off) * MaskWords // Bloom Filter
478 + sizeof(Elf_Word) * NBuckets // Hash Buckets
479 + sizeof(Elf_Word) * NumHashed; // Hash Values
480}
481
482template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
483 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000484 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000485 return;
486 writeBloomFilter(Buf);
487 writeHashTable(Buf);
488}
489
490template <class ELFT>
491void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
492 auto *P = reinterpret_cast<Elf_Word *>(Buf);
493 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000494 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000495 *P++ = MaskWords;
496 *P++ = Shift2;
497 Buf = reinterpret_cast<uint8_t *>(P);
498}
499
500template <class ELFT>
501void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
502 unsigned C = sizeof(Elf_Off) * 8;
503
504 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000505 for (const SymbolData &Sym : Symbols) {
506 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
507 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
508 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000509 Masks[Pos] |= V;
510 }
511 Buf += sizeof(Elf_Off) * MaskWords;
512}
513
514template <class ELFT>
515void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
516 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
517 Elf_Word *Values = Buckets + NBuckets;
518
519 int PrevBucket = -1;
520 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000521 for (const SymbolData &Sym : Symbols) {
522 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000523 assert(PrevBucket <= Bucket);
524 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000525 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000526 PrevBucket = Bucket;
527 if (I > 0)
528 Values[I - 1] |= 1;
529 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000530 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000531 ++I;
532 }
533 if (I > 0)
534 Values[I - 1] |= 1;
535}
536
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000537// Add symbols to this symbol hash table. Note that this function
538// destructively sort a given vector -- which is needed because
539// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000540template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000541void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000542 std::vector<std::pair<SymbolBody *, size_t>> &V) {
543 auto Mid = std::stable_partition(V.begin(), V.end(),
544 [](std::pair<SymbolBody *, size_t> &P) {
George Rimar71a0a402016-06-08 12:57:14 +0000545 return P.first->isUndefined();
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000546 });
547 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000548 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000549 for (auto I = Mid, E = V.end(); I != E; ++I) {
550 SymbolBody *B = I->first;
551 size_t StrOff = I->second;
552 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
553 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000554
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000555 unsigned NBuckets = calcNBuckets(Symbols.size());
556 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000557 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000558 return L.Hash % NBuckets < R.Hash % NBuckets;
559 });
560
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000561 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000562 for (const SymbolData &Sym : Symbols)
563 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000564}
565
566template <class ELFT>
Rui Ueyamaace4f902016-05-24 04:25:47 +0000567DynamicSection<ELFT>::DynamicSection()
568 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000569 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000570 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000571 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000572
573 // .dynamic section is not writable on MIPS.
574 // See "Special Section" in Chapter 4 in the following document:
575 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
576 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000577 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000578}
579
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000580template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000581 if (this->Header.sh_size)
582 return; // Already finalized.
583
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000584 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000585 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000586
Rafael Espindolae2c24612016-01-29 01:24:25 +0000587 auto Add = [=](Entry E) { Entries.push_back(E); };
588
589 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000590 // DynStrTab and doing this here allows this function to set DT_STRSZ.
591 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000592 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
593 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rui Ueyamaace4f902016-05-24 04:25:47 +0000594 for (const std::unique_ptr<SharedFile<ELFT>> &F :
595 Symtab<ELFT>::X->getSharedFiles())
Rafael Espindolade069362016-01-25 21:32:04 +0000596 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000597 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
598 if (!Config->SoName.empty())
599 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
600
Rafael Espindolade069362016-01-25 21:32:04 +0000601 Out<ELFT>::DynStrTab->finalize();
602
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000603 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000604 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000605 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
606 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
607 Add({IsRela ? DT_RELAENT : DT_RELENT,
608 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000609 }
George Rimar648a2c32015-10-20 08:54:27 +0000610 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000611 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
612 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
613 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
614 Out<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000615 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000616 }
617
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000618 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
619 Add({DT_SYMENT, sizeof(Elf_Sym)});
620 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
621 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000622 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000623 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000624 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000625 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000626
Rafael Espindolade069362016-01-25 21:32:04 +0000627 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000628 Add({DT_PREINIT_ARRAY, PreInitArraySec});
629 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000630 }
631 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000632 Add({DT_INIT_ARRAY, InitArraySec});
633 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000634 }
635 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000636 Add({DT_FINI_ARRAY, FiniArraySec});
637 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000638 }
639
Rui Ueyamaace4f902016-05-24 04:25:47 +0000640 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000641 Add({DT_INIT, B});
Rui Ueyamaace4f902016-05-24 04:25:47 +0000642 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000643 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000644
Rafael Espindolade069362016-01-25 21:32:04 +0000645 uint32_t DtFlags = 0;
646 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000647 if (Config->Bsymbolic)
648 DtFlags |= DF_SYMBOLIC;
649 if (Config->ZNodelete)
650 DtFlags1 |= DF_1_NODELETE;
651 if (Config->ZNow) {
652 DtFlags |= DF_BIND_NOW;
653 DtFlags1 |= DF_1_NOW;
654 }
655 if (Config->ZOrigin) {
656 DtFlags |= DF_ORIGIN;
657 DtFlags1 |= DF_1_ORIGIN;
658 }
659
660 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000661 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000662 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000663 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000664
Ed Mastef5d3cf62016-01-06 15:52:27 +0000665 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000666 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000667
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000668 if (size_t NeedNum = Out<ELFT>::VerNeed->getNeedNum()) {
669 Add({DT_VERSYM, Out<ELFT>::VerSym});
670 Add({DT_VERNEED, Out<ELFT>::VerNeed});
671 Add({DT_VERNEEDNUM, NeedNum});
672 }
673
Igor Kudrin304860a2015-11-12 04:39:49 +0000674 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000675 Add({DT_MIPS_RLD_VERSION, 1});
676 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
677 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
678 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
679 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000680 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000681 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000682 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000683 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
684 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000685 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000686 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000687 }
688
Rafael Espindolade069362016-01-25 21:32:04 +0000689 // +1 for DT_NULL
690 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000691}
692
693template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000694 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
695
Rafael Espindolade069362016-01-25 21:32:04 +0000696 for (const Entry &E : Entries) {
697 P->d_tag = E.Tag;
698 switch (E.Kind) {
699 case Entry::SecAddr:
700 P->d_un.d_ptr = E.OutSec->getVA();
701 break;
702 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000703 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000704 break;
705 case Entry::PlainInt:
706 P->d_un.d_val = E.Val;
707 break;
708 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000709 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000710 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000711}
712
713template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000714EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyamade9777a2016-05-23 16:30:41 +0000715 : OutputSectionBase<ELFT>(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
George Rimarf6bc65a2016-01-15 13:34:52 +0000716
Rui Ueyama95a232e2016-05-23 01:45:05 +0000717// .eh_frame_hdr contains a binary search table of pointers to FDEs.
718// Each entry of the search table consists of two values,
719// the starting PC from where FDEs covers, and the FDE's address.
720// It is sorted by PC.
George Rimarf6bc65a2016-01-15 13:34:52 +0000721template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
722 const endianness E = ELFT::TargetEndianness;
723
Rui Ueyamae75e9332016-05-23 03:00:33 +0000724 // Sort the FDE list by their PC and uniqueify. Usually there is only
725 // one FDE for a PC (i.e. function), but if ICF merges two functions
726 // into one, there can be more than one FDEs pointing to the address.
727 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
728 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
729 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
730 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
Peter Collingbournec98de132016-04-11 16:40:08 +0000731
Rui Ueyama1b2936f2016-05-23 01:31:10 +0000732 Buf[0] = 1;
733 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
734 Buf[2] = DW_EH_PE_udata4;
735 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama3b31e672016-05-23 16:24:16 +0000736 write32<E>(Buf + 4, Out<ELFT>::EhFrame->getVA() - this->getVA() - 4);
Rui Ueyamae75e9332016-05-23 03:00:33 +0000737 write32<E>(Buf + 8, Fdes.size());
George Rimarf6bc65a2016-01-15 13:34:52 +0000738 Buf += 12;
739
Rui Ueyamae75e9332016-05-23 03:00:33 +0000740 uintX_t VA = this->getVA();
741 for (FdeData &Fde : Fdes) {
742 write32<E>(Buf, Fde.Pc - VA);
743 write32<E>(Buf + 4, Fde.FdeVA - VA);
George Rimarf6bc65a2016-01-15 13:34:52 +0000744 Buf += 8;
745 }
746}
747
Rui Ueyamade9777a2016-05-23 16:30:41 +0000748template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
749 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
750 this->Header.sh_size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
751}
752
George Rimarf6bc65a2016-01-15 13:34:52 +0000753template <class ELFT>
Rui Ueyamae75e9332016-05-23 03:00:33 +0000754void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
755 Fdes.push_back({Pc, FdeVA});
George Rimarf6bc65a2016-01-15 13:34:52 +0000756}
757
George Rimarf6bc65a2016-01-15 13:34:52 +0000758template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000759OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
760 : OutputSectionBase<ELFT>(Name, Type, Flags) {
761 if (Type == SHT_RELA)
762 this->Header.sh_entsize = sizeof(Elf_Rela);
763 else if (Type == SHT_REL)
764 this->Header.sh_entsize = sizeof(Elf_Rel);
765}
766
767template <class ELFT> void OutputSection<ELFT>::finalize() {
768 uint32_t Type = this->Header.sh_type;
769 if (Type != SHT_RELA && Type != SHT_REL)
770 return;
771 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
772 // sh_info for SHT_REL[A] sections should contain the section header index of
773 // the section to which the relocation applies.
774 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
775 this->Header.sh_info = S->OutSec->SectionIndex;
776}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000777
778template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000779void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000780 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000781 auto *S = cast<InputSection<ELFT>>(C);
782 Sections.push_back(S);
783 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000784 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000785}
786
Rui Ueyamac4185702016-02-10 23:20:42 +0000787// If an input string is in the form of "foo.N" where N is a number,
788// return N. Otherwise, returns 65536, which is one greater than the
789// lowest priority.
790static int getPriority(StringRef S) {
791 size_t Pos = S.rfind('.');
792 if (Pos == StringRef::npos)
793 return 65536;
794 int V;
795 if (S.substr(Pos + 1).getAsInteger(10, V))
796 return 65536;
797 return V;
798}
799
Rafael Espindola56004c52016-04-07 14:22:09 +0000800template <class ELFT>
801void OutputSection<ELFT>::forEachInputSection(
Rui Ueyama10803512016-05-22 00:25:30 +0000802 std::function<void(InputSectionBase<ELFT> *)> F) {
Rafael Espindola56004c52016-04-07 14:22:09 +0000803 for (InputSection<ELFT> *S : Sections)
804 F(S);
Rui Ueyama5af83682016-02-11 23:41:38 +0000805}
806
Rui Ueyamac4185702016-02-10 23:20:42 +0000807// Sorts input sections by section name suffixes, so that .foo.N comes
808// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000809// We want to keep the original order if the priorities are the same
810// because the compiler keeps the original initialization order in a
811// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000812// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000813template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000814 // Sort sections by priority.
815 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000816 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
817
Rui Ueyamac4185702016-02-10 23:20:42 +0000818 std::vector<Pair> V;
819 for (InputSection<ELFT> *S : Sections)
820 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000821 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000822 Sections.clear();
823 for (Pair &P : V)
824 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000825}
Rui Ueyamac4185702016-02-10 23:20:42 +0000826
Rui Ueyama5af83682016-02-11 23:41:38 +0000827// Returns true if S matches /Filename.?\.o$/.
828static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
829 if (!S.endswith(".o"))
830 return false;
831 S = S.drop_back(2);
832 if (S.endswith(Filename))
833 return true;
834 return !S.empty() && S.drop_back().endswith(Filename);
835}
836
837static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
838static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
839
840// .ctors and .dtors are sorted by this priority from highest to lowest.
841//
842// 1. The section was contained in crtbegin (crtbegin contains
843// some sentinel value in its .ctors and .dtors so that the runtime
844// can find the beginning of the sections.)
845//
846// 2. The section has an optional priority value in the form of ".ctors.N"
847// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
848// they are compared as string rather than number.
849//
850// 3. The section is just ".ctors" or ".dtors".
851//
852// 4. The section was contained in crtend, which contains an end marker.
853//
854// In an ideal world, we don't need this function because .init_array and
855// .ctors are duplicate features (and .init_array is newer.) However, there
856// are too many real-world use cases of .ctors, so we had no choice to
857// support that with this rather ad-hoc semantics.
858template <class ELFT>
859static bool compCtors(const InputSection<ELFT> *A,
860 const InputSection<ELFT> *B) {
861 bool BeginA = isCrtbegin(A->getFile()->getName());
862 bool BeginB = isCrtbegin(B->getFile()->getName());
863 if (BeginA != BeginB)
864 return BeginA;
865 bool EndA = isCrtend(A->getFile()->getName());
866 bool EndB = isCrtend(B->getFile()->getName());
867 if (EndA != EndB)
868 return EndB;
869 StringRef X = A->getSectionName();
870 StringRef Y = B->getSectionName();
871 assert(X.startswith(".ctors") || X.startswith(".dtors"));
872 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
873 X = X.substr(6);
874 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000875 if (X.empty() && Y.empty())
876 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000877 return X < Y;
878}
879
880// Sorts input sections by the special rules for .ctors and .dtors.
881// Unfortunately, the rules are different from the one for .{init,fini}_array.
882// Read the comment above.
883template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
884 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +0000885}
886
George Rimare2ee72b2016-02-26 14:48:31 +0000887static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
888 size_t I = 0;
889 for (; I + A.size() < Size; I += A.size())
890 memcpy(Buf + I, A.data(), A.size());
891 memcpy(Buf + I, A.data(), Size - I);
892}
893
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000894template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama07320e42016-04-20 20:13:41 +0000895 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
George Rimare2ee72b2016-02-26 14:48:31 +0000896 if (!Filler.empty())
897 fill(Buf, this->getSize(), Filler);
Rui Ueyamae9809502016-03-11 04:23:12 +0000898 if (Config->Threads) {
899 parallel_for_each(Sections.begin(), Sections.end(),
900 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
901 } else {
902 for (InputSection<ELFT> *C : Sections)
903 C->writeTo(Buf);
904 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000905}
906
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000907template <class ELFT>
Rui Ueyamaf86cb902016-05-23 15:12:41 +0000908EhOutputSection<ELFT>::EhOutputSection()
Rui Ueyama3b31e672016-05-23 16:24:16 +0000909 : OutputSectionBase<ELFT>(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000910
911template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000912void EhOutputSection<ELFT>::forEachInputSection(
Rafael Espindola56004c52016-04-07 14:22:09 +0000913 std::function<void(InputSectionBase<ELFT> *)> F) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000914 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola56004c52016-04-07 14:22:09 +0000915 F(S);
916}
917
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000918// Returns the first relocation that points to a region
919// between Begin and Begin+Size.
920template <class IntTy, class RelTy>
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000921static const RelTy *getReloc(IntTy Begin, IntTy Size, ArrayRef<RelTy> &Rels) {
922 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
923 if (I->r_offset < Begin)
924 continue;
925
926 // Truncate Rels for fast access. That means we expect that the
927 // relocations are sorted and we are looking up symbols in
928 // sequential order. It is naturally satisfied for .eh_frame.
929 Rels = Rels.slice(I - Rels.begin());
930 if (I->r_offset < Begin + Size)
931 return I;
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000932 return nullptr;
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000933 }
934 Rels = ArrayRef<RelTy>();
935 return nullptr;
Rui Ueyama6bf7d912016-05-21 19:06:33 +0000936}
937
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000938// Search for an existing CIE record or create a new one.
939// CIE records from input object files are uniquified by their contents
940// and where their relocations point to.
941template <class ELFT>
942template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000943CieRecord *EhOutputSection<ELFT>::addCie(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000944 EhInputSection<ELFT> *Sec,
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000945 ArrayRef<RelTy> &Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000946 const endianness E = ELFT::TargetEndianness;
Rui Ueyamad8849272016-05-25 16:37:01 +0000947 if (read32<E>(Piece.data().data() + 4) != 0)
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000948 fatal("CIE expected at beginning of .eh_frame: " + Sec->getSectionName());
949
950 SymbolBody *Personality = nullptr;
951 if (const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels))
952 Personality = &Sec->getFile()->getRelocTargetSym(*Rel);
953
954 // Search for an existing CIE by CIE contents/relocation target pair.
Rui Ueyamad8849272016-05-25 16:37:01 +0000955 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000956
957 // If not found, create a new one.
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000958 if (Cie->Piece == nullptr) {
959 Cie->Piece = &Piece;
Rui Ueyamae2060aa2016-05-22 23:52:56 +0000960 Cies.push_back(Cie);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000961 }
962 return Cie;
963}
964
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000965// There is one FDE per function. Returns true if a given FDE
966// points to a live function.
967template <class ELFT>
968template <class RelTy>
Rui Ueyama1e479c22016-05-23 15:07:59 +0000969bool EhOutputSection<ELFT>::isFdeLive(SectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000970 EhInputSection<ELFT> *Sec,
Rui Ueyama19ccffe2016-05-24 15:40:46 +0000971 ArrayRef<RelTy> &Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +0000972 const RelTy *Rel = getReloc(Piece.InputOff, Piece.size(), Rels);
973 if (!Rel)
974 fatal("FDE doesn't reference another section");
975 SymbolBody &B = Sec->getFile()->getRelocTargetSym(*Rel);
976 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
977 if (!D || !D->Section)
978 return false;
979 InputSectionBase<ELFT> *Target = D->Section->Repl;
980 return Target && Target->Live;
981}
982
983// .eh_frame is a sequence of CIE or FDE records. In general, there
984// is one CIE record per input object file which is followed by
985// a list of FDEs. This function searches an existing CIE or create a new
986// one and associates FDEs to the CIE.
Rui Ueyamac0c92602016-02-05 22:56:03 +0000987template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +0000988template <class RelTy>
Rui Ueyama0b9a9032016-05-24 04:19:20 +0000989void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +0000990 ArrayRef<RelTy> Rels) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000991 const endianness E = ELFT::TargetEndianness;
Rafael Espindola820f4bb2016-05-24 15:17:47 +0000992
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000993 DenseMap<size_t, CieRecord *> OffsetToCie;
Rafael Espindola5ee9e7f2016-05-24 19:14:09 +0000994 for (SectionPiece &Piece : Sec->Pieces) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000995 // The empty record is the end marker.
Rui Ueyamad8849272016-05-25 16:37:01 +0000996 if (Piece.size() == 4)
Rafael Espindola5ee9e7f2016-05-24 19:14:09 +0000997 return;
Rafael Espindola1f5696f2016-05-24 16:03:27 +0000998
999 size_t Offset = Piece.InputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001000 uint32_t ID = read32<E>(Piece.data().data() + 4);
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001001 if (ID == 0) {
1002 OffsetToCie[Offset] = addCie(Piece, Sec, Rels);
1003 continue;
1004 }
1005
1006 uint32_t CieOffset = Offset + 4 - ID;
1007 CieRecord *Cie = OffsetToCie[CieOffset];
1008 if (!Cie)
1009 fatal("invalid CIE reference");
1010
1011 if (!isFdeLive(Piece, Sec, Rels))
1012 continue;
1013 Cie->FdePieces.push_back(&Piece);
Rui Ueyamade9777a2016-05-23 16:30:41 +00001014 NumFdes++;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001015 }
1016}
1017
1018template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001019void EhOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001020 auto *Sec = cast<EhInputSection<ELFT>>(C);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001021 Sec->OutSec = this;
1022 this->updateAlign(Sec->Align);
1023 Sections.push_back(Sec);
1024
1025 // .eh_frame is a sequence of CIE or FDE records. This function
1026 // splits it into pieces so that we can call
1027 // SplitInputSection::getSectionPiece on the section.
Rui Ueyama88abd9b2016-05-22 23:53:00 +00001028 Sec->split();
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001029 if (Sec->Pieces.empty())
1030 return;
1031
1032 if (const Elf_Shdr *RelSec = Sec->RelocSection) {
1033 ELFFile<ELFT> &Obj = Sec->getFile()->getObj();
1034 if (RelSec->sh_type == SHT_RELA)
1035 addSectionAux(Sec, Obj.relas(RelSec));
1036 else
1037 addSectionAux(Sec, Obj.rels(RelSec));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001038 return;
1039 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001040 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001041}
1042
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001043template <class ELFT>
Rui Ueyama644ac652016-05-22 00:17:11 +00001044static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1045 memcpy(Buf, D.data(), D.size());
Rui Ueyamac0449a62016-05-21 18:10:13 +00001046
1047 // Fix the size field. -4 since size does not include the size field itself.
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001048 const endianness E = ELFT::TargetEndianness;
Rui Ueyama644ac652016-05-22 00:17:11 +00001049 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
Rafael Espindola56004c52016-04-07 14:22:09 +00001050}
1051
Rui Ueyama1e479c22016-05-23 15:07:59 +00001052template <class ELFT> void EhOutputSection<ELFT>::finalize() {
Rafael Espindola56004c52016-04-07 14:22:09 +00001053 if (Finalized)
1054 return;
1055 Finalized = true;
1056
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001057 size_t Off = 0;
1058 for (CieRecord *Cie : Cies) {
1059 Cie->Piece->OutputOff = Off;
1060 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001061
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001062 for (SectionPiece *Fde : Cie->FdePieces) {
1063 Fde->OutputOff = Off;
1064 Off += alignTo(Fde->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001065 }
1066 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001067 this->Header.sh_size = Off;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001068}
1069
Rui Ueyamae75e9332016-05-23 03:00:33 +00001070template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1071 const endianness E = ELFT::TargetEndianness;
1072 switch (Size) {
1073 case DW_EH_PE_udata2:
1074 return read16<E>(Buf);
1075 case DW_EH_PE_udata4:
1076 return read32<E>(Buf);
1077 case DW_EH_PE_udata8:
1078 return read64<E>(Buf);
1079 case DW_EH_PE_absptr:
1080 if (ELFT::Is64Bits)
1081 return read64<E>(Buf);
1082 return read32<E>(Buf);
1083 }
1084 fatal("unknown FDE size encoding");
1085}
1086
1087// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1088// We need it to create .eh_frame_hdr section.
1089template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001090typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
Rui Ueyamae75e9332016-05-23 03:00:33 +00001091 uint8_t Enc) {
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001092 // The starting address to which this FDE applies is
Rui Ueyamae75e9332016-05-23 03:00:33 +00001093 // stored at FDE + 8 byte.
1094 size_t Off = FdeOff + 8;
1095 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1096 if ((Enc & 0x70) == DW_EH_PE_absptr)
1097 return Addr;
1098 if ((Enc & 0x70) == DW_EH_PE_pcrel)
1099 return Addr + this->getVA() + Off;
1100 fatal("unknown FDE size relative encoding");
1101}
1102
Rui Ueyama1e479c22016-05-23 15:07:59 +00001103template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001104 const endianness E = ELFT::TargetEndianness;
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001105 for (CieRecord *Cie : Cies) {
1106 size_t CieOffset = Cie->Piece->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001107 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001108
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001109 for (SectionPiece *Fde : Cie->FdePieces) {
1110 size_t Off = Fde->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001111 writeCieFde<ELFT>(Buf + Off, Fde->data());
Rafael Espindola56004c52016-04-07 14:22:09 +00001112
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001113 // FDE's second word should have the offset to an associated CIE.
1114 // Write it.
1115 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001116 }
1117 }
1118
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001119 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola22ef9562016-04-13 01:40:19 +00001120 S->relocate(Buf, nullptr);
Rui Ueyamae75e9332016-05-23 03:00:33 +00001121
1122 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001123 // to get a FDE from an address to which FDE is applied. So here
Rui Ueyamae75e9332016-05-23 03:00:33 +00001124 // we obtain two addresses and pass them to EhFrameHdr object.
Rui Ueyama3b31e672016-05-23 16:24:16 +00001125 if (Out<ELFT>::EhFrameHdr) {
1126 for (CieRecord *Cie : Cies) {
Rui Ueyamad8849272016-05-25 16:37:01 +00001127 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->data());
Rui Ueyama3b31e672016-05-23 16:24:16 +00001128 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyama6de2e682016-05-24 02:08:38 +00001129 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rui Ueyama3b31e672016-05-23 16:24:16 +00001130 uintX_t FdeVA = this->getVA() + Fde->OutputOff;
1131 Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1132 }
Rui Ueyamae75e9332016-05-23 03:00:33 +00001133 }
1134 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001135}
1136
1137template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001138MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001139 uintX_t Flags, uintX_t Alignment)
1140 : OutputSectionBase<ELFT>(Name, Type, Flags),
1141 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001142
1143template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001144 if (shouldTailMerge()) {
1145 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001146 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001147 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001148 }
Rui Ueyama31f9f612016-05-06 00:52:08 +00001149 for (const std::pair<CachedHash<StringRef>, size_t> &P : Builder.getMap()) {
1150 StringRef Data = P.first.Val;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001151 memcpy(Buf + P.second, Data.data(), Data.size());
1152 }
1153}
1154
Rui Ueyama34dc99e2016-05-22 01:15:32 +00001155static StringRef toStringRef(ArrayRef<uint8_t> A) {
1156 return {(const char *)A.data(), A.size()};
1157}
1158
Rafael Espindolac159c962015-10-19 21:00:02 +00001159template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001160void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama10803512016-05-22 00:25:30 +00001161 auto *Sec = cast<MergeInputSection<ELFT>>(C);
1162 Sec->OutSec = this;
1163 this->updateAlign(Sec->Align);
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001164 this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize;
Rui Ueyama406b4692016-05-27 14:39:13 +00001165 Sections.push_back(Sec);
Rafael Espindolac159c962015-10-19 21:00:02 +00001166
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001167 bool IsString = this->Header.sh_flags & SHF_STRINGS;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001168
Rui Ueyamab7eda282016-05-24 02:10:28 +00001169 for (SectionPiece &Piece : Sec->Pieces) {
Rui Ueyama3ea87272016-05-22 00:13:04 +00001170 if (!Piece.Live)
Rafael Espindola0b9531c2016-04-22 22:09:35 +00001171 continue;
Rui Ueyamad8849272016-05-25 16:37:01 +00001172 uintX_t OutputOffset = Builder.add(toStringRef(Piece.data()));
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001173 if (!IsString || !shouldTailMerge())
1174 Piece.OutputOff = OutputOffset;
Rafael Espindolac159c962015-10-19 21:00:02 +00001175 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001176}
1177
1178template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001179unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1180 return Builder.getOffset(Val);
1181}
1182
1183template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1184 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1185}
1186
1187template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1188 if (shouldTailMerge())
1189 Builder.finalize();
1190 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001191}
1192
Rui Ueyama406b4692016-05-27 14:39:13 +00001193template <class ELFT> void MergeOutputSection<ELFT>::finalizePieces() {
1194 for (MergeInputSection<ELFT> *Sec : Sections)
1195 Sec->finalizePieces();
1196}
1197
Rafael Espindolac159c962015-10-19 21:00:02 +00001198template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001199StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001200 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1201 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001202 Dynamic(Dynamic) {
1203 this->Header.sh_addralign = 1;
1204}
1205
Rafael Espindolae2c24612016-01-29 01:24:25 +00001206// Adds a string to the string table. If HashIt is true we hash and check for
1207// duplicates. It is optional because the name of global symbols are already
1208// uniqued and hashing them again has a big cost for a small value: uniquing
1209// them with some other string that happens to be the same.
1210template <class ELFT>
1211unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1212 if (HashIt) {
1213 auto R = StringMap.insert(std::make_pair(S, Size));
1214 if (!R.second)
1215 return R.first->second;
1216 }
1217 unsigned Ret = Size;
1218 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001219 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001220 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001221}
1222
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001223template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001224 // ELF string tables start with NUL byte, so advance the pointer by one.
1225 ++Buf;
1226 for (StringRef S : Strings) {
1227 memcpy(Buf, S.data(), S.size());
1228 Buf += S.size() + 1;
1229 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001230}
1231
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001232template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001233SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamaace4f902016-05-24 04:25:47 +00001234 StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001235 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1236 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001237 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rui Ueyamaace4f902016-05-24 04:25:47 +00001238 StrTabSec(StrTabSec) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001239 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001240 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001241}
1242
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001243// Orders symbols according to their positions in the GOT,
1244// in compliance with MIPS ABI rules.
1245// See "Global Offset Table" in Chapter 5 in the following document
1246// for detailed description:
1247// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001248static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1249 const std::pair<SymbolBody *, unsigned> &R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001250 // Sort entries related to non-local preemptible symbols by GOT indexes.
1251 // All other entries go to the first part of GOT in arbitrary order.
1252 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible();
1253 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible();
1254 if (LIsInLocalGot || RIsInLocalGot)
1255 return !RIsInLocalGot;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001256 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001257}
1258
Rafael Espindolabadd3972016-04-08 15:30:56 +00001259static uint8_t getSymbolBinding(SymbolBody *Body) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001260 Symbol *S = Body->symbol();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001261 uint8_t Visibility = S->Visibility;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001262 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1263 return STB_LOCAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001264 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
Rafael Espindolabadd3972016-04-08 15:30:56 +00001265 return STB_GLOBAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001266 return S->Binding;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001267}
1268
Rui Ueyama0db335f2015-10-07 16:58:54 +00001269template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001270 if (this->Header.sh_size)
1271 return; // Already finalized.
1272
Rui Ueyama0db335f2015-10-07 16:58:54 +00001273 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001274 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001275 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001276
George Rimar58941ee2016-02-25 08:23:37 +00001277 if (Config->Relocatable) {
1278 size_t I = NumLocals;
1279 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1280 P.first->DynsymIndex = ++I;
1281 return;
1282 }
1283
Igor Kudrinab665fc2015-10-20 21:47:58 +00001284 if (!StrTabSec.isDynamic()) {
1285 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001286 [](const std::pair<SymbolBody *, unsigned> &L,
1287 const std::pair<SymbolBody *, unsigned> &R) {
1288 return getSymbolBinding(L.first) == STB_LOCAL &&
1289 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001290 });
1291 return;
1292 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001293 if (Out<ELFT>::GnuHashTab)
1294 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1295 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001296 else if (Config->EMachine == EM_MIPS)
1297 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001298 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001299 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001300 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001301}
1302
1303template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001304void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1305 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001306}
1307
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001308template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001309 Buf += sizeof(Elf_Sym);
1310
1311 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1312 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001313 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1314 writeLocalSymbols(Buf);
1315
1316 writeGlobalSymbols(Buf);
1317}
1318
1319template <class ELFT>
1320void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1321 // Iterate over all input object files to copy their local symbols
1322 // to the output symbol table pointed by Buf.
Rui Ueyamaace4f902016-05-24 04:25:47 +00001323 for (const std::unique_ptr<ObjectFile<ELFT>> &File :
1324 Symtab<ELFT>::X->getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001325 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1326 File->KeptLocalSyms) {
1327 const DefinedRegular<ELFT> &Body = *P.first;
1328 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001329 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001330
1331 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001332 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001333 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001334 } else {
Rafael Espindolac159c962015-10-19 21:00:02 +00001335 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1336 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001337 ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001338 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001339 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001340 ESym->st_size = Body.template getSize<ELFT>();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001341 ESym->setBindingAndType(STB_LOCAL, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001342 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001343 }
1344 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001345}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001346
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001347template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001348void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001349 // Write the internal symbol table contents to the output symbol table
1350 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001351 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001352 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001353 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001354 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001355
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001356 uint8_t Type = Body->Type;
1357 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001358
Igor Kudrin853b88d2015-10-20 20:52:14 +00001359 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001360 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001361 ESym->st_name = StrOff;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001362 ESym->setVisibility(Body->symbol()->Visibility);
Rui Ueyamab5a69702016-02-01 21:00:35 +00001363 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001364
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001365 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001366 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001367 else if (isa<DefinedRegular<ELFT>>(Body))
1368 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001369
1370 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1371 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1372 // distinguish such symbols and MIPS lazy-binding stubs.
1373 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1374 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1375 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001376 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001377 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001378 }
1379}
1380
Igor Kudrin853b88d2015-10-20 20:52:14 +00001381template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001382const OutputSectionBase<ELFT> *
1383SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1384 switch (Sym->kind()) {
1385 case SymbolBody::DefinedSyntheticKind:
Peter Collingbourne6a422592016-05-03 01:21:08 +00001386 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001387 case SymbolBody::DefinedRegularKind: {
Rafael Espindola5ffa13c2016-04-15 00:15:02 +00001388 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001389 if (D.Section)
1390 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001391 break;
1392 }
1393 case SymbolBody::DefinedCommonKind:
1394 return Out<ELFT>::Bss;
1395 case SymbolBody::SharedKind:
1396 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1397 return Out<ELFT>::Bss;
1398 break;
Peter Collingbourne60976ed2016-04-27 00:05:06 +00001399 case SymbolBody::UndefinedKind:
Rui Ueyamaf8baa662016-04-07 19:24:51 +00001400 case SymbolBody::LazyArchiveKind:
1401 case SymbolBody::LazyObjectKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001402 break;
1403 case SymbolBody::DefinedBitcodeKind:
Davide Italianof6523ae2016-03-29 02:20:10 +00001404 llvm_unreachable("should have been replaced");
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001405 }
1406 return nullptr;
1407}
1408
1409template <class ELFT>
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001410VersionTableSection<ELFT>::VersionTableSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001411 : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001412 this->Header.sh_addralign = sizeof(uint16_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001413}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001414
1415template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1416 this->Header.sh_size =
1417 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
1418 this->Header.sh_entsize = sizeof(Elf_Versym);
George Rimar8b3c5f22016-06-06 08:04:53 +00001419 // At the moment of june 2016 GNU docs does not mention that sh_link field
1420 // should be set, but Sun docs do. Also readelf relies on this field.
1421 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001422}
1423
1424template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1425 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1426 for (const std::pair<SymbolBody *, size_t> &P :
1427 Out<ELFT>::DynSymTab->getSymbols()) {
1428 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(P.first))
1429 OutVersym->vs_index = SS->VersionId;
1430 else
George Rimard50a1452016-06-08 11:40:24 +00001431 OutVersym->vs_index = VER_NDX_GLOBAL;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001432 ++OutVersym;
1433 }
1434}
1435
1436template <class ELFT>
1437VersionNeedSection<ELFT>::VersionNeedSection()
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001438 : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
Rafael Espindolaaae59562016-04-29 23:20:30 +00001439 this->Header.sh_addralign = sizeof(uint32_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001440}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001441
1442template <class ELFT>
1443void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1444 if (!SS->Verdef) {
George Rimar56efb3492016-06-08 11:49:01 +00001445 SS->VersionId = VER_NDX_GLOBAL;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001446 return;
1447 }
1448 SharedFile<ELFT> *F = SS->File;
1449 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1450 // to create one by adding it to our needed list and creating a dynstr entry
1451 // for the soname.
1452 if (F->VerdefMap.empty())
1453 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1454 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1455 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1456 // prepare to create one by allocating a version identifier and creating a
1457 // dynstr entry for the version name.
1458 if (NV.Index == 0) {
1459 NV.StrTab = Out<ELFT>::DynStrTab->addString(
1460 SS->File->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1461 NV.Index = NextIndex++;
1462 }
1463 SS->VersionId = NV.Index;
1464}
1465
1466template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1467 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1468 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1469 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1470
1471 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1472 // Create an Elf_Verneed for this DSO.
1473 Verneed->vn_version = 1;
1474 Verneed->vn_cnt = P.first->VerdefMap.size();
1475 Verneed->vn_file = P.second;
1476 Verneed->vn_aux =
1477 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1478 Verneed->vn_next = sizeof(Elf_Verneed);
1479 ++Verneed;
1480
1481 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1482 // VerdefMap, which will only contain references to needed version
1483 // definitions. Each Elf_Vernaux is based on the information contained in
1484 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1485 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1486 // data structures within a single input file.
1487 for (auto &NV : P.first->VerdefMap) {
1488 Vernaux->vna_hash = NV.first->vd_hash;
1489 Vernaux->vna_flags = 0;
1490 Vernaux->vna_other = NV.second.Index;
1491 Vernaux->vna_name = NV.second.StrTab;
1492 Vernaux->vna_next = sizeof(Elf_Vernaux);
1493 ++Vernaux;
1494 }
1495
1496 Vernaux[-1].vna_next = 0;
1497 }
1498 Verneed[-1].vn_next = 0;
1499}
1500
1501template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1502 this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1503 this->Header.sh_info = Needed.size();
1504 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1505 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1506 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1507 this->Header.sh_size = Size;
1508}
1509
1510template <class ELFT>
Rui Ueyama3a41be22016-04-07 22:49:21 +00001511BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1512 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1513 HashSize(HashSize) {
1514 // 16 bytes for the note section header.
1515 this->Header.sh_size = 16 + HashSize;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001516}
1517
1518template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1519 const endianness E = ELFT::TargetEndianness;
1520 write32<E>(Buf, 4); // Name size
Rui Ueyama3a41be22016-04-07 22:49:21 +00001521 write32<E>(Buf + 4, HashSize); // Content size
Rui Ueyama634ddf02016-03-11 20:51:53 +00001522 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1523 memcpy(Buf + 12, "GNU", 4); // Name string
1524 HashBuf = Buf + 16;
1525}
1526
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001527template <class ELFT>
1528void BuildIdFnv1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
Rui Ueyama634ddf02016-03-11 20:51:53 +00001529 const endianness E = ELFT::TargetEndianness;
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001530
1531 // 64-bit FNV-1 hash
1532 uint64_t Hash = 0xcbf29ce484222325;
1533 for (ArrayRef<uint8_t> Buf : Bufs) {
1534 for (uint8_t B : Buf) {
1535 Hash *= 0x100000001b3;
1536 Hash ^= B;
1537 }
1538 }
Rui Ueyama3a41be22016-04-07 22:49:21 +00001539 write64<E>(this->HashBuf, Hash);
1540}
1541
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001542template <class ELFT>
1543void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1544 llvm::MD5 Hash;
1545 for (ArrayRef<uint8_t> Buf : Bufs)
1546 Hash.update(Buf);
Rui Ueyama3a41be22016-04-07 22:49:21 +00001547 MD5::MD5Result Res;
1548 Hash.final(Res);
1549 memcpy(this->HashBuf, Res, 16);
Rui Ueyama634ddf02016-03-11 20:51:53 +00001550}
1551
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001552template <class ELFT>
1553void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1554 llvm::SHA1 Hash;
1555 for (ArrayRef<uint8_t> Buf : Bufs)
1556 Hash.update(Buf);
Rui Ueyamad86ec302016-04-07 23:51:56 +00001557 memcpy(this->HashBuf, Hash.final().data(), 20);
1558}
1559
Rui Ueyama634ddf02016-03-11 20:51:53 +00001560template <class ELFT>
Rui Ueyama9194db72016-05-13 21:55:56 +00001561BuildIdHexstring<ELFT>::BuildIdHexstring()
1562 : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
1563
1564template <class ELFT>
1565void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1566 memcpy(this->HashBuf, Config->BuildIdVector.data(),
1567 Config->BuildIdVector.size());
1568}
1569
1570template <class ELFT>
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001571MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1572 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1573 this->Header.sh_addralign = 4;
1574 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1575 this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1576}
1577
1578template <class ELFT>
1579void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1580 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
Simon Atanasyan4ee29182016-04-27 05:31:28 +00001581 R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
Rui Ueyama70eed362016-01-06 22:42:43 +00001582 R->ri_gprmask = GprMask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001583}
1584
1585template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001586void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama70eed362016-01-06 22:42:43 +00001587 // Copy input object file's .reginfo gprmask to output.
Rui Ueyama40845e62015-12-26 05:51:07 +00001588 auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
Rui Ueyama70eed362016-01-06 22:42:43 +00001589 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan84bb3552016-05-26 20:46:01 +00001590 S->OutSec = this;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001591}
1592
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001593template <class ELFT>
1594MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection()
1595 : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS,
1596 SHF_ALLOC | SHF_MIPS_NOSTRIP) {
1597 this->Header.sh_addralign = 8;
1598 this->Header.sh_entsize = 1;
1599 this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1600}
1601
1602template <class ELFT>
1603void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1604 auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf);
1605 Opt->kind = ODK_REGINFO;
1606 Opt->size = this->Header.sh_size;
1607 Opt->section = 0;
1608 Opt->info = 0;
1609 auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt));
1610 Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1611 Reg->ri_gprmask = GprMask;
1612}
1613
1614template <class ELFT>
1615void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1616 auto *S = cast<MipsOptionsInputSection<ELFT>>(C);
1617 if (S->Reginfo)
1618 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan84bb3552016-05-26 20:46:01 +00001619 S->OutSec = this;
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001620}
1621
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001622namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001623namespace elf {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001624template class OutputSectionBase<ELF32LE>;
1625template class OutputSectionBase<ELF32BE>;
1626template class OutputSectionBase<ELF64LE>;
1627template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001628
George Rimarf6bc65a2016-01-15 13:34:52 +00001629template class EhFrameHeader<ELF32LE>;
1630template class EhFrameHeader<ELF32BE>;
1631template class EhFrameHeader<ELF64LE>;
1632template class EhFrameHeader<ELF64BE>;
1633
George Rimar648a2c32015-10-20 08:54:27 +00001634template class GotPltSection<ELF32LE>;
1635template class GotPltSection<ELF32BE>;
1636template class GotPltSection<ELF64LE>;
1637template class GotPltSection<ELF64BE>;
1638
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001639template class GotSection<ELF32LE>;
1640template class GotSection<ELF32BE>;
1641template class GotSection<ELF64LE>;
1642template class GotSection<ELF64BE>;
1643
1644template class PltSection<ELF32LE>;
1645template class PltSection<ELF32BE>;
1646template class PltSection<ELF64LE>;
1647template class PltSection<ELF64BE>;
1648
1649template class RelocationSection<ELF32LE>;
1650template class RelocationSection<ELF32BE>;
1651template class RelocationSection<ELF64LE>;
1652template class RelocationSection<ELF64BE>;
1653
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001654template class InterpSection<ELF32LE>;
1655template class InterpSection<ELF32BE>;
1656template class InterpSection<ELF64LE>;
1657template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001658
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001659template class GnuHashTableSection<ELF32LE>;
1660template class GnuHashTableSection<ELF32BE>;
1661template class GnuHashTableSection<ELF64LE>;
1662template class GnuHashTableSection<ELF64BE>;
1663
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001664template class HashTableSection<ELF32LE>;
1665template class HashTableSection<ELF32BE>;
1666template class HashTableSection<ELF64LE>;
1667template class HashTableSection<ELF64BE>;
1668
1669template class DynamicSection<ELF32LE>;
1670template class DynamicSection<ELF32BE>;
1671template class DynamicSection<ELF64LE>;
1672template class DynamicSection<ELF64BE>;
1673
1674template class OutputSection<ELF32LE>;
1675template class OutputSection<ELF32BE>;
1676template class OutputSection<ELF64LE>;
1677template class OutputSection<ELF64BE>;
1678
Rui Ueyama1e479c22016-05-23 15:07:59 +00001679template class EhOutputSection<ELF32LE>;
1680template class EhOutputSection<ELF32BE>;
1681template class EhOutputSection<ELF64LE>;
1682template class EhOutputSection<ELF64BE>;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001683
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001684template class MipsReginfoOutputSection<ELF32LE>;
1685template class MipsReginfoOutputSection<ELF32BE>;
1686template class MipsReginfoOutputSection<ELF64LE>;
1687template class MipsReginfoOutputSection<ELF64BE>;
1688
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001689template class MipsOptionsOutputSection<ELF32LE>;
1690template class MipsOptionsOutputSection<ELF32BE>;
1691template class MipsOptionsOutputSection<ELF64LE>;
1692template class MipsOptionsOutputSection<ELF64BE>;
1693
Rafael Espindolac159c962015-10-19 21:00:02 +00001694template class MergeOutputSection<ELF32LE>;
1695template class MergeOutputSection<ELF32BE>;
1696template class MergeOutputSection<ELF64LE>;
1697template class MergeOutputSection<ELF64BE>;
1698
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001699template class StringTableSection<ELF32LE>;
1700template class StringTableSection<ELF32BE>;
1701template class StringTableSection<ELF64LE>;
1702template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001703
1704template class SymbolTableSection<ELF32LE>;
1705template class SymbolTableSection<ELF32BE>;
1706template class SymbolTableSection<ELF64LE>;
1707template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001708
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001709template class VersionTableSection<ELF32LE>;
1710template class VersionTableSection<ELF32BE>;
1711template class VersionTableSection<ELF64LE>;
1712template class VersionTableSection<ELF64BE>;
1713
1714template class VersionNeedSection<ELF32LE>;
1715template class VersionNeedSection<ELF32BE>;
1716template class VersionNeedSection<ELF64LE>;
1717template class VersionNeedSection<ELF64BE>;
1718
Rui Ueyama634ddf02016-03-11 20:51:53 +00001719template class BuildIdSection<ELF32LE>;
1720template class BuildIdSection<ELF32BE>;
1721template class BuildIdSection<ELF64LE>;
1722template class BuildIdSection<ELF64BE>;
Rui Ueyama3a41be22016-04-07 22:49:21 +00001723
1724template class BuildIdFnv1<ELF32LE>;
1725template class BuildIdFnv1<ELF32BE>;
1726template class BuildIdFnv1<ELF64LE>;
1727template class BuildIdFnv1<ELF64BE>;
1728
1729template class BuildIdMd5<ELF32LE>;
1730template class BuildIdMd5<ELF32BE>;
1731template class BuildIdMd5<ELF64LE>;
1732template class BuildIdMd5<ELF64BE>;
Rui Ueyamad86ec302016-04-07 23:51:56 +00001733
1734template class BuildIdSha1<ELF32LE>;
1735template class BuildIdSha1<ELF32BE>;
1736template class BuildIdSha1<ELF64LE>;
1737template class BuildIdSha1<ELF64BE>;
Rui Ueyama9194db72016-05-13 21:55:56 +00001738
1739template class BuildIdHexstring<ELF32LE>;
1740template class BuildIdHexstring<ELF32BE>;
1741template class BuildIdHexstring<ELF64LE>;
1742template class BuildIdHexstring<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001743}
1744}