blob: c291ff13f36efeadb50bccc8b41eae847aa9583c [file] [log] [blame]
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001//===- OutputSections.cpp -------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "OutputSections.h"
11#include "Config.h"
George Rimare2ee72b2016-02-26 14:48:31 +000012#include "LinkerScript.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000013#include "SymbolTable.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000014#include "Target.h"
Rui Ueyamae9809502016-03-11 04:23:12 +000015#include "lld/Core/Parallel.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000016#include "llvm/Support/Dwarf.h"
Rui Ueyama3a41be22016-04-07 22:49:21 +000017#include "llvm/Support/MD5.h"
Igor Kudrin1b0d7062015-10-22 08:21:35 +000018#include "llvm/Support/MathExtras.h"
Rui Ueyamad86ec302016-04-07 23:51:56 +000019#include "llvm/Support/SHA1.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000020#include <map>
Rafael Espindola5805c4f2015-09-21 21:38:08 +000021
Rafael Espindola5805c4f2015-09-21 21:38:08 +000022using namespace llvm;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +000023using namespace llvm::dwarf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000024using namespace llvm::object;
Rafael Espindolaa6627382015-10-06 23:56:53 +000025using namespace llvm::support::endian;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000026using namespace llvm::ELF;
27
28using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000029using namespace lld::elf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000030
George Rimar12737b72016-02-25 08:40:26 +000031static bool isAlpha(char C) {
32 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
33}
34
35static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
36
37// Returns true if S is valid as a C language identifier.
Rafael Espindolae0df00b2016-02-28 00:25:54 +000038bool elf::isValidCIdentifier(StringRef S) {
Rui Ueyamadad77c52016-02-26 15:42:06 +000039 return !S.empty() && isAlpha(S[0]) &&
40 std::all_of(S.begin() + 1, S.end(), isAlnum);
George Rimar12737b72016-02-25 08:40:26 +000041}
42
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000043template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +000044OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
45 uintX_t Flags)
Rafael Espindola5805c4f2015-09-21 21:38:08 +000046 : Name(Name) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000047 memset(&Header, 0, sizeof(Elf_Shdr));
Rui Ueyamad97e5c42016-01-07 18:33:11 +000048 Header.sh_type = Type;
49 Header.sh_flags = Flags;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000050}
51
Rafael Espindola35c6af32015-09-25 17:19:10 +000052template <class ELFT>
Rui Ueyamac63c1db2016-03-13 06:50:33 +000053void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
54 *Shdr = Header;
55}
56
57template <class ELFT>
George Rimar648a2c32015-10-20 08:54:27 +000058GotPltSection<ELFT>::GotPltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000059 : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
George Rimar648a2c32015-10-20 08:54:27 +000060 this->Header.sh_addralign = sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000061}
62
Rafael Espindola67d72c02016-03-11 12:06:30 +000063template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
64 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
65 Entries.push_back(&Sym);
George Rimar648a2c32015-10-20 08:54:27 +000066}
67
68template <class ELFT> bool GotPltSection<ELFT>::empty() const {
Igor Kudrin351b41d2015-11-16 17:44:08 +000069 return Entries.empty();
George Rimar648a2c32015-10-20 08:54:27 +000070}
71
George Rimar648a2c32015-10-20 08:54:27 +000072template <class ELFT> void GotPltSection<ELFT>::finalize() {
Igor Kudrin351b41d2015-11-16 17:44:08 +000073 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +000074 (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000075}
76
77template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +000078 Target->writeGotPltHeader(Buf);
Rui Ueyama724d6252016-01-29 01:49:32 +000079 Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000080 for (const SymbolBody *B : Entries) {
Rui Ueyamab5a69702016-02-01 21:00:35 +000081 Target->writeGotPlt(Buf, B->getPltVA<ELFT>());
George Rimar648a2c32015-10-20 08:54:27 +000082 Buf += sizeof(uintX_t);
83 }
84}
85
86template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +000087GotSection<ELFT>::GotSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000088 : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
Igor Kudrin15cd9ff2015-11-06 07:43:03 +000089 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +000090 this->Header.sh_flags |= SHF_MIPS_GPREL;
Rui Ueyama5f551ae2015-10-14 14:02:06 +000091 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +000092}
93
Rafael Espindola67d72c02016-03-11 12:06:30 +000094template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +000095 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanbea20c32016-03-23 09:28:02 +000096 // For "true" local symbols which can be referenced from the same module
97 // only compiler creates two instructions for address loading:
98 //
99 // lw $8, 0($gp) # R_MIPS_GOT16
100 // addi $8, $8, 0 # R_MIPS_LO16
101 //
102 // The first instruction loads high 16 bits of the symbol address while
103 // the second adds an offset. That allows to reduce number of required
104 // GOT entries because only one global offset table entry is necessary
105 // for every 64 KBytes of local data. So for local symbols we need to
106 // allocate number of GOT entries to hold all required "page" addresses.
107 //
108 // All global symbols (hidden and regular) considered by compiler uniformly.
109 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
110 // to load address of the symbol. So for each such symbol we need to
111 // allocate dedicated GOT entry to store its address.
112 //
113 // If a symbol is preemptible we need help of dynamic linker to get its
114 // final address. The corresponding GOT entries are allocated in the
115 // "global" part of GOT. Entries for non preemptible global symbol allocated
116 // in the "local" part of GOT.
117 //
118 // See "Global Offset Table" in Chapter 5:
119 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyand2980d32016-03-29 14:07:22 +0000120 if (Sym.isLocal()) {
121 // At this point we do not know final symbol value so to reduce number
122 // of allocated GOT entries do the following trick. Save all output
123 // sections referenced by GOT relocations. Then later in the `finalize`
124 // method calculate number of "pages" required to cover all saved output
125 // section and allocate appropriate number of GOT entries.
126 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
127 MipsOutSections.insert(OutSec);
128 return;
129 }
130 if (!Sym.isPreemptible()) {
131 // In case of non-local symbols require an entry in the local part
132 // of MIPS GOT, we set GotIndex to 1 just to accent that this symbol
133 // has the GOT entry and escape creation more redundant GOT entries.
134 // FIXME (simon): We can try to store such symbols in the `Entries`
135 // container. But in that case we have to sort out that container
136 // and update GotIndex assigned to symbols.
137 Sym.GotIndex = 1;
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +0000138 ++MipsLocalEntries;
139 return;
140 }
141 }
Rafael Espindola67d72c02016-03-11 12:06:30 +0000142 Sym.GotIndex = Entries.size();
143 Entries.push_back(&Sym);
George Rimar687138c2015-11-13 16:28:53 +0000144}
145
Rafael Espindola67d72c02016-03-11 12:06:30 +0000146template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
147 if (Sym.hasGlobalDynIndex())
George Rimar90cd0a82015-12-01 19:20:26 +0000148 return false;
Rafael Espindola67d72c02016-03-11 12:06:30 +0000149 Sym.GlobalDynIndex = Target->GotHeaderEntriesNum + Entries.size();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000150 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindola67d72c02016-03-11 12:06:30 +0000151 Entries.push_back(&Sym);
George Rimar687138c2015-11-13 16:28:53 +0000152 Entries.push_back(nullptr);
George Rimar90cd0a82015-12-01 19:20:26 +0000153 return true;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000154}
155
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000156// Reserves TLS entries for a TLS module ID and a TLS block offset.
157// In total it takes two GOT slots.
158template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
159 if (TlsIndexOff != uint32_t(-1))
George Rimarb17f7392015-12-01 18:24:07 +0000160 return false;
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000161 TlsIndexOff = Entries.size() * sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000162 Entries.push_back(nullptr);
163 Entries.push_back(nullptr);
George Rimarb17f7392015-12-01 18:24:07 +0000164 return true;
Michael J. Spencer1e225612015-11-11 01:00:24 +0000165}
166
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000167template <class ELFT>
168typename GotSection<ELFT>::uintX_t
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000169GotSection<ELFT>::getMipsLocalPageAddr(uintX_t EntryValue) {
170 // Initialize the entry by the %hi(EntryValue) expression
171 // but without right-shifting.
172 return getMipsLocalEntryAddr((EntryValue + 0x8000) & ~0xffff);
173}
174
175template <class ELFT>
176typename GotSection<ELFT>::uintX_t
177GotSection<ELFT>::getMipsLocalEntryAddr(uintX_t EntryValue) {
Rui Ueyama724d6252016-01-29 01:49:32 +0000178 size_t NewIndex = Target->GotHeaderEntriesNum + MipsLocalGotPos.size();
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000179 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
180 assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries);
181 return this->getVA() + P.first->second * sizeof(uintX_t);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000182}
183
Igor Kudrin304860a2015-11-12 04:39:49 +0000184template <class ELFT>
George Rimar90cd0a82015-12-01 19:20:26 +0000185typename GotSection<ELFT>::uintX_t
186GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
187 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
188}
189
190template <class ELFT>
Rafael Espindola74031ba2016-04-07 15:20:56 +0000191typename GotSection<ELFT>::uintX_t
192GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
193 return B.GlobalDynIndex * sizeof(uintX_t);
194}
195
196template <class ELFT>
Igor Kudrin304860a2015-11-12 04:39:49 +0000197const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
198 return Entries.empty() ? nullptr : Entries.front();
199}
200
201template <class ELFT>
202unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
Rui Ueyama724d6252016-01-29 01:49:32 +0000203 return Target->GotHeaderEntriesNum + MipsLocalEntries;
Igor Kudrin304860a2015-11-12 04:39:49 +0000204}
205
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000206template <class ELFT> void GotSection<ELFT>::finalize() {
Simon Atanasyand2980d32016-03-29 14:07:22 +0000207 for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
208 // Calculate an upper bound of MIPS GOT entries required to store page
209 // addresses of local symbols. We assume the worst case - each 64kb
210 // page of the output section has at least one GOT relocation against it.
211 // Add 0x8000 to the section's size because the page address stored
212 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
213 MipsLocalEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
214 }
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000215 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +0000216 (Target->GotHeaderEntriesNum + MipsLocalEntries + Entries.size()) *
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000217 sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000218}
219
Rafael Espindolaa6627382015-10-06 23:56:53 +0000220template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +0000221 Target->writeGotHeader(Buf);
Rui Ueyama5cbf5d22016-02-02 02:29:03 +0000222 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000223 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
224 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
225 }
Rui Ueyama724d6252016-01-29 01:49:32 +0000226 Buf += Target->GotHeaderEntriesNum * sizeof(uintX_t);
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000227 Buf += MipsLocalEntries * sizeof(uintX_t);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000228 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000229 uint8_t *Entry = Buf;
230 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000231 if (!B)
232 continue;
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000233 // MIPS has special rules to fill up GOT entries.
234 // See "Global Offset Table" in Chapter 5 in the following document
235 // for detailed description:
236 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
237 // As the first approach, we can just store addresses for all symbols.
Rui Ueyamac4466602016-03-13 19:48:18 +0000238 if (Config->EMachine != EM_MIPS && B->isPreemptible())
Rafael Espindolaa6627382015-10-06 23:56:53 +0000239 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000240 uintX_t VA = B->getVA<ELFT>();
Rafael Espindolae782f672015-10-07 03:56:05 +0000241 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000242 }
243}
244
Rafael Espindola35c6af32015-09-25 17:19:10 +0000245template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000246PltSection<ELFT>::PltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000247 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000248 this->Header.sh_addralign = 16;
249}
250
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000251template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama242ddf42015-10-12 18:56:36 +0000252 size_t Off = 0;
Rui Ueyama9398f862016-01-29 04:15:02 +0000253 if (Target->UseLazyBinding) {
Rui Ueyama74937fc2016-02-02 02:53:58 +0000254 // At beginning of PLT, we have code to call the dynamic linker
255 // to resolve dynsyms at runtime. Write such code.
Rui Ueyama900e2d22016-01-29 03:51:49 +0000256 Target->writePltZero(Buf);
Rui Ueyama62515452016-01-29 03:00:32 +0000257 Off += Target->PltZeroSize;
George Rimar648a2c32015-10-20 08:54:27 +0000258 }
George Rimarfb5d7f22015-11-26 19:58:51 +0000259 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000260 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000261 unsigned RelOff = I.second;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000262 uint64_t Got =
263 Target->UseLazyBinding ? B->getGotPltVA<ELFT>() : B->getGotVA<ELFT>();
Rui Ueyama242ddf42015-10-12 18:56:36 +0000264 uint64_t Plt = this->getVA() + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000265 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000266 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000267 }
268}
269
Rafael Espindola67d72c02016-03-11 12:06:30 +0000270template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
271 Sym.PltIndex = Entries.size();
Rui Ueyama724d6252016-01-29 01:49:32 +0000272 unsigned RelOff = Target->UseLazyBinding
George Rimar77b77792015-11-25 22:15:01 +0000273 ? Out<ELFT>::RelaPlt->getRelocOffset()
274 : Out<ELFT>::RelaDyn->getRelocOffset();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000275 Entries.push_back(std::make_pair(&Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000276}
277
George Rimar648a2c32015-10-20 08:54:27 +0000278template <class ELFT> void PltSection<ELFT>::finalize() {
Rui Ueyama724d6252016-01-29 01:49:32 +0000279 this->Header.sh_size =
Rui Ueyama62515452016-01-29 03:00:32 +0000280 Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000281}
282
283template <class ELFT>
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000284RelocationSection<ELFT>::RelocationSection(StringRef Name)
285 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
286 SHF_ALLOC) {
287 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000288 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000289}
290
George Rimar5828c232015-11-30 17:49:19 +0000291template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000292void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000293 Relocs.push_back(Reloc);
294}
295
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000296template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000297 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rui Ueyama614be592016-03-13 05:23:40 +0000298 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000299 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rafael Espindolade9857e2016-02-04 21:33:05 +0000300 SymbolBody *Sym = Rel.Sym;
Rui Ueyamab0210e832016-01-26 00:24:57 +0000301
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000302 if (Config->Rela)
Rui Ueyama614be592016-03-13 05:23:40 +0000303 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend;
Rafael Espindola74031ba2016-04-07 15:20:56 +0000304 P->r_offset = Rel.OffsetInSec + Rel.OffsetSec->getVA();
Rafael Espindolade9857e2016-02-04 21:33:05 +0000305 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
306 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000307 }
308}
309
George Rimar77b77792015-11-25 22:15:01 +0000310template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rui Ueyama5a0b2f72016-02-05 19:13:18 +0000311 return this->Header.sh_entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000312}
313
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000314template <class ELFT> void RelocationSection<ELFT>::finalize() {
George Rimara07ff662015-12-21 10:12:06 +0000315 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
316 : Out<ELFT>::DynSymTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000317 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
318}
319
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000320template <class ELFT>
321InterpSection<ELFT>::InterpSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000322 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000323 this->Header.sh_size = Config->DynamicLinker.size() + 1;
324 this->Header.sh_addralign = 1;
325}
326
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000327template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1e720b92016-03-13 06:50:34 +0000328 StringRef S = Config->DynamicLinker;
329 memcpy(Buf, S.data(), S.size());
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000330}
331
Rafael Espindola35c6af32015-09-25 17:19:10 +0000332template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000333HashTableSection<ELFT>::HashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000334 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000335 this->Header.sh_entsize = sizeof(Elf_Word);
336 this->Header.sh_addralign = sizeof(Elf_Word);
337}
338
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000339static uint32_t hashSysv(StringRef Name) {
Rui Ueyama5f1eee1a2015-10-15 21:27:17 +0000340 uint32_t H = 0;
341 for (char C : Name) {
342 H = (H << 4) + C;
343 uint32_t G = H & 0xf0000000;
344 if (G)
345 H ^= G >> 24;
346 H &= ~G;
347 }
348 return H;
349}
350
Rui Ueyama0db335f2015-10-07 16:58:54 +0000351template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000352 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000353
George Rimare9e1d322016-02-18 15:17:01 +0000354 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000355 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000356
357 // Create as many buckets as there are symbols.
358 // FIXME: This is simplistic. We can try to optimize it, but implementing
359 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000360 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000361 this->Header.sh_size = NumEntries * sizeof(Elf_Word);
362}
363
364template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000365 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000366 auto *P = reinterpret_cast<Elf_Word *>(Buf);
367 *P++ = NumSymbols; // nbucket
368 *P++ = NumSymbols; // nchain
369
370 Elf_Word *Buckets = P;
371 Elf_Word *Chains = P + NumSymbols;
372
Rafael Espindolae2c24612016-01-29 01:24:25 +0000373 for (const std::pair<SymbolBody *, unsigned> &P :
374 Out<ELFT>::DynSymTab->getSymbols()) {
375 SymbolBody *Body = P.first;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000376 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000377 unsigned I = Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000378 uint32_t Hash = hashSysv(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000379 Chains[I] = Buckets[Hash];
380 Buckets[Hash] = I;
381 }
382}
383
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000384static uint32_t hashGnu(StringRef Name) {
385 uint32_t H = 5381;
386 for (uint8_t C : Name)
387 H = (H << 5) + H + C;
388 return H;
389}
390
391template <class ELFT>
392GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000393 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000394 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000395 this->Header.sh_addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000396}
397
398template <class ELFT>
399unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
400 if (!NumHashed)
401 return 0;
402
403 // These values are prime numbers which are not greater than 2^(N-1) + 1.
404 // In result, for any particular NumHashed we return a prime number
405 // which is not greater than NumHashed.
406 static const unsigned Primes[] = {
407 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
408 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
409
410 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
411 array_lengthof(Primes) - 1)];
412}
413
414// Bloom filter estimation: at least 8 bits for each hashed symbol.
415// GNU Hash table requirement: it should be a power of 2,
416// the minimum value is 1, even for an empty table.
417// Expected results for a 32-bit target:
418// calcMaskWords(0..4) = 1
419// calcMaskWords(5..8) = 2
420// calcMaskWords(9..16) = 4
421// For a 64-bit target:
422// calcMaskWords(0..8) = 1
423// calcMaskWords(9..16) = 2
424// calcMaskWords(17..32) = 4
425template <class ELFT>
426unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
427 if (!NumHashed)
428 return 1;
429 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
430}
431
432template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000433 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000434 NBuckets = calcNBuckets(NumHashed);
435 MaskWords = calcMaskWords(NumHashed);
436 // Second hash shift estimation: just predefined values.
437 Shift2 = ELFT::Is64Bits ? 6 : 5;
438
439 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
440 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header
441 + sizeof(Elf_Off) * MaskWords // Bloom Filter
442 + sizeof(Elf_Word) * NBuckets // Hash Buckets
443 + sizeof(Elf_Word) * NumHashed; // Hash Values
444}
445
446template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
447 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000448 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000449 return;
450 writeBloomFilter(Buf);
451 writeHashTable(Buf);
452}
453
454template <class ELFT>
455void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
456 auto *P = reinterpret_cast<Elf_Word *>(Buf);
457 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000458 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000459 *P++ = MaskWords;
460 *P++ = Shift2;
461 Buf = reinterpret_cast<uint8_t *>(P);
462}
463
464template <class ELFT>
465void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
466 unsigned C = sizeof(Elf_Off) * 8;
467
468 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000469 for (const SymbolData &Sym : Symbols) {
470 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
471 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
472 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000473 Masks[Pos] |= V;
474 }
475 Buf += sizeof(Elf_Off) * MaskWords;
476}
477
478template <class ELFT>
479void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
480 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
481 Elf_Word *Values = Buckets + NBuckets;
482
483 int PrevBucket = -1;
484 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000485 for (const SymbolData &Sym : Symbols) {
486 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000487 assert(PrevBucket <= Bucket);
488 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000489 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000490 PrevBucket = Bucket;
491 if (I > 0)
492 Values[I - 1] |= 1;
493 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000494 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000495 ++I;
496 }
497 if (I > 0)
498 Values[I - 1] |= 1;
499}
500
Rafael Espindola31f88882015-11-02 14:33:11 +0000501static bool includeInGnuHashTable(SymbolBody *B) {
Rui Ueyamac112c1b2016-01-29 02:17:01 +0000502 // Assume that includeInDynsym() is already checked.
Rafael Espindola31f88882015-11-02 14:33:11 +0000503 return !B->isUndefined();
504}
505
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000506// Add symbols to this symbol hash table. Note that this function
507// destructively sort a given vector -- which is needed because
508// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000509template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000510void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000511 std::vector<std::pair<SymbolBody *, size_t>> &V) {
512 auto Mid = std::stable_partition(V.begin(), V.end(),
513 [](std::pair<SymbolBody *, size_t> &P) {
514 return !includeInGnuHashTable(P.first);
515 });
516 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000517 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000518 for (auto I = Mid, E = V.end(); I != E; ++I) {
519 SymbolBody *B = I->first;
520 size_t StrOff = I->second;
521 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
522 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000523
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000524 unsigned NBuckets = calcNBuckets(Symbols.size());
525 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000526 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000527 return L.Hash % NBuckets < R.Hash % NBuckets;
528 });
529
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000530 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000531 for (const SymbolData &Sym : Symbols)
532 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000533}
534
535template <class ELFT>
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000536DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000537 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE),
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000538 SymTab(SymTab) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000539 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000540 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000541 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000542
543 // .dynamic section is not writable on MIPS.
544 // See "Special Section" in Chapter 4 in the following document:
545 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
546 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000547 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000548}
549
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000550template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000551 if (this->Header.sh_size)
552 return; // Already finalized.
553
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000554 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000555 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000556
Rafael Espindolae2c24612016-01-29 01:24:25 +0000557 auto Add = [=](Entry E) { Entries.push_back(E); };
558
559 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000560 // DynStrTab and doing this here allows this function to set DT_STRSZ.
561 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000562 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
563 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rafael Espindolade069362016-01-25 21:32:04 +0000564 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
565 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000566 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
567 if (!Config->SoName.empty())
568 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
569
Rafael Espindolade069362016-01-25 21:32:04 +0000570 Out<ELFT>::DynStrTab->finalize();
571
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000572 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000573 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000574 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
575 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
576 Add({IsRela ? DT_RELAENT : DT_RELENT,
577 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000578 }
George Rimar648a2c32015-10-20 08:54:27 +0000579 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000580 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
581 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
582 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
583 Out<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000584 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000585 }
586
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000587 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
588 Add({DT_SYMENT, sizeof(Elf_Sym)});
589 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
590 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000591 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000592 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000593 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000594 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000595
Rafael Espindolade069362016-01-25 21:32:04 +0000596 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000597 Add({DT_PREINIT_ARRAY, PreInitArraySec});
598 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000599 }
600 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000601 Add({DT_INIT_ARRAY, InitArraySec});
602 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000603 }
604 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000605 Add({DT_FINI_ARRAY, FiniArraySec});
606 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000607 }
608
Rui Ueyama304d1352016-01-25 21:47:25 +0000609 if (SymbolBody *B = SymTab.find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000610 Add({DT_INIT, B});
Rui Ueyama304d1352016-01-25 21:47:25 +0000611 if (SymbolBody *B = SymTab.find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000612 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000613
Rafael Espindolade069362016-01-25 21:32:04 +0000614 uint32_t DtFlags = 0;
615 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000616 if (Config->Bsymbolic)
617 DtFlags |= DF_SYMBOLIC;
618 if (Config->ZNodelete)
619 DtFlags1 |= DF_1_NODELETE;
620 if (Config->ZNow) {
621 DtFlags |= DF_BIND_NOW;
622 DtFlags1 |= DF_1_NOW;
623 }
624 if (Config->ZOrigin) {
625 DtFlags |= DF_ORIGIN;
626 DtFlags1 |= DF_1_ORIGIN;
627 }
628
629 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000630 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000631 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000632 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000633
Ed Mastef5d3cf62016-01-06 15:52:27 +0000634 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000635 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000636
Igor Kudrin304860a2015-11-12 04:39:49 +0000637 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000638 Add({DT_MIPS_RLD_VERSION, 1});
639 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
640 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
641 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
642 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000643 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000644 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000645 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000646 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
647 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000648 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000649 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000650 }
651
Rafael Espindolade069362016-01-25 21:32:04 +0000652 // +1 for DT_NULL
653 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000654}
655
656template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000657 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
658
Rafael Espindolade069362016-01-25 21:32:04 +0000659 for (const Entry &E : Entries) {
660 P->d_tag = E.Tag;
661 switch (E.Kind) {
662 case Entry::SecAddr:
663 P->d_un.d_ptr = E.OutSec->getVA();
664 break;
665 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000666 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000667 break;
668 case Entry::PlainInt:
669 P->d_un.d_val = E.Val;
670 break;
671 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000672 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000673 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000674}
675
676template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000677EhFrameHeader<ELFT>::EhFrameHeader()
678 : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS,
679 SHF_ALLOC) {
680 // It's a 4 bytes of header + pointer to the contents of the .eh_frame section
681 // + the number of FDE pointers in the table.
682 this->Header.sh_size = 12;
683}
684
685// We have to get PC values of FDEs. They depend on relocations
686// which are target specific, so we run this code after performing
687// all relocations. We read the values from ouput buffer according to the
688// encoding given for FDEs. Return value is an offset to the initial PC value
689// for the FDE.
690template <class ELFT>
691typename EhFrameHeader<ELFT>::uintX_t
692EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) {
693 const endianness E = ELFT::TargetEndianness;
Simon Atanasyanea423e22016-03-02 05:38:42 +0000694 uint8_t Size = F.Enc & 0x7;
695 if (Size == DW_EH_PE_absptr)
696 Size = sizeof(uintX_t) == 8 ? DW_EH_PE_udata8 : DW_EH_PE_udata4;
697 uint64_t PC;
698 switch (Size) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000699 case DW_EH_PE_udata2:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000700 PC = read16<E>(F.PCRel);
701 break;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000702 case DW_EH_PE_udata4:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000703 PC = read32<E>(F.PCRel);
704 break;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000705 case DW_EH_PE_udata8:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000706 PC = read64<E>(F.PCRel);
707 break;
708 default:
George Rimar57610422016-03-11 14:43:02 +0000709 fatal("unknown FDE size encoding");
George Rimarf6bc65a2016-01-15 13:34:52 +0000710 }
Simon Atanasyanea423e22016-03-02 05:38:42 +0000711 switch (F.Enc & 0x70) {
712 case DW_EH_PE_absptr:
713 return PC;
714 case DW_EH_PE_pcrel:
715 return PC + EhVA + F.Off + 8;
716 default:
George Rimar57610422016-03-11 14:43:02 +0000717 fatal("unknown FDE size relative encoding");
Simon Atanasyanea423e22016-03-02 05:38:42 +0000718 }
George Rimarf6bc65a2016-01-15 13:34:52 +0000719}
720
721template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
722 const endianness E = ELFT::TargetEndianness;
723
Peter Collingbournec98de132016-04-11 16:40:08 +0000724 uintX_t EhVA = Sec->getVA();
725 uintX_t VA = this->getVA();
726
727 // InitialPC -> Offset in .eh_frame, sorted by InitialPC, and deduplicate PCs.
728 // FIXME: Deduplication leaves unneeded null bytes at the end of the section.
729 std::map<uintX_t, size_t> PcToOffset;
730 for (const FdeData &F : FdeList)
731 PcToOffset[getFdePc(EhVA, F)] = F.Off;
732
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000733 const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4,
734 DW_EH_PE_udata4,
735 DW_EH_PE_datarel | DW_EH_PE_sdata4};
George Rimarf6bc65a2016-01-15 13:34:52 +0000736 memcpy(Buf, Header, sizeof(Header));
737
George Rimarf6bc65a2016-01-15 13:34:52 +0000738 uintX_t EhOff = EhVA - VA - 4;
739 write32<E>(Buf + 4, EhOff);
Peter Collingbournec98de132016-04-11 16:40:08 +0000740 write32<E>(Buf + 8, PcToOffset.size());
George Rimarf6bc65a2016-01-15 13:34:52 +0000741 Buf += 12;
742
George Rimarf6bc65a2016-01-15 13:34:52 +0000743 for (auto &I : PcToOffset) {
744 // The first four bytes are an offset to the initial PC value for the FDE.
745 write32<E>(Buf, I.first - VA);
746 // The last four bytes are an offset to the FDE data itself.
747 write32<E>(Buf + 4, EhVA + I.second - VA);
748 Buf += 8;
749 }
750}
751
752template <class ELFT>
753void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) {
George Rimar45ca88d2016-01-25 19:27:50 +0000754 assert((!this->Sec || this->Sec == Sec) &&
755 "multiple .eh_frame sections not supported for .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000756 Live = Config->EhFrameHdr;
757 this->Sec = Sec;
758}
759
760template <class ELFT>
761void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000762 if (Live && (Enc & 0xF0) == DW_EH_PE_datarel)
Rui Ueyama64cfffd2016-01-28 18:40:06 +0000763 fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000764 FdeList.push_back(FdeData{Enc, Off, PCRel});
765}
766
767template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() {
768 // Each FDE entry is 8 bytes long:
769 // The first four bytes are an offset to the initial PC value for the FDE. The
770 // last four byte are an offset to the FDE data itself.
771 this->Header.sh_size += 8;
772}
773
774template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000775OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
776 : OutputSectionBase<ELFT>(Name, Type, Flags) {
777 if (Type == SHT_RELA)
778 this->Header.sh_entsize = sizeof(Elf_Rela);
779 else if (Type == SHT_REL)
780 this->Header.sh_entsize = sizeof(Elf_Rel);
781}
782
783template <class ELFT> void OutputSection<ELFT>::finalize() {
784 uint32_t Type = this->Header.sh_type;
785 if (Type != SHT_RELA && Type != SHT_REL)
786 return;
787 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
788 // sh_info for SHT_REL[A] sections should contain the section header index of
789 // the section to which the relocation applies.
790 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
791 this->Header.sh_info = S->OutSec->SectionIndex;
792}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000793
794template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000795void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000796 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000797 auto *S = cast<InputSection<ELFT>>(C);
798 Sections.push_back(S);
799 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000800 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000801}
802
Rui Ueyamac4185702016-02-10 23:20:42 +0000803// If an input string is in the form of "foo.N" where N is a number,
804// return N. Otherwise, returns 65536, which is one greater than the
805// lowest priority.
806static int getPriority(StringRef S) {
807 size_t Pos = S.rfind('.');
808 if (Pos == StringRef::npos)
809 return 65536;
810 int V;
811 if (S.substr(Pos + 1).getAsInteger(10, V))
812 return 65536;
813 return V;
814}
815
Rafael Espindola56004c52016-04-07 14:22:09 +0000816template <class ELFT>
817void OutputSection<ELFT>::forEachInputSection(
818 std::function<void(InputSectionBase<ELFT> *S)> F) {
819 for (InputSection<ELFT> *S : Sections)
820 F(S);
Rui Ueyama5af83682016-02-11 23:41:38 +0000821}
822
Rui Ueyamac4185702016-02-10 23:20:42 +0000823// Sorts input sections by section name suffixes, so that .foo.N comes
824// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000825// We want to keep the original order if the priorities are the same
826// because the compiler keeps the original initialization order in a
827// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000828// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000829template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000830 // Sort sections by priority.
831 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000832 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
833
Rui Ueyamac4185702016-02-10 23:20:42 +0000834 std::vector<Pair> V;
835 for (InputSection<ELFT> *S : Sections)
836 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000837 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000838 Sections.clear();
839 for (Pair &P : V)
840 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000841}
Rui Ueyamac4185702016-02-10 23:20:42 +0000842
Rui Ueyama5af83682016-02-11 23:41:38 +0000843// Returns true if S matches /Filename.?\.o$/.
844static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
845 if (!S.endswith(".o"))
846 return false;
847 S = S.drop_back(2);
848 if (S.endswith(Filename))
849 return true;
850 return !S.empty() && S.drop_back().endswith(Filename);
851}
852
853static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
854static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
855
856// .ctors and .dtors are sorted by this priority from highest to lowest.
857//
858// 1. The section was contained in crtbegin (crtbegin contains
859// some sentinel value in its .ctors and .dtors so that the runtime
860// can find the beginning of the sections.)
861//
862// 2. The section has an optional priority value in the form of ".ctors.N"
863// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
864// they are compared as string rather than number.
865//
866// 3. The section is just ".ctors" or ".dtors".
867//
868// 4. The section was contained in crtend, which contains an end marker.
869//
870// In an ideal world, we don't need this function because .init_array and
871// .ctors are duplicate features (and .init_array is newer.) However, there
872// are too many real-world use cases of .ctors, so we had no choice to
873// support that with this rather ad-hoc semantics.
874template <class ELFT>
875static bool compCtors(const InputSection<ELFT> *A,
876 const InputSection<ELFT> *B) {
877 bool BeginA = isCrtbegin(A->getFile()->getName());
878 bool BeginB = isCrtbegin(B->getFile()->getName());
879 if (BeginA != BeginB)
880 return BeginA;
881 bool EndA = isCrtend(A->getFile()->getName());
882 bool EndB = isCrtend(B->getFile()->getName());
883 if (EndA != EndB)
884 return EndB;
885 StringRef X = A->getSectionName();
886 StringRef Y = B->getSectionName();
887 assert(X.startswith(".ctors") || X.startswith(".dtors"));
888 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
889 X = X.substr(6);
890 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000891 if (X.empty() && Y.empty())
892 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000893 return X < Y;
894}
895
896// Sorts input sections by the special rules for .ctors and .dtors.
897// Unfortunately, the rules are different from the one for .{init,fini}_array.
898// Read the comment above.
899template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
900 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +0000901}
902
George Rimare2ee72b2016-02-26 14:48:31 +0000903static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
904 size_t I = 0;
905 for (; I + A.size() < Size; I += A.size())
906 memcpy(Buf + I, A.data(), A.size());
907 memcpy(Buf + I, A.data(), Size - I);
908}
909
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000910template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimare2ee72b2016-02-26 14:48:31 +0000911 ArrayRef<uint8_t> Filler = Script->getFiller(this->Name);
912 if (!Filler.empty())
913 fill(Buf, this->getSize(), Filler);
Rui Ueyamae9809502016-03-11 04:23:12 +0000914 if (Config->Threads) {
915 parallel_for_each(Sections.begin(), Sections.end(),
916 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
917 } else {
918 for (InputSection<ELFT> *C : Sections)
919 C->writeTo(Buf);
920 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000921}
922
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000923template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +0000924EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type,
925 uintX_t Flags)
George Rimarf6bc65a2016-01-15 13:34:52 +0000926 : OutputSectionBase<ELFT>(Name, Type, Flags) {
927 Out<ELFT>::EhFrameHdr->assignEhFrame(this);
928}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000929
930template <class ELFT>
Rafael Espindola56004c52016-04-07 14:22:09 +0000931void EHOutputSection<ELFT>::forEachInputSection(
932 std::function<void(InputSectionBase<ELFT> *)> F) {
933 for (EHInputSection<ELFT> *S : Sections)
934 F(S);
935}
936
937template <class ELFT>
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000938EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index)
939 : S(S), Index(Index) {}
940
941template <class ELFT> StringRef EHRegion<ELFT>::data() const {
942 ArrayRef<uint8_t> SecData = S->getSectionData();
943 ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets;
944 size_t Start = Offsets[Index].first;
945 size_t End =
946 Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first;
947 return StringRef((const char *)SecData.data() + Start, End - Start);
948}
949
950template <class ELFT>
951Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index)
952 : EHRegion<ELFT>(S, Index) {}
953
George Rimarf6bc65a2016-01-15 13:34:52 +0000954// Read a byte and advance D by one byte.
955static uint8_t readByte(ArrayRef<uint8_t> &D) {
956 if (D.empty())
George Rimar57610422016-03-11 14:43:02 +0000957 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +0000958 uint8_t B = D.front();
959 D = D.slice(1);
960 return B;
961}
962
963static void skipLeb128(ArrayRef<uint8_t> &D) {
964 while (!D.empty()) {
965 uint8_t Val = D.front();
966 D = D.slice(1);
967 if ((Val & 0x80) == 0)
968 return;
969 }
George Rimar57610422016-03-11 14:43:02 +0000970 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +0000971}
972
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000973template <class ELFT> static size_t getAugPSize(unsigned Enc) {
974 switch (Enc & 0x0f) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000975 case DW_EH_PE_absptr:
976 case DW_EH_PE_signed:
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000977 return ELFT::Is64Bits ? 8 : 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000978 case DW_EH_PE_udata2:
979 case DW_EH_PE_sdata2:
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000980 return 2;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000981 case DW_EH_PE_udata4:
982 case DW_EH_PE_sdata4:
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000983 return 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000984 case DW_EH_PE_udata8:
985 case DW_EH_PE_sdata8:
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000986 return 8;
987 }
George Rimar57610422016-03-11 14:43:02 +0000988 fatal("unknown FDE encoding");
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000989}
990
991template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) {
992 uint8_t Enc = readByte(D);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000993 if ((Enc & 0xf0) == DW_EH_PE_aligned)
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000994 fatal("DW_EH_PE_aligned encoding is not supported");
995 size_t Size = getAugPSize<ELFT>(Enc);
Rafael Espindola9e072d32016-02-09 22:47:34 +0000996 if (Size >= D.size())
George Rimar57610422016-03-11 14:43:02 +0000997 fatal("corrupted CIE");
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000998 D = D.slice(Size);
999}
1000
George Rimarf6bc65a2016-01-15 13:34:52 +00001001template <class ELFT>
1002uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) {
Rui Ueyamabe748c22016-02-08 05:18:44 +00001003 if (D.size() < 8)
1004 fatal("CIE too small");
George Rimarf6bc65a2016-01-15 13:34:52 +00001005 D = D.slice(8);
1006
1007 uint8_t Version = readByte(D);
1008 if (Version != 1 && Version != 3)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001009 fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version));
George Rimarf6bc65a2016-01-15 13:34:52 +00001010
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001011 const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0');
Rui Ueyamabe748c22016-02-08 05:18:44 +00001012 if (AugEnd == D.end())
George Rimar57610422016-03-11 14:43:02 +00001013 fatal("corrupted CIE");
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001014 StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin());
Rui Ueyamabe748c22016-02-08 05:18:44 +00001015 D = D.slice(Aug.size() + 1);
George Rimarf6bc65a2016-01-15 13:34:52 +00001016
1017 // Code alignment factor should always be 1 for .eh_frame.
1018 if (readByte(D) != 1)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001019 fatal("CIE code alignment must be 1");
Rui Ueyamabe748c22016-02-08 05:18:44 +00001020
1021 // Skip data alignment factor.
George Rimarf6bc65a2016-01-15 13:34:52 +00001022 skipLeb128(D);
1023
1024 // Skip the return address register. In CIE version 1 this is a single
1025 // byte. In CIE version 3 this is an unsigned LEB128.
1026 if (Version == 1)
1027 readByte(D);
1028 else
1029 skipLeb128(D);
1030
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001031 // We only care about an 'R' value, but other records may precede an 'R'
1032 // record. Records are not in TLV (type-length-value) format, so we need
1033 // to teach the linker how to skip records for each type.
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001034 for (char C : Aug) {
1035 if (C == 'R')
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001036 return readByte(D);
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001037 if (C == 'z') {
1038 skipLeb128(D);
1039 continue;
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001040 }
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001041 if (C == 'P') {
1042 skipAugP<ELFT>(D);
1043 continue;
1044 }
Simon Atanasyanea423e22016-03-02 05:38:42 +00001045 if (C == 'L') {
1046 readByte(D);
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001047 continue;
Simon Atanasyanea423e22016-03-02 05:38:42 +00001048 }
George Rimar57610422016-03-11 14:43:02 +00001049 fatal("unknown .eh_frame augmentation string: " + Aug);
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001050 }
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001051 return DW_EH_PE_absptr;
George Rimarf6bc65a2016-01-15 13:34:52 +00001052}
1053
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001054template <class ELFT>
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001055static typename ELFT::uint readEntryLength(ArrayRef<uint8_t> D) {
Rui Ueyamac0c92602016-02-05 22:56:03 +00001056 const endianness E = ELFT::TargetEndianness;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001057 if (D.size() < 4)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001058 fatal("CIE/FDE too small");
1059
1060 // First 4 bytes of CIE/FDE is the size of the record.
1061 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead.
1062 uint64_t V = read32<E>(D.data());
1063 if (V < UINT32_MAX) {
1064 uint64_t Len = V + 4;
1065 if (Len > D.size())
Rui Ueyamac0c92602016-02-05 22:56:03 +00001066 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001067 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001068 }
1069
1070 if (D.size() < 12)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001071 fatal("CIE/FDE too small");
1072 V = read64<E>(D.data() + 4);
1073 uint64_t Len = V + 12;
1074 if (Len < V || D.size() < Len)
Rui Ueyamac0c92602016-02-05 22:56:03 +00001075 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001076 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001077}
1078
1079template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +00001080template <class RelTy>
1081void EHOutputSection<ELFT>::addSectionAux(EHInputSection<ELFT> *S,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +00001082 ArrayRef<RelTy> Rels) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001083 const endianness E = ELFT::TargetEndianness;
1084
1085 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001086 this->updateAlign(S->Align);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001087 Sections.push_back(S);
1088
1089 ArrayRef<uint8_t> SecData = S->getSectionData();
1090 ArrayRef<uint8_t> D = SecData;
1091 uintX_t Offset = 0;
1092 auto RelI = Rels.begin();
1093 auto RelE = Rels.end();
1094
George Rimar147747a2016-01-02 16:55:01 +00001095 DenseMap<unsigned, unsigned> OffsetToIndex;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001096 while (!D.empty()) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001097 unsigned Index = S->Offsets.size();
1098 S->Offsets.push_back(std::make_pair(Offset, -1));
1099
Rui Ueyamac0c92602016-02-05 22:56:03 +00001100 uintX_t Length = readEntryLength<ELFT>(D);
George Rimarf6bc65a2016-01-15 13:34:52 +00001101 // If CIE/FDE data length is zero then Length is 4, this
1102 // shall be considered a terminator and processing shall end.
1103 if (Length == 4)
1104 break;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001105 StringRef Entry((const char *)D.data(), Length);
1106
1107 while (RelI != RelE && RelI->r_offset < Offset)
1108 ++RelI;
1109 uintX_t NextOffset = Offset + Length;
1110 bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset;
1111
1112 uint32_t ID = read32<E>(D.data() + 4);
1113 if (ID == 0) {
1114 // CIE
1115 Cie<ELFT> C(S, Index);
George Rimarf6bc65a2016-01-15 13:34:52 +00001116 if (Config->EhFrameHdr)
1117 C.FdeEncoding = getFdeEncoding(D);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001118
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001119 SymbolBody *Personality = nullptr;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001120 if (HasReloc) {
1121 uint32_t SymIndex = RelI->getSymbol(Config->Mips64EL);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001122 Personality = &S->getFile()->getSymbolBody(SymIndex).repl();
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001123 }
1124
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001125 std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001126 auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size()));
George Rimar147747a2016-01-02 16:55:01 +00001127 if (P.second) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001128 Cies.push_back(C);
Rui Ueyama489a8062016-01-14 20:53:50 +00001129 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
George Rimar147747a2016-01-02 16:55:01 +00001130 }
1131 OffsetToIndex[Offset] = P.first->second;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001132 } else {
1133 if (!HasReloc)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001134 fatal("FDE doesn't reference another section");
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001135 InputSectionBase<ELFT> *Target = S->getRelocTarget(*RelI);
Rafael Espindola1f5b70f2016-03-11 14:21:37 +00001136 if (Target && Target->Live) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001137 uint32_t CieOffset = Offset + 4 - ID;
George Rimar147747a2016-01-02 16:55:01 +00001138 auto I = OffsetToIndex.find(CieOffset);
1139 if (I == OffsetToIndex.end())
George Rimar777f9632016-03-12 08:31:34 +00001140 fatal("invalid CIE reference");
George Rimar147747a2016-01-02 16:55:01 +00001141 Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index));
George Rimarf6bc65a2016-01-15 13:34:52 +00001142 Out<ELFT>::EhFrameHdr->reserveFde();
Rui Ueyama489a8062016-01-14 20:53:50 +00001143 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001144 }
1145 }
1146
1147 Offset = NextOffset;
1148 D = D.slice(Length);
1149 }
1150}
1151
1152template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001153void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1154 auto *S = cast<EHInputSection<ELFT>>(C);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001155 const Elf_Shdr *RelSec = S->RelocSection;
Rui Ueyama0de86c12016-01-27 22:23:44 +00001156 if (!RelSec) {
Rafael Espindola0f7ccc32016-04-05 14:47:28 +00001157 addSectionAux(S, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001158 return;
1159 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001160 ELFFile<ELFT> &Obj = S->getFile()->getObj();
1161 if (RelSec->sh_type == SHT_RELA)
Rui Ueyama0de86c12016-01-27 22:23:44 +00001162 addSectionAux(S, Obj.relas(RelSec));
1163 else
1164 addSectionAux(S, Obj.rels(RelSec));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001165}
1166
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001167template <class ELFT>
Rafael Espindola56004c52016-04-07 14:22:09 +00001168static void writeAlignedCieOrFde(StringRef Data, uint8_t *Buf) {
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001169 typedef typename ELFT::uint uintX_t;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001170 const endianness E = ELFT::TargetEndianness;
Rui Ueyama489a8062016-01-14 20:53:50 +00001171 uint64_t Len = alignTo(Data.size(), sizeof(uintX_t));
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001172 write32<E>(Buf, Len - 4);
1173 memcpy(Buf + 4, Data.data() + 4, Data.size() - 4);
Rafael Espindola56004c52016-04-07 14:22:09 +00001174}
1175
1176template <class ELFT> void EHOutputSection<ELFT>::finalize() {
1177 if (Finalized)
1178 return;
1179 Finalized = true;
1180
1181 size_t Offset = 0;
1182 for (const Cie<ELFT> &C : Cies) {
1183 C.S->Offsets[C.Index].second = Offset;
1184 Offset += alignTo(C.data().size(), sizeof(uintX_t));
1185
1186 for (const EHRegion<ELFT> &F : C.Fdes) {
1187 F.S->Offsets[F.Index].second = Offset;
1188 Offset += alignTo(F.data().size(), sizeof(uintX_t));
1189 }
1190 }
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001191}
1192
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001193template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1194 const endianness E = ELFT::TargetEndianness;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001195 for (const Cie<ELFT> &C : Cies) {
Rafael Espindola56004c52016-04-07 14:22:09 +00001196 size_t CieOffset = C.S->Offsets[C.Index].second;
1197 writeAlignedCieOrFde<ELFT>(C.data(), Buf + CieOffset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001198
1199 for (const EHRegion<ELFT> &F : C.Fdes) {
Rafael Espindola56004c52016-04-07 14:22:09 +00001200 size_t Offset = F.S->Offsets[F.Index].second;
1201 writeAlignedCieOrFde<ELFT>(F.data(), Buf + Offset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001202 write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer
Rafael Espindola56004c52016-04-07 14:22:09 +00001203
George Rimarf6bc65a2016-01-15 13:34:52 +00001204 Out<ELFT>::EhFrameHdr->addFde(C.FdeEncoding, Offset, Buf + Offset + 8);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001205 }
1206 }
1207
Rafael Espindola22ef9562016-04-13 01:40:19 +00001208 for (EHInputSection<ELFT> *S : Sections)
1209 S->relocate(Buf, nullptr);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001210}
1211
1212template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001213MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001214 uintX_t Flags, uintX_t Alignment)
1215 : OutputSectionBase<ELFT>(Name, Type, Flags),
1216 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001217
1218template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001219 if (shouldTailMerge()) {
1220 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001221 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001222 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001223 }
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001224 for (const std::pair<StringRef, size_t> &P : Builder.getMap()) {
1225 StringRef Data = P.first;
1226 memcpy(Buf + P.second, Data.data(), Data.size());
1227 }
1228}
1229
1230static size_t findNull(StringRef S, size_t EntSize) {
1231 // Optimize the common case.
1232 if (EntSize == 1)
1233 return S.find(0);
1234
1235 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1236 const char *B = S.begin() + I;
1237 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1238 return I;
1239 }
1240 return StringRef::npos;
Rafael Espindolac159c962015-10-19 21:00:02 +00001241}
1242
1243template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001244void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1245 auto *S = cast<MergeInputSection<ELFT>>(C);
Rafael Espindolac159c962015-10-19 21:00:02 +00001246 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001247 this->updateAlign(S->Align);
Rafael Espindolac159c962015-10-19 21:00:02 +00001248
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001249 ArrayRef<uint8_t> D = S->getSectionData();
George Rimarf940d592015-10-25 20:14:07 +00001250 StringRef Data((const char *)D.data(), D.size());
Rafael Espindolac159c962015-10-19 21:00:02 +00001251 uintX_t EntSize = S->getSectionHdr()->sh_entsize;
George Rimar0baa1d32016-03-18 09:28:39 +00001252 this->Header.sh_entsize = EntSize;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001253
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001254 // If this is of type string, the contents are null-terminated strings.
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001255 if (this->Header.sh_flags & SHF_STRINGS) {
Rui Ueyamaad87ff72016-01-06 02:52:24 +00001256 uintX_t Offset = 0;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001257 while (!Data.empty()) {
1258 size_t End = findNull(Data, EntSize);
1259 if (End == StringRef::npos)
George Rimar777f9632016-03-12 08:31:34 +00001260 fatal("string is not null terminated");
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001261 StringRef Entry = Data.substr(0, End + EntSize);
George Rimar4b40ebc2015-11-13 13:44:59 +00001262 uintX_t OutputOffset = Builder.add(Entry);
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001263 if (shouldTailMerge())
1264 OutputOffset = -1;
1265 S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1266 uintX_t Size = End + EntSize;
1267 Data = Data.substr(Size);
1268 Offset += Size;
1269 }
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001270 return;
1271 }
1272
1273 // If this is not of type string, every entry has the same size.
1274 for (unsigned I = 0, N = Data.size(); I != N; I += EntSize) {
1275 StringRef Entry = Data.substr(I, EntSize);
1276 size_t OutputOffset = Builder.add(Entry);
1277 S->Offsets.push_back(std::make_pair(I, OutputOffset));
Rafael Espindolac159c962015-10-19 21:00:02 +00001278 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001279}
1280
1281template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001282unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1283 return Builder.getOffset(Val);
1284}
1285
1286template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1287 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1288}
1289
1290template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1291 if (shouldTailMerge())
1292 Builder.finalize();
1293 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001294}
1295
1296template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001297StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001298 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1299 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001300 Dynamic(Dynamic) {
1301 this->Header.sh_addralign = 1;
1302}
1303
Rafael Espindolae2c24612016-01-29 01:24:25 +00001304// Adds a string to the string table. If HashIt is true we hash and check for
1305// duplicates. It is optional because the name of global symbols are already
1306// uniqued and hashing them again has a big cost for a small value: uniquing
1307// them with some other string that happens to be the same.
1308template <class ELFT>
1309unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1310 if (HashIt) {
1311 auto R = StringMap.insert(std::make_pair(S, Size));
1312 if (!R.second)
1313 return R.first->second;
1314 }
1315 unsigned Ret = Size;
1316 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001317 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001318 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001319}
1320
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001321template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001322 // ELF string tables start with NUL byte, so advance the pointer by one.
1323 ++Buf;
1324 for (StringRef S : Strings) {
1325 memcpy(Buf, S.data(), S.size());
1326 Buf += S.size() + 1;
1327 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001328}
1329
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001330template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001331SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001332 SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001333 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1334 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001335 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001336 StrTabSec(StrTabSec), Table(Table) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001337 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001338 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001339}
1340
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001341// Orders symbols according to their positions in the GOT,
1342// in compliance with MIPS ABI rules.
1343// See "Global Offset Table" in Chapter 5 in the following document
1344// for detailed description:
1345// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001346static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1347 const std::pair<SymbolBody *, unsigned> &R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001348 // Sort entries related to non-local preemptible symbols by GOT indexes.
1349 // All other entries go to the first part of GOT in arbitrary order.
1350 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible();
1351 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible();
1352 if (LIsInLocalGot || RIsInLocalGot)
1353 return !RIsInLocalGot;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001354 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001355}
1356
Rafael Espindolabadd3972016-04-08 15:30:56 +00001357static uint8_t getSymbolBinding(SymbolBody *Body) {
1358 uint8_t Visibility = Body->getVisibility();
1359 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1360 return STB_LOCAL;
1361 if (Config->NoGnuUnique && Body->Binding == STB_GNU_UNIQUE)
1362 return STB_GLOBAL;
1363 return Body->Binding;
1364}
1365
Rui Ueyama0db335f2015-10-07 16:58:54 +00001366template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001367 if (this->Header.sh_size)
1368 return; // Already finalized.
1369
Rui Ueyama0db335f2015-10-07 16:58:54 +00001370 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001371 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001372 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001373
George Rimar58941ee2016-02-25 08:23:37 +00001374 if (Config->Relocatable) {
1375 size_t I = NumLocals;
1376 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1377 P.first->DynsymIndex = ++I;
1378 return;
1379 }
1380
Igor Kudrinab665fc2015-10-20 21:47:58 +00001381 if (!StrTabSec.isDynamic()) {
1382 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001383 [](const std::pair<SymbolBody *, unsigned> &L,
1384 const std::pair<SymbolBody *, unsigned> &R) {
1385 return getSymbolBinding(L.first) == STB_LOCAL &&
1386 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001387 });
1388 return;
1389 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001390 if (Out<ELFT>::GnuHashTab)
1391 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1392 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001393 else if (Config->EMachine == EM_MIPS)
1394 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001395 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001396 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001397 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001398}
1399
1400template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001401void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1402 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001403}
1404
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001405template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001406 Buf += sizeof(Elf_Sym);
1407
1408 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1409 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001410 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1411 writeLocalSymbols(Buf);
1412
1413 writeGlobalSymbols(Buf);
1414}
1415
1416template <class ELFT>
1417void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1418 // Iterate over all input object files to copy their local symbols
1419 // to the output symbol table pointed by Buf.
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001420 for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001421 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1422 File->KeptLocalSyms) {
1423 const DefinedRegular<ELFT> &Body = *P.first;
1424 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001425 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001426
1427 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001428 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001429 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001430 } else {
Rafael Espindolac159c962015-10-19 21:00:02 +00001431 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1432 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001433 ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001434 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001435 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001436 ESym->st_size = Body.template getSize<ELFT>();
1437 ESym->setBindingAndType(Body.Binding, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001438 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001439 }
1440 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001441}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001442
Rafael Espindolab729b212016-04-08 15:43:43 +00001443static uint8_t getSymbolVisibility(SymbolBody *Body) {
1444 if (Body->isShared())
1445 return STV_DEFAULT;
1446 return Body->getVisibility();
1447}
1448
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001449template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001450void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001451 // Write the internal symbol table contents to the output symbol table
1452 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001453 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001454 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001455 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001456 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001457
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001458 uint8_t Type = Body->Type;
1459 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001460
Igor Kudrin853b88d2015-10-20 20:52:14 +00001461 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001462 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001463 ESym->st_name = StrOff;
Rafael Espindolab729b212016-04-08 15:43:43 +00001464 ESym->setVisibility(getSymbolVisibility(Body));
Rui Ueyamab5a69702016-02-01 21:00:35 +00001465 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001466
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001467 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001468 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001469 else if (isa<DefinedRegular<ELFT>>(Body))
1470 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001471
1472 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1473 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1474 // distinguish such symbols and MIPS lazy-binding stubs.
1475 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1476 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1477 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001478 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001479 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001480 }
1481}
1482
Igor Kudrin853b88d2015-10-20 20:52:14 +00001483template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001484const OutputSectionBase<ELFT> *
1485SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1486 switch (Sym->kind()) {
1487 case SymbolBody::DefinedSyntheticKind:
1488 return &cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1489 case SymbolBody::DefinedRegularKind: {
Rafael Espindola5ffa13c2016-04-15 00:15:02 +00001490 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001491 if (D.Section)
1492 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001493 break;
1494 }
1495 case SymbolBody::DefinedCommonKind:
1496 return Out<ELFT>::Bss;
1497 case SymbolBody::SharedKind:
1498 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1499 return Out<ELFT>::Bss;
1500 break;
1501 case SymbolBody::UndefinedElfKind:
Rafael Espindolaf4765732016-04-06 13:22:41 +00001502 case SymbolBody::UndefinedBitcodeKind:
Rui Ueyamaf8baa662016-04-07 19:24:51 +00001503 case SymbolBody::LazyArchiveKind:
1504 case SymbolBody::LazyObjectKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001505 break;
1506 case SymbolBody::DefinedBitcodeKind:
Davide Italianof6523ae2016-03-29 02:20:10 +00001507 llvm_unreachable("should have been replaced");
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001508 }
1509 return nullptr;
1510}
1511
1512template <class ELFT>
Rui Ueyama3a41be22016-04-07 22:49:21 +00001513BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1514 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1515 HashSize(HashSize) {
1516 // 16 bytes for the note section header.
1517 this->Header.sh_size = 16 + HashSize;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001518}
1519
1520template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1521 const endianness E = ELFT::TargetEndianness;
1522 write32<E>(Buf, 4); // Name size
Rui Ueyama3a41be22016-04-07 22:49:21 +00001523 write32<E>(Buf + 4, HashSize); // Content size
Rui Ueyama634ddf02016-03-11 20:51:53 +00001524 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1525 memcpy(Buf + 12, "GNU", 4); // Name string
1526 HashBuf = Buf + 16;
1527}
1528
Rui Ueyama3a41be22016-04-07 22:49:21 +00001529template <class ELFT> void BuildIdFnv1<ELFT>::update(ArrayRef<uint8_t> Buf) {
1530 // 64-bit FNV-1 hash
Rui Ueyama634ddf02016-03-11 20:51:53 +00001531 const uint64_t Prime = 0x100000001b3;
1532 for (uint8_t B : Buf) {
1533 Hash *= Prime;
1534 Hash ^= B;
1535 }
1536}
1537
Rui Ueyama3a41be22016-04-07 22:49:21 +00001538template <class ELFT> void BuildIdFnv1<ELFT>::writeBuildId() {
Rui Ueyama634ddf02016-03-11 20:51:53 +00001539 const endianness E = ELFT::TargetEndianness;
Rui Ueyama3a41be22016-04-07 22:49:21 +00001540 write64<E>(this->HashBuf, Hash);
1541}
1542
1543template <class ELFT> void BuildIdMd5<ELFT>::update(ArrayRef<uint8_t> Buf) {
1544 Hash.update(Buf);
1545}
1546
1547template <class ELFT> void BuildIdMd5<ELFT>::writeBuildId() {
1548 MD5::MD5Result Res;
1549 Hash.final(Res);
1550 memcpy(this->HashBuf, Res, 16);
Rui Ueyama634ddf02016-03-11 20:51:53 +00001551}
1552
Rui Ueyamad86ec302016-04-07 23:51:56 +00001553template <class ELFT> void BuildIdSha1<ELFT>::update(ArrayRef<uint8_t> Buf) {
1554 Hash.update(Buf);
1555}
1556
1557template <class ELFT> void BuildIdSha1<ELFT>::writeBuildId() {
1558 memcpy(this->HashBuf, Hash.final().data(), 20);
1559}
1560
Rui Ueyama634ddf02016-03-11 20:51:53 +00001561template <class ELFT>
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001562MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1563 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1564 this->Header.sh_addralign = 4;
1565 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1566 this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1567}
1568
1569template <class ELFT>
1570void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1571 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1572 R->ri_gp_value = getMipsGpAddr<ELFT>();
Rui Ueyama70eed362016-01-06 22:42:43 +00001573 R->ri_gprmask = GprMask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001574}
1575
1576template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001577void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama70eed362016-01-06 22:42:43 +00001578 // Copy input object file's .reginfo gprmask to output.
Rui Ueyama40845e62015-12-26 05:51:07 +00001579 auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
Rui Ueyama70eed362016-01-06 22:42:43 +00001580 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001581}
1582
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001583namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001584namespace elf {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001585template class OutputSectionBase<ELF32LE>;
1586template class OutputSectionBase<ELF32BE>;
1587template class OutputSectionBase<ELF64LE>;
1588template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001589
George Rimarf6bc65a2016-01-15 13:34:52 +00001590template class EhFrameHeader<ELF32LE>;
1591template class EhFrameHeader<ELF32BE>;
1592template class EhFrameHeader<ELF64LE>;
1593template class EhFrameHeader<ELF64BE>;
1594
George Rimar648a2c32015-10-20 08:54:27 +00001595template class GotPltSection<ELF32LE>;
1596template class GotPltSection<ELF32BE>;
1597template class GotPltSection<ELF64LE>;
1598template class GotPltSection<ELF64BE>;
1599
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001600template class GotSection<ELF32LE>;
1601template class GotSection<ELF32BE>;
1602template class GotSection<ELF64LE>;
1603template class GotSection<ELF64BE>;
1604
1605template class PltSection<ELF32LE>;
1606template class PltSection<ELF32BE>;
1607template class PltSection<ELF64LE>;
1608template class PltSection<ELF64BE>;
1609
1610template class RelocationSection<ELF32LE>;
1611template class RelocationSection<ELF32BE>;
1612template class RelocationSection<ELF64LE>;
1613template class RelocationSection<ELF64BE>;
1614
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001615template class InterpSection<ELF32LE>;
1616template class InterpSection<ELF32BE>;
1617template class InterpSection<ELF64LE>;
1618template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001619
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001620template class GnuHashTableSection<ELF32LE>;
1621template class GnuHashTableSection<ELF32BE>;
1622template class GnuHashTableSection<ELF64LE>;
1623template class GnuHashTableSection<ELF64BE>;
1624
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001625template class HashTableSection<ELF32LE>;
1626template class HashTableSection<ELF32BE>;
1627template class HashTableSection<ELF64LE>;
1628template class HashTableSection<ELF64BE>;
1629
1630template class DynamicSection<ELF32LE>;
1631template class DynamicSection<ELF32BE>;
1632template class DynamicSection<ELF64LE>;
1633template class DynamicSection<ELF64BE>;
1634
1635template class OutputSection<ELF32LE>;
1636template class OutputSection<ELF32BE>;
1637template class OutputSection<ELF64LE>;
1638template class OutputSection<ELF64BE>;
1639
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001640template class EHOutputSection<ELF32LE>;
1641template class EHOutputSection<ELF32BE>;
1642template class EHOutputSection<ELF64LE>;
1643template class EHOutputSection<ELF64BE>;
1644
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001645template class MipsReginfoOutputSection<ELF32LE>;
1646template class MipsReginfoOutputSection<ELF32BE>;
1647template class MipsReginfoOutputSection<ELF64LE>;
1648template class MipsReginfoOutputSection<ELF64BE>;
1649
Rafael Espindolac159c962015-10-19 21:00:02 +00001650template class MergeOutputSection<ELF32LE>;
1651template class MergeOutputSection<ELF32BE>;
1652template class MergeOutputSection<ELF64LE>;
1653template class MergeOutputSection<ELF64BE>;
1654
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001655template class StringTableSection<ELF32LE>;
1656template class StringTableSection<ELF32BE>;
1657template class StringTableSection<ELF64LE>;
1658template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001659
1660template class SymbolTableSection<ELF32LE>;
1661template class SymbolTableSection<ELF32BE>;
1662template class SymbolTableSection<ELF64LE>;
1663template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001664
1665template class BuildIdSection<ELF32LE>;
1666template class BuildIdSection<ELF32BE>;
1667template class BuildIdSection<ELF64LE>;
1668template class BuildIdSection<ELF64BE>;
Rui Ueyama3a41be22016-04-07 22:49:21 +00001669
1670template class BuildIdFnv1<ELF32LE>;
1671template class BuildIdFnv1<ELF32BE>;
1672template class BuildIdFnv1<ELF64LE>;
1673template class BuildIdFnv1<ELF64BE>;
1674
1675template class BuildIdMd5<ELF32LE>;
1676template class BuildIdMd5<ELF32BE>;
1677template class BuildIdMd5<ELF64LE>;
1678template class BuildIdMd5<ELF64BE>;
Rui Ueyamad86ec302016-04-07 23:51:56 +00001679
1680template class BuildIdSha1<ELF32LE>;
1681template class BuildIdSha1<ELF32BE>;
1682template class BuildIdSha1<ELF64LE>;
1683template class BuildIdSha1<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001684}
1685}