blob: e6b86f635e8f6da1e42f24661e2181422e3a91ba [file] [log] [blame]
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00001//===- SyntheticSections.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// This file contains linker-synthesized sections. Currently,
11// synthetic sections are created either output sections or input sections,
12// but we are rewriting code so that all synthetic sections are created as
13// input sections.
14//
15//===----------------------------------------------------------------------===//
16
17#include "SyntheticSections.h"
18#include "Config.h"
19#include "Error.h"
20#include "InputFiles.h"
Rui Ueyamae288eef2016-11-02 18:58:44 +000021#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000022#include "OutputSections.h"
23#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000024#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000025#include "Target.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000026#include "Writer.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000027
Rui Ueyama3da3f062016-11-10 20:20:37 +000028#include "lld/Config/Version.h"
George Rimar364b59e22016-11-06 07:42:55 +000029#include "lld/Core/Parallel.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000030#include "llvm/Support/Endian.h"
31#include "llvm/Support/MD5.h"
32#include "llvm/Support/RandomNumberGenerator.h"
33#include "llvm/Support/SHA1.h"
34#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000035#include <cstdlib>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000036
37using namespace llvm;
38using namespace llvm::ELF;
39using namespace llvm::object;
40using namespace llvm::support;
41using namespace llvm::support::endian;
42
43using namespace lld;
44using namespace lld::elf;
45
Rui Ueyamae8a61022016-11-05 23:05:47 +000046template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
47 std::vector<DefinedCommon *> V;
48 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
49 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
50 V.push_back(B);
51 return V;
52}
53
54// Find all common symbols and allocate space for them.
Rafael Espindola682a5bc2016-11-08 14:42:34 +000055template <class ELFT> InputSection<ELFT> *elf::createCommonSection() {
56 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
57 ArrayRef<uint8_t>(), "COMMON");
58 Ret->Live = true;
Rui Ueyamae8a61022016-11-05 23:05:47 +000059
60 // Sort the common symbols by alignment as an heuristic to pack them better.
61 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
62 std::stable_sort(Syms.begin(), Syms.end(),
63 [](const DefinedCommon *A, const DefinedCommon *B) {
64 return A->Alignment > B->Alignment;
65 });
66
67 // Assign offsets to symbols.
68 size_t Size = 0;
69 size_t Alignment = 1;
70 for (DefinedCommon *Sym : Syms) {
Rui Ueyama1c786822016-11-05 23:14:54 +000071 Alignment = std::max<size_t>(Alignment, Sym->Alignment);
Rui Ueyamae8a61022016-11-05 23:05:47 +000072 Size = alignTo(Size, Sym->Alignment);
73
74 // Compute symbol offset relative to beginning of input section.
75 Sym->Offset = Size;
76 Size += Sym->Size;
77 }
Rafael Espindola682a5bc2016-11-08 14:42:34 +000078 Ret->Alignment = Alignment;
79 Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
80 return Ret;
Rui Ueyamae8a61022016-11-05 23:05:47 +000081}
82
Rui Ueyama3da3f062016-11-10 20:20:37 +000083// Returns an LLD version string.
84static ArrayRef<uint8_t> getVersion() {
85 // Check LLD_VERSION first for ease of testing.
86 // You can get consitent output by using the environment variable.
87 // This is only for testing.
88 StringRef S = getenv("LLD_VERSION");
89 if (S.empty())
90 S = Saver.save(Twine("Linker: ") + getLLDVersion());
91
92 // +1 to include the terminating '\0'.
93 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000094}
Rui Ueyama3da3f062016-11-10 20:20:37 +000095
96// Creates a .comment section containing LLD version info.
97// With this feature, you can identify LLD-generated binaries easily
98// by "objdump -s -j .comment <file>".
99// The returned object is a mergeable string section.
100template <class ELFT> MergeInputSection<ELFT> *elf::createCommentSection() {
101 typename ELFT::Shdr Hdr = {};
102 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
103 Hdr.sh_type = SHT_PROGBITS;
104 Hdr.sh_entsize = 1;
105 Hdr.sh_addralign = 1;
106
107 auto *Ret = make<MergeInputSection<ELFT>>(/*file=*/nullptr, &Hdr, ".comment");
108 Ret->Data = getVersion();
109 Ret->splitIntoPieces();
110 return Ret;
111}
112
Simon Atanasyance02cf02016-11-09 21:36:56 +0000113// Iterate over sections of the specified type. For each section call
114// provided function. After that "kill" the section by turning off
115// "Live" flag, so that they won't be included in the final output.
116template <class ELFT>
117static void iterateSectionContents(
118 uint32_t Type,
Simon Atanasyan93214b72016-11-09 21:46:42 +0000119 std::function<void(elf::ObjectFile<ELFT> *, ArrayRef<uint8_t>)> F) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000120 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
121 if (Sec && Sec->Live && Sec->Type == Type) {
122 Sec->Live = false;
123 F(Sec->getFile(), Sec->Data);
124 }
125 }
126}
127
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000128// .MIPS.abiflags section.
129template <class ELFT>
130MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection()
131 : InputSection<ELFT>(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ArrayRef<uint8_t>(),
132 ".MIPS.abiflags") {
133 auto Func = [this](ObjectFile<ELFT> *F, ArrayRef<uint8_t> D) {
134 if (D.size() != sizeof(Elf_Mips_ABIFlags)) {
135 error(getFilename(F) + ": invalid size of .MIPS.abiflags section");
136 return;
137 }
138 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(D.data());
139 if (S->version != 0) {
140 error(getFilename(F) + ": unexpected .MIPS.abiflags version " +
141 Twine(S->version));
142 return;
143 }
144 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
145 // select the highest number of ISA/Rev/Ext.
146 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
147 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
148 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
149 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
150 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
151 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
152 Flags.ases |= S->ases;
153 Flags.flags1 |= S->flags1;
154 Flags.flags2 |= S->flags2;
155 Flags.fp_abi =
156 elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, getFilename(F));
157 };
158 iterateSectionContents<ELFT>(SHT_MIPS_ABIFLAGS, Func);
159
160 this->Data = ArrayRef<uint8_t>((const uint8_t *)&Flags, sizeof(Flags));
161 this->Live = true;
162}
163
Simon Atanasyance02cf02016-11-09 21:36:56 +0000164// .MIPS.options section.
165template <class ELFT>
166MipsOptionsSection<ELFT>::MipsOptionsSection()
167 : InputSection<ELFT>(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ArrayRef<uint8_t>(),
168 ".MIPS.options") {
169 Buf.resize(sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo));
170 getOptions()->kind = ODK_REGINFO;
171 getOptions()->size = Buf.size();
172 auto Func = [this](ObjectFile<ELFT> *F, ArrayRef<uint8_t> D) {
173 while (!D.empty()) {
174 if (D.size() < sizeof(Elf_Mips_Options)) {
175 error(getFilename(F) + ": invalid size of .MIPS.options section");
176 break;
177 }
178 auto *O = reinterpret_cast<const Elf_Mips_Options *>(D.data());
179 if (O->kind == ODK_REGINFO) {
180 if (Config->Relocatable && O->getRegInfo().ri_gp_value)
181 error(getFilename(F) + ": unsupported non-zero ri_gp_value");
182 getOptions()->getRegInfo().ri_gprmask |= O->getRegInfo().ri_gprmask;
183 F->MipsGp0 = O->getRegInfo().ri_gp_value;
184 break;
185 }
186 if (!O->size)
187 fatal(getFilename(F) + ": zero option descriptor size");
188 D = D.slice(O->size);
189 }
190 };
191 iterateSectionContents<ELFT>(SHT_MIPS_OPTIONS, Func);
192
193 this->Data = ArrayRef<uint8_t>(Buf);
194 // Section should be alive for N64 ABI only.
195 this->Live = ELFT::Is64Bits;
196}
197
198template <class ELFT> void MipsOptionsSection<ELFT>::finalize() {
199 if (!Config->Relocatable)
200 getOptions()->getRegInfo().ri_gp_value =
Simon Atanasyan725dc142016-11-16 21:01:02 +0000201 In<ELFT>::MipsGot->getVA() + MipsGPOffset;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000202}
203
204// MIPS .reginfo section.
205template <class ELFT>
206MipsReginfoSection<ELFT>::MipsReginfoSection()
207 : InputSection<ELFT>(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ArrayRef<uint8_t>(),
208 ".reginfo") {
209 auto Func = [this](ObjectFile<ELFT> *F, ArrayRef<uint8_t> D) {
210 if (D.size() != sizeof(Elf_Mips_RegInfo)) {
211 error(getFilename(F) + ": invalid size of .reginfo section");
212 return;
213 }
214 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(D.data());
215 if (Config->Relocatable && R->ri_gp_value)
216 error(getFilename(F) + ": unsupported non-zero ri_gp_value");
217 Reginfo.ri_gprmask |= R->ri_gprmask;
218 F->MipsGp0 = R->ri_gp_value;
219 };
220 iterateSectionContents<ELFT>(SHT_MIPS_REGINFO, Func);
221
222 this->Data = ArrayRef<uint8_t>((const uint8_t *)&Reginfo, sizeof(Reginfo));
223 // Section should be alive for O32 and N32 ABIs only.
224 this->Live = !ELFT::Is64Bits;
225}
226
227template <class ELFT> void MipsReginfoSection<ELFT>::finalize() {
228 if (!Config->Relocatable)
Simon Atanasyan725dc142016-11-16 21:01:02 +0000229 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getVA() + MipsGPOffset;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000230}
231
Rui Ueyamae288eef2016-11-02 18:58:44 +0000232static ArrayRef<uint8_t> createInterp() {
233 // StringSaver guarantees that the returned string ends with '\0'.
234 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6294a242016-11-04 17:41:29 +0000235 return {(const uint8_t *)S.data(), S.size() + 1};
Rui Ueyamae288eef2016-11-02 18:58:44 +0000236}
237
Rafael Espindolac0e47fb2016-11-08 14:56:27 +0000238template <class ELFT> InputSection<ELFT> *elf::createInterpSection() {
239 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 1,
240 createInterp(), ".interp");
241 Ret->Live = true;
242 return Ret;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000243}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000244
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000245template <class ELFT>
246BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
247 : InputSection<ELFT>(SHF_ALLOC, SHT_NOTE, 1, ArrayRef<uint8_t>(),
George Rimar364b59e22016-11-06 07:42:55 +0000248 ".note.gnu.build-id"),
249 HashSize(HashSize) {
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000250 this->Live = true;
251
Rafael Espindola0e876cf2016-11-10 15:41:34 +0000252 Buf.resize(HeaderSize + HashSize);
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000253 const endianness E = ELFT::TargetEndianness;
Rafael Espindola1a541122016-11-08 14:47:16 +0000254 write32<E>(Buf.data(), 4); // Name size
255 write32<E>(Buf.data() + 4, HashSize); // Content size
256 write32<E>(Buf.data() + 8, NT_GNU_BUILD_ID); // Type
257 memcpy(Buf.data() + 12, "GNU", 4); // Name string
258 this->Data = ArrayRef<uint8_t>(Buf);
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000259}
260
Rui Ueyama35e00752016-11-10 00:12:28 +0000261// Returns the location of the build-id hash value in the output.
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000262template <class ELFT>
263uint8_t *BuildIdSection<ELFT>::getOutputLoc(uint8_t *Start) const {
Rafael Espindola0e876cf2016-11-10 15:41:34 +0000264 return Start + this->OutSec->Offset + this->OutSecOff + HeaderSize;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000265}
266
Rui Ueyama35e00752016-11-10 00:12:28 +0000267// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000268static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
269 size_t ChunkSize) {
270 std::vector<ArrayRef<uint8_t>> Ret;
271 while (Arr.size() > ChunkSize) {
272 Ret.push_back(Arr.take_front(ChunkSize));
273 Arr = Arr.drop_front(ChunkSize);
274 }
275 if (!Arr.empty())
276 Ret.push_back(Arr);
277 return Ret;
278}
279
Rui Ueyama35e00752016-11-10 00:12:28 +0000280// Computes a hash value of Data using a given hash function.
281// In order to utilize multiple cores, we first split data into 1MB
282// chunks, compute a hash for each chunk, and then compute a hash value
283// of the hash values.
George Rimar364b59e22016-11-06 07:42:55 +0000284template <class ELFT>
285void BuildIdSection<ELFT>::computeHash(
George Rimar828787a2016-11-06 08:39:46 +0000286 llvm::MutableArrayRef<uint8_t> Data,
Rui Ueyama35e00752016-11-10 00:12:28 +0000287 std::function<void(ArrayRef<uint8_t> Arr, uint8_t *Dest)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000288 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
289 std::vector<uint8_t> HashList(Chunks.size() * HashSize);
290
Rui Ueyama35e00752016-11-10 00:12:28 +0000291 auto Fn = [&](ArrayRef<uint8_t> &Chunk) {
292 size_t Idx = &Chunk - Chunks.data();
293 HashFn(Chunk, HashList.data() + Idx * HashSize);
294 };
George Rimar364b59e22016-11-06 07:42:55 +0000295
Rui Ueyama35e00752016-11-10 00:12:28 +0000296 if (Config->Threads)
297 parallel_for_each(Chunks.begin(), Chunks.end(), Fn);
298 else
299 std::for_each(Chunks.begin(), Chunks.end(), Fn);
300
301 HashFn(HashList, this->getOutputLoc(Data.begin()));
George Rimar364b59e22016-11-06 07:42:55 +0000302}
303
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000304template <class ELFT>
305void BuildIdFastHash<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
George Rimar50209712016-11-06 08:26:53 +0000306 this->computeHash(Buf, [](ArrayRef<uint8_t> Arr, uint8_t *Dest) {
Rui Ueyama35e00752016-11-10 00:12:28 +0000307 write64le(Dest, xxHash64(toStringRef(Arr)));
George Rimar364b59e22016-11-06 07:42:55 +0000308 });
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000309}
310
311template <class ELFT>
312void BuildIdMd5<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
Rui Ueyama35e00752016-11-10 00:12:28 +0000313 this->computeHash(Buf, [](ArrayRef<uint8_t> Arr, uint8_t *Dest) {
George Rimar364b59e22016-11-06 07:42:55 +0000314 MD5 Hash;
315 Hash.update(Arr);
316 MD5::MD5Result Res;
317 Hash.final(Res);
Rui Ueyama35e00752016-11-10 00:12:28 +0000318 memcpy(Dest, Res, 16);
George Rimar364b59e22016-11-06 07:42:55 +0000319 });
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000320}
321
322template <class ELFT>
323void BuildIdSha1<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
Rui Ueyama35e00752016-11-10 00:12:28 +0000324 this->computeHash(Buf, [](ArrayRef<uint8_t> Arr, uint8_t *Dest) {
George Rimar364b59e22016-11-06 07:42:55 +0000325 SHA1 Hash;
326 Hash.update(Arr);
Rui Ueyama35e00752016-11-10 00:12:28 +0000327 memcpy(Dest, Hash.final().data(), 20);
George Rimar364b59e22016-11-06 07:42:55 +0000328 });
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000329}
330
331template <class ELFT>
332void BuildIdUuid<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
Rui Ueyama35e00752016-11-10 00:12:28 +0000333 if (getRandomBytes(this->getOutputLoc(Buf.data()), this->HashSize))
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000334 error("entropy source failure");
335}
336
337template <class ELFT>
338BuildIdHexstring<ELFT>::BuildIdHexstring()
339 : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
340
341template <class ELFT>
342void BuildIdHexstring<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
Rui Ueyama35e00752016-11-10 00:12:28 +0000343 memcpy(this->getOutputLoc(Buf.data()), Config->BuildIdVector.data(),
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000344 Config->BuildIdVector.size());
345}
346
Eugene Leviant41ca3272016-11-10 09:48:29 +0000347template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000348GotSection<ELFT>::GotSection()
349 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
Simon Atanasyan725dc142016-11-16 21:01:02 +0000350 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000351
352template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
353 Sym.GotIndex = Entries.size();
354 Entries.push_back(&Sym);
355}
356
Simon Atanasyan725dc142016-11-16 21:01:02 +0000357template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
358 if (Sym.GlobalDynIndex != -1U)
359 return false;
360 Sym.GlobalDynIndex = Entries.size();
361 // Global Dynamic TLS entries take two GOT slots.
362 Entries.push_back(nullptr);
363 Entries.push_back(&Sym);
364 return true;
365}
366
367// Reserves TLS entries for a TLS module ID and a TLS block offset.
368// In total it takes two GOT slots.
369template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
370 if (TlsIndexOff != uint32_t(-1))
371 return false;
372 TlsIndexOff = Entries.size() * sizeof(uintX_t);
373 Entries.push_back(nullptr);
374 Entries.push_back(nullptr);
375 return true;
376}
377
Eugene Leviantad4439e2016-11-11 11:33:32 +0000378template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000379typename GotSection<ELFT>::uintX_t
380GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
381 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
382}
383
384template <class ELFT>
385typename GotSection<ELFT>::uintX_t
386GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
387 return B.GlobalDynIndex * sizeof(uintX_t);
388}
389
390template <class ELFT> void GotSection<ELFT>::finalize() {
391 Size = Entries.size() * sizeof(uintX_t);
392}
393
394template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
395 for (const SymbolBody *B : Entries) {
396 uint8_t *Entry = Buf;
397 Buf += sizeof(uintX_t);
398 if (!B)
399 continue;
400 if (B->isPreemptible())
401 continue; // The dynamic linker will take care of it.
402 uintX_t VA = B->getVA<ELFT>();
403 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
404 }
405}
406
407template <class ELFT>
408MipsGotSection<ELFT>::MipsGotSection()
409 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL,
410 SHT_PROGBITS, Target->GotEntrySize, ".got") {}
411
412template <class ELFT>
413void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, uintX_t Addend,
Eugene Leviantad4439e2016-11-11 11:33:32 +0000414 RelExpr Expr) {
415 // For "true" local symbols which can be referenced from the same module
416 // only compiler creates two instructions for address loading:
417 //
418 // lw $8, 0($gp) # R_MIPS_GOT16
419 // addi $8, $8, 0 # R_MIPS_LO16
420 //
421 // The first instruction loads high 16 bits of the symbol address while
422 // the second adds an offset. That allows to reduce number of required
423 // GOT entries because only one global offset table entry is necessary
424 // for every 64 KBytes of local data. So for local symbols we need to
425 // allocate number of GOT entries to hold all required "page" addresses.
426 //
427 // All global symbols (hidden and regular) considered by compiler uniformly.
428 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
429 // to load address of the symbol. So for each such symbol we need to
430 // allocate dedicated GOT entry to store its address.
431 //
432 // If a symbol is preemptible we need help of dynamic linker to get its
433 // final address. The corresponding GOT entries are allocated in the
434 // "global" part of GOT. Entries for non preemptible global symbol allocated
435 // in the "local" part of GOT.
436 //
437 // See "Global Offset Table" in Chapter 5:
438 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
439 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
440 // At this point we do not know final symbol value so to reduce number
441 // of allocated GOT entries do the following trick. Save all output
442 // sections referenced by GOT relocations. Then later in the `finalize`
443 // method calculate number of "pages" required to cover all saved output
444 // section and allocate appropriate number of GOT entries.
445 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
446 MipsOutSections.insert(OutSec);
447 return;
448 }
449 if (Sym.isTls()) {
450 // GOT entries created for MIPS TLS relocations behave like
451 // almost GOT entries from other ABIs. They go to the end
452 // of the global offset table.
453 Sym.GotIndex = Entries.size();
454 Entries.push_back(&Sym);
455 return;
456 }
457 auto AddEntry = [&](SymbolBody &S, uintX_t A, MipsGotEntries &Items) {
458 if (S.isInGot() && !A)
459 return;
460 size_t NewIndex = Items.size();
461 if (!MipsGotMap.insert({{&S, A}, NewIndex}).second)
462 return;
463 Items.emplace_back(&S, A);
464 if (!A)
465 S.GotIndex = NewIndex;
466 };
467 if (Sym.isPreemptible()) {
468 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
469 AddEntry(Sym, 0, MipsGlobal);
470 Sym.IsInGlobalMipsGot = true;
471 } else if (Expr == R_MIPS_GOT_OFF32) {
472 AddEntry(Sym, Addend, MipsLocal32);
473 Sym.Is32BitMipsGot = true;
474 } else {
475 // Hold local GOT entries accessed via a 16-bit index separately.
476 // That allows to write them in the beginning of the GOT and keep
477 // their indexes as less as possible to escape relocation's overflow.
478 AddEntry(Sym, Addend, MipsLocal);
479 }
480}
481
Simon Atanasyan725dc142016-11-16 21:01:02 +0000482template <class ELFT> bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000483 if (Sym.GlobalDynIndex != -1U)
484 return false;
485 Sym.GlobalDynIndex = Entries.size();
486 // Global Dynamic TLS entries take two GOT slots.
487 Entries.push_back(nullptr);
488 Entries.push_back(&Sym);
489 return true;
490}
491
492// Reserves TLS entries for a TLS module ID and a TLS block offset.
493// In total it takes two GOT slots.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000494template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000495 if (TlsIndexOff != uint32_t(-1))
496 return false;
497 TlsIndexOff = Entries.size() * sizeof(uintX_t);
498 Entries.push_back(nullptr);
499 Entries.push_back(nullptr);
500 return true;
501}
502
503template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000504typename MipsGotSection<ELFT>::uintX_t
505MipsGotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000506 // Initialize the entry by the %hi(EntryValue) expression
507 // but without right-shifting.
508 EntryValue = (EntryValue + 0x8000) & ~0xffff;
509 // Take into account MIPS GOT header.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000510 // See comment in the MipsGotSection::writeTo.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000511 size_t NewIndex = MipsLocalGotPos.size() + 2;
512 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
513 assert(!P.second || MipsLocalGotPos.size() <= MipsPageEntries);
514 return (uintX_t)P.first->second * sizeof(uintX_t) - MipsGPOffset;
515}
516
517template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000518typename MipsGotSection<ELFT>::uintX_t
519MipsGotSection<ELFT>::getMipsGotOffset(const SymbolBody &B, uintX_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000520 // Calculate offset of the GOT entries block: TLS, global, local.
521 uintX_t GotBlockOff;
522 if (B.isTls())
523 GotBlockOff = getMipsTlsOffset();
524 else if (B.IsInGlobalMipsGot)
525 GotBlockOff = getMipsLocalEntriesNum() * sizeof(uintX_t);
526 else if (B.Is32BitMipsGot)
527 GotBlockOff = (MipsPageEntries + MipsLocal.size()) * sizeof(uintX_t);
528 else
529 GotBlockOff = MipsPageEntries * sizeof(uintX_t);
530 // Calculate index of the GOT entry in the block.
531 uintX_t GotIndex;
532 if (B.isInGot())
533 GotIndex = B.GotIndex;
534 else {
535 auto It = MipsGotMap.find({&B, Addend});
536 assert(It != MipsGotMap.end());
537 GotIndex = It->second;
538 }
539 return GotBlockOff + GotIndex * sizeof(uintX_t) - MipsGPOffset;
540}
541
542template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000543typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getMipsTlsOffset() const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000544 return (getMipsLocalEntriesNum() + MipsGlobal.size()) * sizeof(uintX_t);
545}
546
547template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000548typename MipsGotSection<ELFT>::uintX_t
549MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000550 return B.GlobalDynIndex * sizeof(uintX_t);
551}
552
553template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000554const SymbolBody *MipsGotSection<ELFT>::getMipsFirstGlobalEntry() const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000555 return MipsGlobal.empty() ? nullptr : MipsGlobal.front().first;
556}
557
558template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000559unsigned MipsGotSection<ELFT>::getMipsLocalEntriesNum() const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000560 return MipsPageEntries + MipsLocal.size() + MipsLocal32.size();
561}
562
Simon Atanasyan725dc142016-11-16 21:01:02 +0000563template <class ELFT> void MipsGotSection<ELFT>::finalize() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000564 size_t EntriesNum = Entries.size();
Simon Atanasyan725dc142016-11-16 21:01:02 +0000565 // Take into account MIPS GOT header.
566 // See comment in the MipsGotSection::writeTo.
567 MipsPageEntries += 2;
568 for (const OutputSectionBase *OutSec : MipsOutSections) {
569 // Calculate an upper bound of MIPS GOT entries required to store page
570 // addresses of local symbols. We assume the worst case - each 64kb
571 // page of the output section has at least one GOT relocation against it.
572 // Add 0x8000 to the section's size because the page address stored
573 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
574 MipsPageEntries += (OutSec->Size + 0x8000 + 0xfffe) / 0xffff;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000575 }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000576 EntriesNum += getMipsLocalEntriesNum() + MipsGlobal.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000577 Size = EntriesNum * sizeof(uintX_t);
578}
579
580template <class ELFT>
581static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
582 typedef typename ELFT::uint uintX_t;
583 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
584}
585
Simon Atanasyan725dc142016-11-16 21:01:02 +0000586template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000587 // Set the MSB of the second GOT slot. This is not required by any
588 // MIPS ABI documentation, though.
589 //
590 // There is a comment in glibc saying that "The MSB of got[1] of a
591 // gnu object is set to identify gnu objects," and in GNU gold it
592 // says "the second entry will be used by some runtime loaders".
593 // But how this field is being used is unclear.
594 //
595 // We are not really willing to mimic other linkers behaviors
596 // without understanding why they do that, but because all files
597 // generated by GNU tools have this special GOT value, and because
598 // we've been doing this for years, it is probably a safe bet to
599 // keep doing this for now. We really need to revisit this to see
600 // if we had to do this.
601 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
602 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
603 // Write 'page address' entries to the local part of the GOT.
604 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
605 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
606 writeUint<ELFT>(Entry, L.first);
607 }
608 Buf += MipsPageEntries * sizeof(uintX_t);
609 auto AddEntry = [&](const MipsGotEntry &SA) {
610 uint8_t *Entry = Buf;
611 Buf += sizeof(uintX_t);
612 const SymbolBody *Body = SA.first;
613 uintX_t VA = Body->template getVA<ELFT>(SA.second);
614 writeUint<ELFT>(Entry, VA);
615 };
616 std::for_each(std::begin(MipsLocal), std::end(MipsLocal), AddEntry);
617 std::for_each(std::begin(MipsLocal32), std::end(MipsLocal32), AddEntry);
618 std::for_each(std::begin(MipsGlobal), std::end(MipsGlobal), AddEntry);
619 // Initialize TLS-related GOT entries. If the entry has a corresponding
620 // dynamic relocations, leave it initialized by zero. Write down adjusted
621 // TLS symbol's values otherwise. To calculate the adjustments use offsets
622 // for thread-local storage.
623 // https://www.linux-mips.org/wiki/NPTL
624 if (TlsIndexOff != -1U && !Config->Pic)
625 writeUint<ELFT>(Buf + TlsIndexOff, 1);
626 for (const SymbolBody *B : Entries) {
627 if (!B || B->isPreemptible())
628 continue;
629 uintX_t VA = B->getVA<ELFT>();
630 if (B->GotIndex != -1U) {
631 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
632 writeUint<ELFT>(Entry, VA - 0x7000);
633 }
634 if (B->GlobalDynIndex != -1U) {
635 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
636 writeUint<ELFT>(Entry, 1);
637 Entry += sizeof(uintX_t);
638 writeUint<ELFT>(Entry, VA - 0x8000);
639 }
640 }
641}
642
Eugene Leviantad4439e2016-11-11 11:33:32 +0000643template <class ELFT>
Eugene Leviant41ca3272016-11-10 09:48:29 +0000644GotPltSection<ELFT>::GotPltSection()
645 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
George Rimard8b27762016-11-14 10:14:18 +0000646 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000647
648template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
649 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
650 Entries.push_back(&Sym);
651}
652
653template <class ELFT> bool GotPltSection<ELFT>::empty() const {
654 return Entries.empty();
655}
656
657template <class ELFT> size_t GotPltSection<ELFT>::getSize() const {
658 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
659 Target->GotPltEntrySize;
660}
661
662template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
663 Target->writeGotPltHeader(Buf);
664 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
665 for (const SymbolBody *B : Entries) {
666 Target->writeGotPlt(Buf, *B);
667 Buf += sizeof(uintX_t);
668 }
669}
670
Eugene Leviant22eb0262016-11-14 09:16:00 +0000671template <class ELFT>
672StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
673 : SyntheticSection<ELFT>(Dynamic ? (uintX_t)SHF_ALLOC : 0, SHT_STRTAB, 1,
674 Name),
675 Dynamic(Dynamic) {}
676
677// Adds a string to the string table. If HashIt is true we hash and check for
678// duplicates. It is optional because the name of global symbols are already
679// uniqued and hashing them again has a big cost for a small value: uniquing
680// them with some other string that happens to be the same.
681template <class ELFT>
682unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
683 if (HashIt) {
684 auto R = StringMap.insert(std::make_pair(S, this->Size));
685 if (!R.second)
686 return R.first->second;
687 }
688 unsigned Ret = this->Size;
689 this->Size = this->Size + S.size() + 1;
690 Strings.push_back(S);
691 return Ret;
692}
693
694template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
695 // ELF string tables start with NUL byte, so advance the pointer by one.
696 ++Buf;
697 for (StringRef S : Strings) {
698 memcpy(Buf, S.data(), S.size());
699 Buf += S.size() + 1;
700 }
701}
702
Eugene Leviant6380ce22016-11-15 12:26:55 +0000703static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
704
705template <class ELFT>
706DynamicSection<ELFT>::DynamicSection()
707 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC,
708 sizeof(uintX_t), ".dynamic") {
709 this->Entsize = ELFT::Is64Bits ? 16 : 8;
710 // .dynamic section is not writable on MIPS.
711 // See "Special Section" in Chapter 4 in the following document:
712 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
713 if (Config->EMachine == EM_MIPS)
714 this->Flags = SHF_ALLOC;
715
716 addEntries();
717}
718
719// There are some dynamic entries that don't depend on other sections.
720// Such entries can be set early.
721template <class ELFT> void DynamicSection<ELFT>::addEntries() {
722 // Add strings to .dynstr early so that .dynstr's size will be
723 // fixed early.
724 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +0000725 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000726 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +0000727 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000728 In<ELFT>::DynStrTab->addString(Config->RPath)});
729 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
730 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +0000731 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000732 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +0000733 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000734
735 // Set DT_FLAGS and DT_FLAGS_1.
736 uint32_t DtFlags = 0;
737 uint32_t DtFlags1 = 0;
738 if (Config->Bsymbolic)
739 DtFlags |= DF_SYMBOLIC;
740 if (Config->ZNodelete)
741 DtFlags1 |= DF_1_NODELETE;
742 if (Config->ZNow) {
743 DtFlags |= DF_BIND_NOW;
744 DtFlags1 |= DF_1_NOW;
745 }
746 if (Config->ZOrigin) {
747 DtFlags |= DF_ORIGIN;
748 DtFlags1 |= DF_1_ORIGIN;
749 }
750
751 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +0000752 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000753 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +0000754 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000755
756 if (!Config->Entry.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +0000757 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000758}
759
760// Add remaining entries to complete .dynamic contents.
761template <class ELFT> void DynamicSection<ELFT>::finalize() {
762 if (this->Size)
763 return; // Already finalized.
764
765 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
766
Eugene Levianta96d9022016-11-16 10:02:27 +0000767 if (In<ELFT>::RelaDyn->hasRelocs()) {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000768 bool IsRela = Config->Rela;
Rui Ueyama729ac792016-11-17 04:10:09 +0000769 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
770 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getSize()});
771 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000772 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
773
774 // MIPS dynamic loader does not support RELCOUNT tag.
775 // The problem is in the tight relation between dynamic
776 // relocations and GOT. So do not emit this tag on MIPS.
777 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +0000778 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +0000779 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +0000780 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000781 }
782 }
Eugene Levianta96d9022016-11-16 10:02:27 +0000783 if (In<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000784 add({DT_JMPREL, In<ELFT>::RelaPlt});
785 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getSize()});
786 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000787 In<ELFT>::GotPlt});
Rui Ueyama729ac792016-11-17 04:10:09 +0000788 add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000789 }
790
Eugene Leviant9230db92016-11-17 09:16:34 +0000791 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +0000792 add({DT_SYMENT, sizeof(Elf_Sym)});
793 add({DT_STRTAB, In<ELFT>::DynStrTab});
794 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000795 if (Out<ELFT>::GnuHashTab)
Rui Ueyama729ac792016-11-17 04:10:09 +0000796 add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000797 if (Out<ELFT>::HashTab)
Rui Ueyama729ac792016-11-17 04:10:09 +0000798 add({DT_HASH, Out<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000799
800 if (Out<ELFT>::PreinitArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000801 add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
802 add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000803 }
804 if (Out<ELFT>::InitArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000805 add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
806 add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000807 }
808 if (Out<ELFT>::FiniArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000809 add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
810 add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000811 }
812
813 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +0000814 add({DT_INIT, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000815 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +0000816 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000817
818 bool HasVerNeed = Out<ELFT>::VerNeed->getNeedNum() != 0;
819 if (HasVerNeed || Out<ELFT>::VerDef)
Rui Ueyama729ac792016-11-17 04:10:09 +0000820 add({DT_VERSYM, Out<ELFT>::VerSym});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000821 if (Out<ELFT>::VerDef) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000822 add({DT_VERDEF, Out<ELFT>::VerDef});
823 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000824 }
825 if (HasVerNeed) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000826 add({DT_VERNEED, Out<ELFT>::VerNeed});
827 add({DT_VERNEEDNUM, Out<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000828 }
829
830 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000831 add({DT_MIPS_RLD_VERSION, 1});
832 add({DT_MIPS_FLAGS, RHF_NOTPOT});
833 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +0000834 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +0000835 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getMipsLocalEntriesNum()});
Simon Atanasyan725dc142016-11-16 21:01:02 +0000836 if (const SymbolBody *B = In<ELFT>::MipsGot->getMipsFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +0000837 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000838 else
Eugene Leviant9230db92016-11-17 09:16:34 +0000839 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +0000840 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000841 if (Out<ELFT>::MipsRldMap)
Rui Ueyama729ac792016-11-17 04:10:09 +0000842 add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000843 }
844
845 this->OutSec->Entsize = this->Entsize;
846 this->OutSec->Link = this->Link;
847
848 // +1 for DT_NULL
849 this->Size = (Entries.size() + 1) * this->Entsize;
850}
851
852template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
853 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
854
855 for (const Entry &E : Entries) {
856 P->d_tag = E.Tag;
857 switch (E.Kind) {
858 case Entry::SecAddr:
859 P->d_un.d_ptr = E.OutSec->Addr;
860 break;
861 case Entry::InSecAddr:
862 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
863 break;
864 case Entry::SecSize:
865 P->d_un.d_val = E.OutSec->Size;
866 break;
867 case Entry::SymAddr:
868 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
869 break;
870 case Entry::PlainInt:
871 P->d_un.d_val = E.Val;
872 break;
873 }
874 ++P;
875 }
876}
877
Eugene Levianta96d9022016-11-16 10:02:27 +0000878template <class ELFT>
879typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
880 if (OutputSec)
881 return OutputSec->Addr + OffsetInSec;
882 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
883}
884
885template <class ELFT>
886typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
887 if (UseSymVA)
888 return Sym->getVA<ELFT>(Addend);
889 return Addend;
890}
891
892template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
893 if (Sym && !UseSymVA)
894 return Sym->DynsymIndex;
895 return 0;
896}
897
898template <class ELFT>
899RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
900 : SyntheticSection<ELFT>(SHF_ALLOC, Config->Rela ? SHT_RELA : SHT_REL,
901 sizeof(uintX_t), Name),
902 Sort(Sort) {
903 this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
904}
905
906template <class ELFT>
907void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
908 if (Reloc.Type == Target->RelativeRel)
909 ++NumRelativeRelocs;
910 Relocs.push_back(Reloc);
911}
912
913template <class ELFT, class RelTy>
914static bool compRelocations(const RelTy &A, const RelTy &B) {
915 bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
916 bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
917 if (AIsRel != BIsRel)
918 return AIsRel;
919
920 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
921}
922
923template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
924 uint8_t *BufBegin = Buf;
925 for (const DynamicReloc<ELFT> &Rel : Relocs) {
926 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
927 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
928
929 if (Config->Rela)
930 P->r_addend = Rel.getAddend();
931 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +0000932 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +0000933 // Dynamic relocation against MIPS GOT section make deal TLS entries
934 // allocated in the end of the GOT. We need to adjust the offset to take
935 // in account 'local' and 'global' GOT entries.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000936 P->r_offset += In<ELFT>::MipsGot->getMipsTlsOffset();
Eugene Levianta96d9022016-11-16 10:02:27 +0000937 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
938 }
939
940 if (Sort) {
941 if (Config->Rela)
942 std::stable_sort((Elf_Rela *)BufBegin,
943 (Elf_Rela *)BufBegin + Relocs.size(),
944 compRelocations<ELFT, Elf_Rela>);
945 else
946 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
947 compRelocations<ELFT, Elf_Rel>);
948 }
949}
950
951template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
952 return this->Entsize * Relocs.size();
953}
954
955template <class ELFT> void RelocationSection<ELFT>::finalize() {
Eugene Leviant9230db92016-11-17 09:16:34 +0000956 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
957 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +0000958
959 // Set required output section properties.
960 this->OutSec->Link = this->Link;
961 this->OutSec->Entsize = this->Entsize;
962}
963
Eugene Leviant9230db92016-11-17 09:16:34 +0000964template <class ELFT>
965SymbolTableSection<ELFT>::SymbolTableSection(
966 StringTableSection<ELFT> &StrTabSec)
967 : SyntheticSection<ELFT>(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
968 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
969 sizeof(uintX_t),
970 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
971 StrTabSec(StrTabSec) {
972 this->Entsize = sizeof(Elf_Sym);
973}
974
975// Orders symbols according to their positions in the GOT,
976// in compliance with MIPS ABI rules.
977// See "Global Offset Table" in Chapter 5 in the following document
978// for detailed description:
979// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
980static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
981 // Sort entries related to non-local preemptible symbols by GOT indexes.
982 // All other entries go to the first part of GOT in arbitrary order.
983 bool LIsInLocalGot = !L->IsInGlobalMipsGot;
984 bool RIsInLocalGot = !R->IsInGlobalMipsGot;
985 if (LIsInLocalGot || RIsInLocalGot)
986 return !RIsInLocalGot;
987 return L->GotIndex < R->GotIndex;
988}
989
990static uint8_t getSymbolBinding(SymbolBody *Body) {
991 Symbol *S = Body->symbol();
992 if (Config->Relocatable)
993 return S->Binding;
994 uint8_t Visibility = S->Visibility;
995 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
996 return STB_LOCAL;
997 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
998 return STB_GLOBAL;
999 return S->Binding;
1000}
1001
1002template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1003 this->OutSec->Link = this->Link = StrTabSec.OutSec->SectionIndex;
1004 this->OutSec->Info = this->Info = NumLocals + 1;
1005 this->OutSec->Entsize = this->Entsize;
1006
1007 if (Config->Relocatable) {
1008 size_t I = NumLocals;
1009 for (const SymbolTableEntry &S : Symbols)
1010 S.Symbol->DynsymIndex = ++I;
1011 return;
1012 }
1013
1014 if (!StrTabSec.isDynamic()) {
1015 std::stable_sort(Symbols.begin(), Symbols.end(),
1016 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1017 return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1018 getSymbolBinding(R.Symbol) != STB_LOCAL;
1019 });
1020 return;
1021 }
1022 if (Out<ELFT>::GnuHashTab)
1023 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1024 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
1025 else if (Config->EMachine == EM_MIPS)
1026 std::stable_sort(Symbols.begin(), Symbols.end(),
1027 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1028 return sortMipsSymbols(L.Symbol, R.Symbol);
1029 });
1030 size_t I = 0;
1031 for (const SymbolTableEntry &S : Symbols)
1032 S.Symbol->DynsymIndex = ++I;
1033}
1034
1035template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1036 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1037}
1038
1039template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1040 Buf += sizeof(Elf_Sym);
1041
1042 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1043 // .dynsym only contains global symbols.
1044 if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1045 writeLocalSymbols(Buf);
1046
1047 writeGlobalSymbols(Buf);
1048}
1049
1050template <class ELFT>
1051void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1052 // Iterate over all input object files to copy their local symbols
1053 // to the output symbol table pointed by Buf.
1054 for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
1055 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1056 File->KeptLocalSyms) {
1057 const DefinedRegular<ELFT> &Body = *P.first;
1058 InputSectionBase<ELFT> *Section = Body.Section;
1059 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1060
1061 if (!Section) {
1062 ESym->st_shndx = SHN_ABS;
1063 ESym->st_value = Body.Value;
1064 } else {
1065 const OutputSectionBase *OutSec = Section->OutSec;
1066 ESym->st_shndx = OutSec->SectionIndex;
1067 ESym->st_value = OutSec->Addr + Section->getOffset(Body);
1068 }
1069 ESym->st_name = P.second;
1070 ESym->st_size = Body.template getSize<ELFT>();
1071 ESym->setBindingAndType(STB_LOCAL, Body.Type);
1072 Buf += sizeof(*ESym);
1073 }
1074 }
1075}
1076
1077template <class ELFT>
1078void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1079 // Write the internal symbol table contents to the output symbol table
1080 // pointed by Buf.
1081 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1082 for (const SymbolTableEntry &S : Symbols) {
1083 SymbolBody *Body = S.Symbol;
1084 size_t StrOff = S.StrTabOffset;
1085
1086 uint8_t Type = Body->Type;
1087 uintX_t Size = Body->getSize<ELFT>();
1088
1089 ESym->setBindingAndType(getSymbolBinding(Body), Type);
1090 ESym->st_size = Size;
1091 ESym->st_name = StrOff;
1092 ESym->setVisibility(Body->symbol()->Visibility);
1093 ESym->st_value = Body->getVA<ELFT>();
1094
1095 if (const OutputSectionBase *OutSec = getOutputSection(Body))
1096 ESym->st_shndx = OutSec->SectionIndex;
1097 else if (isa<DefinedRegular<ELFT>>(Body))
1098 ESym->st_shndx = SHN_ABS;
1099
1100 if (Config->EMachine == EM_MIPS) {
1101 // On MIPS we need to mark symbol which has a PLT entry and requires
1102 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1103 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1104 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1105 if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1106 ESym->st_other |= STO_MIPS_PLT;
1107 if (Config->Relocatable) {
1108 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1109 if (D && D->isMipsPIC())
1110 ESym->st_other |= STO_MIPS_PIC;
1111 }
1112 }
1113 ++ESym;
1114 }
1115}
1116
1117template <class ELFT>
1118const OutputSectionBase *
1119SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1120 switch (Sym->kind()) {
1121 case SymbolBody::DefinedSyntheticKind:
1122 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1123 case SymbolBody::DefinedRegularKind: {
1124 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1125 if (D.Section)
1126 return D.Section->OutSec;
1127 break;
1128 }
1129 case SymbolBody::DefinedCommonKind:
1130 return In<ELFT>::Common->OutSec;
1131 case SymbolBody::SharedKind:
1132 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1133 return Out<ELFT>::Bss;
1134 break;
1135 case SymbolBody::UndefinedKind:
1136 case SymbolBody::LazyArchiveKind:
1137 case SymbolBody::LazyObjectKind:
1138 break;
1139 }
1140 return nullptr;
1141}
1142
Rafael Espindola682a5bc2016-11-08 14:42:34 +00001143template InputSection<ELF32LE> *elf::createCommonSection();
1144template InputSection<ELF32BE> *elf::createCommonSection();
1145template InputSection<ELF64LE> *elf::createCommonSection();
1146template InputSection<ELF64BE> *elf::createCommonSection();
Rui Ueyamae8a61022016-11-05 23:05:47 +00001147
Rafael Espindolac0e47fb2016-11-08 14:56:27 +00001148template InputSection<ELF32LE> *elf::createInterpSection();
1149template InputSection<ELF32BE> *elf::createInterpSection();
1150template InputSection<ELF64LE> *elf::createInterpSection();
1151template InputSection<ELF64BE> *elf::createInterpSection();
Rui Ueyamae288eef2016-11-02 18:58:44 +00001152
Rui Ueyama3da3f062016-11-10 20:20:37 +00001153template MergeInputSection<ELF32LE> *elf::createCommentSection();
1154template MergeInputSection<ELF32BE> *elf::createCommentSection();
1155template MergeInputSection<ELF64LE> *elf::createCommentSection();
1156template MergeInputSection<ELF64BE> *elf::createCommentSection();
1157
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00001158template class elf::MipsAbiFlagsSection<ELF32LE>;
1159template class elf::MipsAbiFlagsSection<ELF32BE>;
1160template class elf::MipsAbiFlagsSection<ELF64LE>;
1161template class elf::MipsAbiFlagsSection<ELF64BE>;
1162
Simon Atanasyance02cf02016-11-09 21:36:56 +00001163template class elf::MipsOptionsSection<ELF32LE>;
1164template class elf::MipsOptionsSection<ELF32BE>;
1165template class elf::MipsOptionsSection<ELF64LE>;
1166template class elf::MipsOptionsSection<ELF64BE>;
1167
1168template class elf::MipsReginfoSection<ELF32LE>;
1169template class elf::MipsReginfoSection<ELF32BE>;
1170template class elf::MipsReginfoSection<ELF64LE>;
1171template class elf::MipsReginfoSection<ELF64BE>;
1172
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00001173template class elf::BuildIdSection<ELF32LE>;
1174template class elf::BuildIdSection<ELF32BE>;
1175template class elf::BuildIdSection<ELF64LE>;
1176template class elf::BuildIdSection<ELF64BE>;
1177
1178template class elf::BuildIdFastHash<ELF32LE>;
1179template class elf::BuildIdFastHash<ELF32BE>;
1180template class elf::BuildIdFastHash<ELF64LE>;
1181template class elf::BuildIdFastHash<ELF64BE>;
1182
1183template class elf::BuildIdMd5<ELF32LE>;
1184template class elf::BuildIdMd5<ELF32BE>;
1185template class elf::BuildIdMd5<ELF64LE>;
1186template class elf::BuildIdMd5<ELF64BE>;
1187
1188template class elf::BuildIdSha1<ELF32LE>;
1189template class elf::BuildIdSha1<ELF32BE>;
1190template class elf::BuildIdSha1<ELF64LE>;
1191template class elf::BuildIdSha1<ELF64BE>;
1192
1193template class elf::BuildIdUuid<ELF32LE>;
1194template class elf::BuildIdUuid<ELF32BE>;
1195template class elf::BuildIdUuid<ELF64LE>;
1196template class elf::BuildIdUuid<ELF64BE>;
1197
1198template class elf::BuildIdHexstring<ELF32LE>;
1199template class elf::BuildIdHexstring<ELF32BE>;
1200template class elf::BuildIdHexstring<ELF64LE>;
1201template class elf::BuildIdHexstring<ELF64BE>;
Eugene Leviant41ca3272016-11-10 09:48:29 +00001202
Eugene Leviantad4439e2016-11-11 11:33:32 +00001203template class elf::GotSection<ELF32LE>;
1204template class elf::GotSection<ELF32BE>;
1205template class elf::GotSection<ELF64LE>;
1206template class elf::GotSection<ELF64BE>;
1207
Simon Atanasyan725dc142016-11-16 21:01:02 +00001208template class elf::MipsGotSection<ELF32LE>;
1209template class elf::MipsGotSection<ELF32BE>;
1210template class elf::MipsGotSection<ELF64LE>;
1211template class elf::MipsGotSection<ELF64BE>;
1212
Eugene Leviant41ca3272016-11-10 09:48:29 +00001213template class elf::GotPltSection<ELF32LE>;
1214template class elf::GotPltSection<ELF32BE>;
1215template class elf::GotPltSection<ELF64LE>;
1216template class elf::GotPltSection<ELF64BE>;
Eugene Leviant22eb0262016-11-14 09:16:00 +00001217
1218template class elf::StringTableSection<ELF32LE>;
1219template class elf::StringTableSection<ELF32BE>;
1220template class elf::StringTableSection<ELF64LE>;
1221template class elf::StringTableSection<ELF64BE>;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001222
1223template class elf::DynamicSection<ELF32LE>;
1224template class elf::DynamicSection<ELF32BE>;
1225template class elf::DynamicSection<ELF64LE>;
1226template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00001227
1228template class elf::RelocationSection<ELF32LE>;
1229template class elf::RelocationSection<ELF32BE>;
1230template class elf::RelocationSection<ELF64LE>;
1231template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00001232
1233template class elf::SymbolTableSection<ELF32LE>;
1234template class elf::SymbolTableSection<ELF32BE>;
1235template class elf::SymbolTableSection<ELF64LE>;
1236template class elf::SymbolTableSection<ELF64BE>;