blob: d69100a22d4804261eb653f96c2c4eeb8a6e9401 [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"
Eugene Leviant17b7a572016-11-22 17:49:14 +000021#include "LinkerScript.h"
Rui Ueyamae288eef2016-11-02 18:58:44 +000022#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000023#include "OutputSections.h"
24#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000025#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000026#include "Target.h"
Rui Ueyama244a4352016-12-03 21:24:51 +000027#include "Threads.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000028#include "Writer.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000029
Rui Ueyama3da3f062016-11-10 20:20:37 +000030#include "lld/Config/Version.h"
Eugene Leviant952eb4d2016-11-21 15:52:10 +000031#include "llvm/Support/Dwarf.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000032#include "llvm/Support/Endian.h"
33#include "llvm/Support/MD5.h"
34#include "llvm/Support/RandomNumberGenerator.h"
35#include "llvm/Support/SHA1.h"
36#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000037#include <cstdlib>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000038
39using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000040using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000041using namespace llvm::ELF;
42using namespace llvm::object;
43using namespace llvm::support;
44using namespace llvm::support::endian;
45
46using namespace lld;
47using namespace lld::elf;
48
Rui Ueyamae8a61022016-11-05 23:05:47 +000049template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
50 std::vector<DefinedCommon *> V;
51 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
52 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
53 V.push_back(B);
54 return V;
55}
56
57// Find all common symbols and allocate space for them.
Rafael Espindola682a5bc2016-11-08 14:42:34 +000058template <class ELFT> InputSection<ELFT> *elf::createCommonSection() {
59 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
60 ArrayRef<uint8_t>(), "COMMON");
61 Ret->Live = true;
Rui Ueyamae8a61022016-11-05 23:05:47 +000062
63 // Sort the common symbols by alignment as an heuristic to pack them better.
64 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
65 std::stable_sort(Syms.begin(), Syms.end(),
66 [](const DefinedCommon *A, const DefinedCommon *B) {
67 return A->Alignment > B->Alignment;
68 });
69
70 // Assign offsets to symbols.
71 size_t Size = 0;
72 size_t Alignment = 1;
73 for (DefinedCommon *Sym : Syms) {
Rui Ueyama1c786822016-11-05 23:14:54 +000074 Alignment = std::max<size_t>(Alignment, Sym->Alignment);
Rui Ueyamae8a61022016-11-05 23:05:47 +000075 Size = alignTo(Size, Sym->Alignment);
76
77 // Compute symbol offset relative to beginning of input section.
78 Sym->Offset = Size;
79 Size += Sym->Size;
80 }
Rafael Espindola682a5bc2016-11-08 14:42:34 +000081 Ret->Alignment = Alignment;
82 Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
83 return Ret;
Rui Ueyamae8a61022016-11-05 23:05:47 +000084}
85
Rui Ueyama3da3f062016-11-10 20:20:37 +000086// Returns an LLD version string.
87static ArrayRef<uint8_t> getVersion() {
88 // Check LLD_VERSION first for ease of testing.
89 // You can get consitent output by using the environment variable.
90 // This is only for testing.
91 StringRef S = getenv("LLD_VERSION");
92 if (S.empty())
93 S = Saver.save(Twine("Linker: ") + getLLDVersion());
94
95 // +1 to include the terminating '\0'.
96 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000097}
Rui Ueyama3da3f062016-11-10 20:20:37 +000098
99// Creates a .comment section containing LLD version info.
100// With this feature, you can identify LLD-generated binaries easily
101// by "objdump -s -j .comment <file>".
102// The returned object is a mergeable string section.
103template <class ELFT> MergeInputSection<ELFT> *elf::createCommentSection() {
104 typename ELFT::Shdr Hdr = {};
105 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
106 Hdr.sh_type = SHT_PROGBITS;
107 Hdr.sh_entsize = 1;
108 Hdr.sh_addralign = 1;
109
110 auto *Ret = make<MergeInputSection<ELFT>>(/*file=*/nullptr, &Hdr, ".comment");
111 Ret->Data = getVersion();
112 Ret->splitIntoPieces();
113 return Ret;
114}
115
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000116// .MIPS.abiflags section.
117template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000118MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
119 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
120 Flags(Flags) {}
121
122template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
123 memcpy(Buf, &Flags, sizeof(Flags));
124}
125
126template <class ELFT>
127MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
128 Elf_Mips_ABIFlags Flags = {};
129 bool Create = false;
130
131 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
132 if (!Sec->Live || Sec->Type != SHT_MIPS_ABIFLAGS)
133 continue;
134 Sec->Live = false;
135 Create = true;
136
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000137 std::string Filename = toString(Sec->getFile());
Rui Ueyama12f2da82016-11-22 03:57:06 +0000138 if (Sec->Data.size() != sizeof(Elf_Mips_ABIFlags)) {
139 error(Filename + ": invalid size of .MIPS.abiflags section");
140 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000141 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000142 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000143 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000144 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000145 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000146 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000147 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000148
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000149 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
150 // select the highest number of ISA/Rev/Ext.
151 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
152 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
153 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
154 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
155 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
156 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
157 Flags.ases |= S->ases;
158 Flags.flags1 |= S->flags1;
159 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000160 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000161 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000162
Rui Ueyama12f2da82016-11-22 03:57:06 +0000163 if (Create)
164 return make<MipsAbiFlagsSection<ELFT>>(Flags);
165 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000166}
167
Simon Atanasyance02cf02016-11-09 21:36:56 +0000168// .MIPS.options section.
169template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000170MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
171 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
172 Reginfo(Reginfo) {}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000173
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000174template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
175 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
176 Options->kind = ODK_REGINFO;
177 Options->size = getSize();
178
179 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000180 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000181 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000182}
183
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000184template <class ELFT>
185MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
186 // N64 ABI only.
187 if (!ELFT::Is64Bits)
188 return nullptr;
189
190 Elf_Mips_RegInfo Reginfo = {};
191 bool Create = false;
192
193 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
194 if (!Sec->Live || Sec->Type != SHT_MIPS_OPTIONS)
195 continue;
196 Sec->Live = false;
197 Create = true;
198
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000199 std::string Filename = toString(Sec->getFile());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000200 ArrayRef<uint8_t> D = Sec->Data;
201
202 while (!D.empty()) {
203 if (D.size() < sizeof(Elf_Mips_Options)) {
204 error(Filename + ": invalid size of .MIPS.options section");
205 break;
206 }
207
208 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
209 if (Opt->kind == ODK_REGINFO) {
210 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
211 error(Filename + ": unsupported non-zero ri_gp_value");
212 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
213 Sec->getFile()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
214 break;
215 }
216
217 if (!Opt->size)
218 fatal(Filename + ": zero option descriptor size");
219 D = D.slice(Opt->size);
220 }
221 };
222
223 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000224 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000225 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000226}
227
228// MIPS .reginfo section.
229template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000230MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
231 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
232 Reginfo(Reginfo) {}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000233
Rui Ueyamab71cae92016-11-22 03:57:08 +0000234template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000235 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000236 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000237 memcpy(Buf, &Reginfo, sizeof(Reginfo));
238}
239
240template <class ELFT>
241MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
242 // Section should be alive for O32 and N32 ABIs only.
243 if (ELFT::Is64Bits)
244 return nullptr;
245
246 Elf_Mips_RegInfo Reginfo = {};
247 bool Create = false;
248
249 for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) {
250 if (!Sec->Live || Sec->Type != SHT_MIPS_REGINFO)
251 continue;
252 Sec->Live = false;
253 Create = true;
254
255 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000256 error(toString(Sec->getFile()) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000257 return nullptr;
258 }
259 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
260 if (Config->Relocatable && R->ri_gp_value)
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000261 error(toString(Sec->getFile()) + ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000262
263 Reginfo.ri_gprmask |= R->ri_gprmask;
264 Sec->getFile()->MipsGp0 = R->ri_gp_value;
265 };
266
267 if (Create)
268 return make<MipsReginfoSection<ELFT>>(Reginfo);
269 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000270}
271
Rafael Espindolac0e47fb2016-11-08 14:56:27 +0000272template <class ELFT> InputSection<ELFT> *elf::createInterpSection() {
273 auto *Ret = make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 1,
Rui Ueyama81a4b262016-11-22 04:33:01 +0000274 ArrayRef<uint8_t>(), ".interp");
Rafael Espindolac0e47fb2016-11-08 14:56:27 +0000275 Ret->Live = true;
Rui Ueyama81a4b262016-11-22 04:33:01 +0000276
277 // StringSaver guarantees that the returned string ends with '\0'.
278 StringRef S = Saver.save(Config->DynamicLinker);
279 Ret->Data = {(const uint8_t *)S.data(), S.size() + 1};
Rafael Espindolac0e47fb2016-11-08 14:56:27 +0000280 return Ret;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000281}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000282
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000283static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000284 switch (Config->BuildId) {
285 case BuildIdKind::Fast:
286 return 8;
287 case BuildIdKind::Md5:
288 case BuildIdKind::Uuid:
289 return 16;
290 case BuildIdKind::Sha1:
291 return 20;
292 case BuildIdKind::Hexstring:
293 return Config->BuildIdVector.size();
294 default:
295 llvm_unreachable("unknown BuildIdKind");
296 }
297}
298
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000299template <class ELFT>
300BuildIdSection<ELFT>::BuildIdSection()
301 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000302 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000303
304template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
305 const endianness E = ELFT::TargetEndianness;
306 write32<E>(Buf, 4); // Name size
307 write32<E>(Buf + 4, HashSize); // Content size
308 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
309 memcpy(Buf + 12, "GNU", 4); // Name string
310 HashBuf = Buf + 16;
311}
312
Rui Ueyama35e00752016-11-10 00:12:28 +0000313// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000314static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
315 size_t ChunkSize) {
316 std::vector<ArrayRef<uint8_t>> Ret;
317 while (Arr.size() > ChunkSize) {
318 Ret.push_back(Arr.take_front(ChunkSize));
319 Arr = Arr.drop_front(ChunkSize);
320 }
321 if (!Arr.empty())
322 Ret.push_back(Arr);
323 return Ret;
324}
325
Rui Ueyama35e00752016-11-10 00:12:28 +0000326// Computes a hash value of Data using a given hash function.
327// In order to utilize multiple cores, we first split data into 1MB
328// chunks, compute a hash for each chunk, and then compute a hash value
329// of the hash values.
George Rimar364b59e22016-11-06 07:42:55 +0000330template <class ELFT>
331void BuildIdSection<ELFT>::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000332 llvm::ArrayRef<uint8_t> Data,
333 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000334 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000335 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000336
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000337 // Compute hash values.
Rui Ueyama244a4352016-12-03 21:24:51 +0000338 forLoop(0, Chunks.size(),
339 [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); });
Rui Ueyama35e00752016-11-10 00:12:28 +0000340
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000341 // Write to the final output buffer.
342 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000343}
344
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000345template <class ELFT>
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000346void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000347 switch (Config->BuildId) {
348 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000349 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000350 write64le(Dest, xxHash64(toStringRef(Arr)));
351 });
352 break;
353 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000354 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000355 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000356 });
357 break;
358 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000359 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000360 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000361 });
362 break;
363 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000364 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000365 error("entropy source failure");
366 break;
367 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000368 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000369 break;
370 default:
371 llvm_unreachable("unknown BuildIdKind");
372 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000373}
374
Eugene Leviant41ca3272016-11-10 09:48:29 +0000375template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000376GotSection<ELFT>::GotSection()
377 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
Simon Atanasyan725dc142016-11-16 21:01:02 +0000378 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000379
380template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000381 Sym.GotIndex = NumEntries;
382 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000383}
384
Simon Atanasyan725dc142016-11-16 21:01:02 +0000385template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
386 if (Sym.GlobalDynIndex != -1U)
387 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000388 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000389 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000390 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000391 return true;
392}
393
394// Reserves TLS entries for a TLS module ID and a TLS block offset.
395// In total it takes two GOT slots.
396template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
397 if (TlsIndexOff != uint32_t(-1))
398 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000399 TlsIndexOff = NumEntries * sizeof(uintX_t);
400 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000401 return true;
402}
403
Eugene Leviantad4439e2016-11-11 11:33:32 +0000404template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000405typename GotSection<ELFT>::uintX_t
406GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
407 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
408}
409
410template <class ELFT>
411typename GotSection<ELFT>::uintX_t
412GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
413 return B.GlobalDynIndex * sizeof(uintX_t);
414}
415
416template <class ELFT> void GotSection<ELFT>::finalize() {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000417 Size = NumEntries * sizeof(uintX_t);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000418}
419
George Rimar11992c862016-11-25 08:05:41 +0000420template <class ELFT> bool GotSection<ELFT>::empty() const {
421 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
422 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000423 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000424}
425
Simon Atanasyan725dc142016-11-16 21:01:02 +0000426template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000427 this->relocate(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000428}
429
430template <class ELFT>
431MipsGotSection<ELFT>::MipsGotSection()
432 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL,
433 SHT_PROGBITS, Target->GotEntrySize, ".got") {}
434
435template <class ELFT>
436void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, uintX_t Addend,
Eugene Leviantad4439e2016-11-11 11:33:32 +0000437 RelExpr Expr) {
438 // For "true" local symbols which can be referenced from the same module
439 // only compiler creates two instructions for address loading:
440 //
441 // lw $8, 0($gp) # R_MIPS_GOT16
442 // addi $8, $8, 0 # R_MIPS_LO16
443 //
444 // The first instruction loads high 16 bits of the symbol address while
445 // the second adds an offset. That allows to reduce number of required
446 // GOT entries because only one global offset table entry is necessary
447 // for every 64 KBytes of local data. So for local symbols we need to
448 // allocate number of GOT entries to hold all required "page" addresses.
449 //
450 // All global symbols (hidden and regular) considered by compiler uniformly.
451 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
452 // to load address of the symbol. So for each such symbol we need to
453 // allocate dedicated GOT entry to store its address.
454 //
455 // If a symbol is preemptible we need help of dynamic linker to get its
456 // final address. The corresponding GOT entries are allocated in the
457 // "global" part of GOT. Entries for non preemptible global symbol allocated
458 // in the "local" part of GOT.
459 //
460 // See "Global Offset Table" in Chapter 5:
461 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
462 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
463 // At this point we do not know final symbol value so to reduce number
464 // of allocated GOT entries do the following trick. Save all output
465 // sections referenced by GOT relocations. Then later in the `finalize`
466 // method calculate number of "pages" required to cover all saved output
467 // section and allocate appropriate number of GOT entries.
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000468 PageIndexMap.insert({cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec, 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000469 return;
470 }
471 if (Sym.isTls()) {
472 // GOT entries created for MIPS TLS relocations behave like
473 // almost GOT entries from other ABIs. They go to the end
474 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000475 Sym.GotIndex = TlsEntries.size();
476 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000477 return;
478 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000479 auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000480 if (S.isInGot() && !A)
481 return;
482 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000483 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000484 return;
485 Items.emplace_back(&S, A);
486 if (!A)
487 S.GotIndex = NewIndex;
488 };
489 if (Sym.isPreemptible()) {
490 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000491 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000492 Sym.IsInGlobalMipsGot = true;
493 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000494 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000495 Sym.Is32BitMipsGot = true;
496 } else {
497 // Hold local GOT entries accessed via a 16-bit index separately.
498 // That allows to write them in the beginning of the GOT and keep
499 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000500 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000501 }
502}
503
Simon Atanasyan725dc142016-11-16 21:01:02 +0000504template <class ELFT> bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000505 if (Sym.GlobalDynIndex != -1U)
506 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000507 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000508 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000509 TlsEntries.push_back(nullptr);
510 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000511 return true;
512}
513
514// Reserves TLS entries for a TLS module ID and a TLS block offset.
515// In total it takes two GOT slots.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000516template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000517 if (TlsIndexOff != uint32_t(-1))
518 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000519 TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
520 TlsEntries.push_back(nullptr);
521 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000522 return true;
523}
524
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000525static uint64_t getMipsPageAddr(uint64_t Addr) {
526 return (Addr + 0x8000) & ~0xffff;
527}
528
529static uint64_t getMipsPageCount(uint64_t Size) {
530 return (Size + 0xfffe) / 0xffff + 1;
531}
532
Eugene Leviantad4439e2016-11-11 11:33:32 +0000533template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000534typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000535MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
536 uintX_t Addend) const {
537 const OutputSectionBase *OutSec =
538 cast<DefinedRegular<ELFT>>(&B)->Section->OutSec;
539 uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
540 uintX_t SymAddr = getMipsPageAddr(B.getVA<ELFT>(Addend));
541 uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
542 assert(Index < PageEntriesNum);
543 return (HeaderEntriesNum + Index) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000544}
545
546template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000547typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000548MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
549 uintX_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000550 // Calculate offset of the GOT entries block: TLS, global, local.
Simon Atanasyana0efc422016-11-29 10:23:50 +0000551 uintX_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000552 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000553 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000554 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000555 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000556 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000557 Index += LocalEntries.size();
558 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000559 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000560 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000561 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000562 auto It = EntryIndexMap.find({&B, Addend});
563 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000564 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000565 }
Simon Atanasyana0efc422016-11-29 10:23:50 +0000566 return Index * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000567}
568
569template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000570typename MipsGotSection<ELFT>::uintX_t
571MipsGotSection<ELFT>::getTlsOffset() const {
572 return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000573}
574
575template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000576typename MipsGotSection<ELFT>::uintX_t
577MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000578 return B.GlobalDynIndex * sizeof(uintX_t);
579}
580
581template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000582const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
583 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000584}
585
586template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000587unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000588 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
589 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000590}
591
Simon Atanasyan725dc142016-11-16 21:01:02 +0000592template <class ELFT> void MipsGotSection<ELFT>::finalize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000593 PageEntriesNum = 0;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000594 for (std::pair<const OutputSectionBase *, size_t> &P : PageIndexMap) {
595 // For each output section referenced by GOT page relocations calculate
596 // and save into PageIndexMap an upper bound of MIPS GOT entries required
597 // to store page addresses of local symbols. We assume the worst case -
598 // each 64kb page of the output section has at least one GOT relocation
599 // against it. And take in account the case when the section intersects
600 // page boundaries.
601 P.second = PageEntriesNum;
602 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000603 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000604 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
605 sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000606}
607
George Rimar11992c862016-11-25 08:05:41 +0000608template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
609 // We add the .got section to the result for dynamic MIPS target because
610 // its address and properties are mentioned in the .dynamic section.
611 return Config->Relocatable;
612}
613
Simon Atanasyan8469b882016-11-23 22:22:16 +0000614template <class ELFT> unsigned MipsGotSection<ELFT>::getGp() const {
615 return ElfSym<ELFT>::MipsGp->template getVA<ELFT>(0);
616}
617
Eugene Leviantad4439e2016-11-11 11:33:32 +0000618template <class ELFT>
619static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
620 typedef typename ELFT::uint uintX_t;
621 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
622}
623
Simon Atanasyan725dc142016-11-16 21:01:02 +0000624template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000625 // Set the MSB of the second GOT slot. This is not required by any
626 // MIPS ABI documentation, though.
627 //
628 // There is a comment in glibc saying that "The MSB of got[1] of a
629 // gnu object is set to identify gnu objects," and in GNU gold it
630 // says "the second entry will be used by some runtime loaders".
631 // But how this field is being used is unclear.
632 //
633 // We are not really willing to mimic other linkers behaviors
634 // without understanding why they do that, but because all files
635 // generated by GNU tools have this special GOT value, and because
636 // we've been doing this for years, it is probably a safe bet to
637 // keep doing this for now. We really need to revisit this to see
638 // if we had to do this.
639 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
640 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
Simon Atanasyana0efc422016-11-29 10:23:50 +0000641 Buf += HeaderEntriesNum * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000642 // Write 'page address' entries to the local part of the GOT.
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000643 for (std::pair<const OutputSectionBase *, size_t> &L : PageIndexMap) {
644 size_t PageCount = getMipsPageCount(L.first->Size);
645 uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
646 for (size_t PI = 0; PI < PageCount; ++PI) {
647 uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
648 writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
649 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000650 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000651 Buf += PageEntriesNum * sizeof(uintX_t);
652 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000653 uint8_t *Entry = Buf;
654 Buf += sizeof(uintX_t);
655 const SymbolBody *Body = SA.first;
656 uintX_t VA = Body->template getVA<ELFT>(SA.second);
657 writeUint<ELFT>(Entry, VA);
658 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000659 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
660 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
661 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000662 // Initialize TLS-related GOT entries. If the entry has a corresponding
663 // dynamic relocations, leave it initialized by zero. Write down adjusted
664 // TLS symbol's values otherwise. To calculate the adjustments use offsets
665 // for thread-local storage.
666 // https://www.linux-mips.org/wiki/NPTL
667 if (TlsIndexOff != -1U && !Config->Pic)
668 writeUint<ELFT>(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000669 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000670 if (!B || B->isPreemptible())
671 continue;
672 uintX_t VA = B->getVA<ELFT>();
673 if (B->GotIndex != -1U) {
674 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
675 writeUint<ELFT>(Entry, VA - 0x7000);
676 }
677 if (B->GlobalDynIndex != -1U) {
678 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
679 writeUint<ELFT>(Entry, 1);
680 Entry += sizeof(uintX_t);
681 writeUint<ELFT>(Entry, VA - 0x8000);
682 }
683 }
684}
685
Eugene Leviantad4439e2016-11-11 11:33:32 +0000686template <class ELFT>
Eugene Leviant41ca3272016-11-10 09:48:29 +0000687GotPltSection<ELFT>::GotPltSection()
688 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
George Rimard8b27762016-11-14 10:14:18 +0000689 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000690
691template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
692 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
693 Entries.push_back(&Sym);
694}
695
Eugene Leviant41ca3272016-11-10 09:48:29 +0000696template <class ELFT> size_t GotPltSection<ELFT>::getSize() const {
697 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
698 Target->GotPltEntrySize;
699}
700
701template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
702 Target->writeGotPltHeader(Buf);
703 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
704 for (const SymbolBody *B : Entries) {
705 Target->writeGotPlt(Buf, *B);
706 Buf += sizeof(uintX_t);
707 }
708}
709
Peter Smithbaffdb82016-12-08 12:58:55 +0000710// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
711// part of the .got.plt
712template <class ELFT>
713IgotPltSection<ELFT>::IgotPltSection()
714 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
715 Target->GotPltEntrySize,
716 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {
717}
718
719template <class ELFT> void IgotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
720 Sym.IsInIgot = true;
721 Sym.GotPltIndex = Entries.size();
722 Entries.push_back(&Sym);
723}
724
725template <class ELFT> size_t IgotPltSection<ELFT>::getSize() const {
726 return Entries.size() * Target->GotPltEntrySize;
727}
728
729template <class ELFT> void IgotPltSection<ELFT>::writeTo(uint8_t *Buf) {
730 for (const SymbolBody *B : Entries) {
731 if (Config->EMachine == EM_ARM)
732 // On ARM we are actually part of the Got and not GotPlt.
733 write32le(Buf, B->getVA<ELFT>());
734 else
735 Target->writeGotPlt(Buf, *B);
736 Buf += sizeof(uintX_t);
737 }
738}
739
Eugene Leviant22eb0262016-11-14 09:16:00 +0000740template <class ELFT>
741StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
742 : SyntheticSection<ELFT>(Dynamic ? (uintX_t)SHF_ALLOC : 0, SHT_STRTAB, 1,
743 Name),
744 Dynamic(Dynamic) {}
745
746// Adds a string to the string table. If HashIt is true we hash and check for
747// duplicates. It is optional because the name of global symbols are already
748// uniqued and hashing them again has a big cost for a small value: uniquing
749// them with some other string that happens to be the same.
750template <class ELFT>
751unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
752 if (HashIt) {
753 auto R = StringMap.insert(std::make_pair(S, this->Size));
754 if (!R.second)
755 return R.first->second;
756 }
757 unsigned Ret = this->Size;
758 this->Size = this->Size + S.size() + 1;
759 Strings.push_back(S);
760 return Ret;
761}
762
763template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
764 // ELF string tables start with NUL byte, so advance the pointer by one.
765 ++Buf;
766 for (StringRef S : Strings) {
767 memcpy(Buf, S.data(), S.size());
768 Buf += S.size() + 1;
769 }
770}
771
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000772// Returns the number of version definition entries. Because the first entry
773// is for the version definition itself, it is the number of versioned symbols
774// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000775static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
776
777template <class ELFT>
778DynamicSection<ELFT>::DynamicSection()
779 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC,
780 sizeof(uintX_t), ".dynamic") {
781 this->Entsize = ELFT::Is64Bits ? 16 : 8;
782 // .dynamic section is not writable on MIPS.
783 // See "Special Section" in Chapter 4 in the following document:
784 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
785 if (Config->EMachine == EM_MIPS)
786 this->Flags = SHF_ALLOC;
787
788 addEntries();
789}
790
791// There are some dynamic entries that don't depend on other sections.
792// Such entries can be set early.
793template <class ELFT> void DynamicSection<ELFT>::addEntries() {
794 // Add strings to .dynstr early so that .dynstr's size will be
795 // fixed early.
796 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +0000797 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000798 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +0000799 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000800 In<ELFT>::DynStrTab->addString(Config->RPath)});
801 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
802 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +0000803 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000804 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +0000805 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000806
807 // Set DT_FLAGS and DT_FLAGS_1.
808 uint32_t DtFlags = 0;
809 uint32_t DtFlags1 = 0;
810 if (Config->Bsymbolic)
811 DtFlags |= DF_SYMBOLIC;
812 if (Config->ZNodelete)
813 DtFlags1 |= DF_1_NODELETE;
814 if (Config->ZNow) {
815 DtFlags |= DF_BIND_NOW;
816 DtFlags1 |= DF_1_NOW;
817 }
818 if (Config->ZOrigin) {
819 DtFlags |= DF_ORIGIN;
820 DtFlags1 |= DF_1_ORIGIN;
821 }
822
823 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +0000824 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000825 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +0000826 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000827
Petr Hosek668bebe2016-12-07 02:05:42 +0000828 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +0000829 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000830}
831
832// Add remaining entries to complete .dynamic contents.
833template <class ELFT> void DynamicSection<ELFT>::finalize() {
834 if (this->Size)
835 return; // Already finalized.
836
837 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +0000838 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000839 bool IsRela = Config->Rela;
Rui Ueyama729ac792016-11-17 04:10:09 +0000840 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +0000841 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +0000842 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000843 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
844
845 // MIPS dynamic loader does not support RELCOUNT tag.
846 // The problem is in the tight relation between dynamic
847 // relocations and GOT. So do not emit this tag on MIPS.
848 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +0000849 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +0000850 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +0000851 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000852 }
853 }
Peter Smithbaffdb82016-12-08 12:58:55 +0000854 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000855 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +0000856 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +0000857 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +0000858 In<ELFT>::GotPlt});
Rui Ueyama729ac792016-11-17 04:10:09 +0000859 add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000860 }
861
Eugene Leviant9230db92016-11-17 09:16:34 +0000862 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +0000863 add({DT_SYMENT, sizeof(Elf_Sym)});
864 add({DT_STRTAB, In<ELFT>::DynStrTab});
865 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
Eugene Leviantbe809a72016-11-18 06:44:18 +0000866 if (In<ELFT>::GnuHashTab)
867 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +0000868 if (In<ELFT>::HashTab)
869 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000870
871 if (Out<ELFT>::PreinitArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000872 add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
873 add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000874 }
875 if (Out<ELFT>::InitArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000876 add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
877 add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000878 }
879 if (Out<ELFT>::FiniArray) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000880 add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
881 add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000882 }
883
884 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +0000885 add({DT_INIT, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000886 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +0000887 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000888
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000889 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
890 if (HasVerNeed || In<ELFT>::VerDef)
891 add({DT_VERSYM, In<ELFT>::VerSym});
892 if (In<ELFT>::VerDef) {
893 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +0000894 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000895 }
896 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000897 add({DT_VERNEED, In<ELFT>::VerNeed});
898 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000899 }
900
901 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +0000902 add({DT_MIPS_RLD_VERSION, 1});
903 add({DT_MIPS_FLAGS, RHF_NOTPOT});
904 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +0000905 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000906 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
907 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +0000908 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000909 else
Eugene Leviant9230db92016-11-17 09:16:34 +0000910 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +0000911 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +0000912 if (In<ELFT>::MipsRldMap)
913 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +0000914 }
915
916 this->OutSec->Entsize = this->Entsize;
917 this->OutSec->Link = this->Link;
918
919 // +1 for DT_NULL
920 this->Size = (Entries.size() + 1) * this->Entsize;
921}
922
923template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
924 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
925
926 for (const Entry &E : Entries) {
927 P->d_tag = E.Tag;
928 switch (E.Kind) {
929 case Entry::SecAddr:
930 P->d_un.d_ptr = E.OutSec->Addr;
931 break;
932 case Entry::InSecAddr:
933 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
934 break;
935 case Entry::SecSize:
936 P->d_un.d_val = E.OutSec->Size;
937 break;
938 case Entry::SymAddr:
939 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
940 break;
941 case Entry::PlainInt:
942 P->d_un.d_val = E.Val;
943 break;
944 }
945 ++P;
946 }
947}
948
Eugene Levianta96d9022016-11-16 10:02:27 +0000949template <class ELFT>
950typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
951 if (OutputSec)
952 return OutputSec->Addr + OffsetInSec;
953 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
954}
955
956template <class ELFT>
957typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
958 if (UseSymVA)
959 return Sym->getVA<ELFT>(Addend);
960 return Addend;
961}
962
963template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
964 if (Sym && !UseSymVA)
965 return Sym->DynsymIndex;
966 return 0;
967}
968
969template <class ELFT>
970RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
971 : SyntheticSection<ELFT>(SHF_ALLOC, Config->Rela ? SHT_RELA : SHT_REL,
972 sizeof(uintX_t), Name),
973 Sort(Sort) {
974 this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
975}
976
977template <class ELFT>
978void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
979 if (Reloc.Type == Target->RelativeRel)
980 ++NumRelativeRelocs;
981 Relocs.push_back(Reloc);
982}
983
984template <class ELFT, class RelTy>
985static bool compRelocations(const RelTy &A, const RelTy &B) {
986 bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
987 bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
988 if (AIsRel != BIsRel)
989 return AIsRel;
990
991 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
992}
993
994template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
995 uint8_t *BufBegin = Buf;
996 for (const DynamicReloc<ELFT> &Rel : Relocs) {
997 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
998 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
999
1000 if (Config->Rela)
1001 P->r_addend = Rel.getAddend();
1002 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001003 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001004 // Dynamic relocation against MIPS GOT section make deal TLS entries
1005 // allocated in the end of the GOT. We need to adjust the offset to take
1006 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001007 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Eugene Levianta96d9022016-11-16 10:02:27 +00001008 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
1009 }
1010
1011 if (Sort) {
1012 if (Config->Rela)
1013 std::stable_sort((Elf_Rela *)BufBegin,
1014 (Elf_Rela *)BufBegin + Relocs.size(),
1015 compRelocations<ELFT, Elf_Rela>);
1016 else
1017 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1018 compRelocations<ELFT, Elf_Rel>);
1019 }
1020}
1021
1022template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1023 return this->Entsize * Relocs.size();
1024}
1025
1026template <class ELFT> void RelocationSection<ELFT>::finalize() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001027 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1028 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001029
1030 // Set required output section properties.
1031 this->OutSec->Link = this->Link;
1032 this->OutSec->Entsize = this->Entsize;
1033}
1034
Eugene Leviant9230db92016-11-17 09:16:34 +00001035template <class ELFT>
1036SymbolTableSection<ELFT>::SymbolTableSection(
1037 StringTableSection<ELFT> &StrTabSec)
1038 : SyntheticSection<ELFT>(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1039 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1040 sizeof(uintX_t),
1041 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1042 StrTabSec(StrTabSec) {
1043 this->Entsize = sizeof(Elf_Sym);
1044}
1045
1046// Orders symbols according to their positions in the GOT,
1047// in compliance with MIPS ABI rules.
1048// See "Global Offset Table" in Chapter 5 in the following document
1049// for detailed description:
1050// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1051static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
1052 // Sort entries related to non-local preemptible symbols by GOT indexes.
1053 // All other entries go to the first part of GOT in arbitrary order.
1054 bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1055 bool RIsInLocalGot = !R->IsInGlobalMipsGot;
1056 if (LIsInLocalGot || RIsInLocalGot)
1057 return !RIsInLocalGot;
1058 return L->GotIndex < R->GotIndex;
1059}
1060
1061static uint8_t getSymbolBinding(SymbolBody *Body) {
1062 Symbol *S = Body->symbol();
1063 if (Config->Relocatable)
1064 return S->Binding;
1065 uint8_t Visibility = S->Visibility;
1066 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1067 return STB_LOCAL;
1068 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
1069 return STB_GLOBAL;
1070 return S->Binding;
1071}
1072
1073template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1074 this->OutSec->Link = this->Link = StrTabSec.OutSec->SectionIndex;
1075 this->OutSec->Info = this->Info = NumLocals + 1;
1076 this->OutSec->Entsize = this->Entsize;
1077
1078 if (Config->Relocatable) {
1079 size_t I = NumLocals;
1080 for (const SymbolTableEntry &S : Symbols)
1081 S.Symbol->DynsymIndex = ++I;
1082 return;
1083 }
1084
1085 if (!StrTabSec.isDynamic()) {
1086 std::stable_sort(Symbols.begin(), Symbols.end(),
1087 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1088 return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1089 getSymbolBinding(R.Symbol) != STB_LOCAL;
1090 });
1091 return;
1092 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001093 if (In<ELFT>::GnuHashTab)
Eugene Leviant9230db92016-11-17 09:16:34 +00001094 // NB: It also sorts Symbols to meet the GNU hash table requirements.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001095 In<ELFT>::GnuHashTab->addSymbols(Symbols);
Eugene Leviant9230db92016-11-17 09:16:34 +00001096 else if (Config->EMachine == EM_MIPS)
1097 std::stable_sort(Symbols.begin(), Symbols.end(),
1098 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1099 return sortMipsSymbols(L.Symbol, R.Symbol);
1100 });
1101 size_t I = 0;
1102 for (const SymbolTableEntry &S : Symbols)
1103 S.Symbol->DynsymIndex = ++I;
1104}
1105
1106template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1107 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1108}
1109
1110template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1111 Buf += sizeof(Elf_Sym);
1112
1113 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1114 // .dynsym only contains global symbols.
1115 if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
1116 writeLocalSymbols(Buf);
1117
1118 writeGlobalSymbols(Buf);
1119}
1120
1121template <class ELFT>
1122void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1123 // Iterate over all input object files to copy their local symbols
1124 // to the output symbol table pointed by Buf.
1125 for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
1126 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1127 File->KeptLocalSyms) {
1128 const DefinedRegular<ELFT> &Body = *P.first;
1129 InputSectionBase<ELFT> *Section = Body.Section;
1130 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1131
1132 if (!Section) {
1133 ESym->st_shndx = SHN_ABS;
1134 ESym->st_value = Body.Value;
1135 } else {
1136 const OutputSectionBase *OutSec = Section->OutSec;
1137 ESym->st_shndx = OutSec->SectionIndex;
1138 ESym->st_value = OutSec->Addr + Section->getOffset(Body);
1139 }
1140 ESym->st_name = P.second;
1141 ESym->st_size = Body.template getSize<ELFT>();
1142 ESym->setBindingAndType(STB_LOCAL, Body.Type);
1143 Buf += sizeof(*ESym);
1144 }
1145 }
1146}
1147
1148template <class ELFT>
1149void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1150 // Write the internal symbol table contents to the output symbol table
1151 // pointed by Buf.
1152 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1153 for (const SymbolTableEntry &S : Symbols) {
1154 SymbolBody *Body = S.Symbol;
1155 size_t StrOff = S.StrTabOffset;
1156
1157 uint8_t Type = Body->Type;
1158 uintX_t Size = Body->getSize<ELFT>();
1159
1160 ESym->setBindingAndType(getSymbolBinding(Body), Type);
1161 ESym->st_size = Size;
1162 ESym->st_name = StrOff;
1163 ESym->setVisibility(Body->symbol()->Visibility);
1164 ESym->st_value = Body->getVA<ELFT>();
1165
1166 if (const OutputSectionBase *OutSec = getOutputSection(Body))
1167 ESym->st_shndx = OutSec->SectionIndex;
1168 else if (isa<DefinedRegular<ELFT>>(Body))
1169 ESym->st_shndx = SHN_ABS;
1170
1171 if (Config->EMachine == EM_MIPS) {
1172 // On MIPS we need to mark symbol which has a PLT entry and requires
1173 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1174 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1175 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1176 if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1177 ESym->st_other |= STO_MIPS_PLT;
1178 if (Config->Relocatable) {
1179 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1180 if (D && D->isMipsPIC())
1181 ESym->st_other |= STO_MIPS_PIC;
1182 }
1183 }
1184 ++ESym;
1185 }
1186}
1187
1188template <class ELFT>
1189const OutputSectionBase *
1190SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1191 switch (Sym->kind()) {
1192 case SymbolBody::DefinedSyntheticKind:
1193 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1194 case SymbolBody::DefinedRegularKind: {
1195 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1196 if (D.Section)
1197 return D.Section->OutSec;
1198 break;
1199 }
1200 case SymbolBody::DefinedCommonKind:
1201 return In<ELFT>::Common->OutSec;
1202 case SymbolBody::SharedKind:
1203 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1204 return Out<ELFT>::Bss;
1205 break;
1206 case SymbolBody::UndefinedKind:
1207 case SymbolBody::LazyArchiveKind:
1208 case SymbolBody::LazyObjectKind:
1209 break;
1210 }
1211 return nullptr;
1212}
1213
Eugene Leviantbe809a72016-11-18 06:44:18 +00001214template <class ELFT>
1215GnuHashTableSection<ELFT>::GnuHashTableSection()
1216 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t),
1217 ".gnu.hash") {
1218 this->Entsize = ELFT::Is64Bits ? 0 : 4;
1219}
1220
1221template <class ELFT>
1222unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
1223 if (!NumHashed)
1224 return 0;
1225
1226 // These values are prime numbers which are not greater than 2^(N-1) + 1.
1227 // In result, for any particular NumHashed we return a prime number
1228 // which is not greater than NumHashed.
1229 static const unsigned Primes[] = {
1230 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
1231 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
1232
1233 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
1234 array_lengthof(Primes) - 1)];
1235}
1236
1237// Bloom filter estimation: at least 8 bits for each hashed symbol.
1238// GNU Hash table requirement: it should be a power of 2,
1239// the minimum value is 1, even for an empty table.
1240// Expected results for a 32-bit target:
1241// calcMaskWords(0..4) = 1
1242// calcMaskWords(5..8) = 2
1243// calcMaskWords(9..16) = 4
1244// For a 64-bit target:
1245// calcMaskWords(0..8) = 1
1246// calcMaskWords(9..16) = 2
1247// calcMaskWords(17..32) = 4
1248template <class ELFT>
1249unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
1250 if (!NumHashed)
1251 return 1;
1252 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
1253}
1254
1255template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
1256 unsigned NumHashed = Symbols.size();
1257 NBuckets = calcNBuckets(NumHashed);
1258 MaskWords = calcMaskWords(NumHashed);
1259 // Second hash shift estimation: just predefined values.
1260 Shift2 = ELFT::Is64Bits ? 6 : 5;
1261
1262 this->OutSec->Entsize = this->Entsize;
1263 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1264 this->Size = sizeof(Elf_Word) * 4 // Header
1265 + sizeof(Elf_Off) * MaskWords // Bloom Filter
1266 + sizeof(Elf_Word) * NBuckets // Hash Buckets
1267 + sizeof(Elf_Word) * NumHashed; // Hash Values
1268}
1269
1270template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1271 writeHeader(Buf);
1272 if (Symbols.empty())
1273 return;
1274 writeBloomFilter(Buf);
1275 writeHashTable(Buf);
1276}
1277
1278template <class ELFT>
1279void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
1280 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1281 *P++ = NBuckets;
1282 *P++ = In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
1283 *P++ = MaskWords;
1284 *P++ = Shift2;
1285 Buf = reinterpret_cast<uint8_t *>(P);
1286}
1287
1288template <class ELFT>
1289void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
1290 unsigned C = sizeof(Elf_Off) * 8;
1291
1292 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
1293 for (const SymbolData &Sym : Symbols) {
1294 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
1295 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
1296 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
1297 Masks[Pos] |= V;
1298 }
1299 Buf += sizeof(Elf_Off) * MaskWords;
1300}
1301
1302template <class ELFT>
1303void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
1304 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1305 Elf_Word *Values = Buckets + NBuckets;
1306
1307 int PrevBucket = -1;
1308 int I = 0;
1309 for (const SymbolData &Sym : Symbols) {
1310 int Bucket = Sym.Hash % NBuckets;
1311 assert(PrevBucket <= Bucket);
1312 if (Bucket != PrevBucket) {
1313 Buckets[Bucket] = Sym.Body->DynsymIndex;
1314 PrevBucket = Bucket;
1315 if (I > 0)
1316 Values[I - 1] |= 1;
1317 }
1318 Values[I] = Sym.Hash & ~1;
1319 ++I;
1320 }
1321 if (I > 0)
1322 Values[I - 1] |= 1;
1323}
1324
1325static uint32_t hashGnu(StringRef Name) {
1326 uint32_t H = 5381;
1327 for (uint8_t C : Name)
1328 H = (H << 5) + H + C;
1329 return H;
1330}
1331
1332// Add symbols to this symbol hash table. Note that this function
1333// destructively sort a given vector -- which is needed because
1334// GNU-style hash table places some sorting requirements.
1335template <class ELFT>
1336void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
1337 // Ideally this will just be 'auto' but GCC 6.1 is not able
1338 // to deduce it correctly.
1339 std::vector<SymbolTableEntry>::iterator Mid =
1340 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1341 return S.Symbol->isUndefined();
1342 });
1343 if (Mid == V.end())
1344 return;
1345 for (auto I = Mid, E = V.end(); I != E; ++I) {
1346 SymbolBody *B = I->Symbol;
1347 size_t StrOff = I->StrTabOffset;
1348 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
1349 }
1350
1351 unsigned NBuckets = calcNBuckets(Symbols.size());
1352 std::stable_sort(Symbols.begin(), Symbols.end(),
1353 [&](const SymbolData &L, const SymbolData &R) {
1354 return L.Hash % NBuckets < R.Hash % NBuckets;
1355 });
1356
1357 V.erase(Mid, V.end());
1358 for (const SymbolData &Sym : Symbols)
1359 V.push_back({Sym.Body, Sym.STName});
1360}
1361
Eugene Leviantb96e8092016-11-18 09:06:47 +00001362template <class ELFT>
1363HashTableSection<ELFT>::HashTableSection()
1364 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_HASH, sizeof(Elf_Word), ".hash") {
1365 this->Entsize = sizeof(Elf_Word);
1366}
1367
1368template <class ELFT> void HashTableSection<ELFT>::finalize() {
1369 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1370 this->OutSec->Entsize = this->Entsize;
1371
1372 unsigned NumEntries = 2; // nbucket and nchain.
1373 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1374
1375 // Create as many buckets as there are symbols.
1376 // FIXME: This is simplistic. We can try to optimize it, but implementing
1377 // support for SHT_GNU_HASH is probably even more profitable.
1378 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
1379 this->Size = NumEntries * sizeof(Elf_Word);
1380}
1381
1382template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
1383 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
1384 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1385 *P++ = NumSymbols; // nbucket
1386 *P++ = NumSymbols; // nchain
1387
1388 Elf_Word *Buckets = P;
1389 Elf_Word *Chains = P + NumSymbols;
1390
1391 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1392 SymbolBody *Body = S.Symbol;
1393 StringRef Name = Body->getName();
1394 unsigned I = Body->DynsymIndex;
1395 uint32_t Hash = hashSysV(Name) % NumSymbols;
1396 Chains[I] = Buckets[Hash];
1397 Buckets[Hash] = I;
1398 }
1399}
1400
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001401template <class ELFT>
1402PltSection<ELFT>::PltSection()
1403 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1404 ".plt") {}
1405
1406template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
1407 // At beginning of PLT, we have code to call the dynamic linker
1408 // to resolve dynsyms at runtime. Write such code.
1409 Target->writePltHeader(Buf);
1410 size_t Off = Target->PltHeaderSize;
1411
1412 for (auto &I : Entries) {
1413 const SymbolBody *B = I.first;
1414 unsigned RelOff = I.second;
1415 uint64_t Got = B->getGotPltVA<ELFT>();
1416 uint64_t Plt = this->getVA() + Off;
1417 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1418 Off += Target->PltEntrySize;
1419 }
1420}
1421
1422template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
1423 Sym.PltIndex = Entries.size();
1424 unsigned RelOff = In<ELFT>::RelaPlt->getRelocOffset();
1425 Entries.push_back(std::make_pair(&Sym, RelOff));
1426}
1427
1428template <class ELFT> size_t PltSection<ELFT>::getSize() const {
1429 return Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
1430}
1431
Eugene Levianta113a412016-11-21 09:24:43 +00001432template <class ELFT>
Peter Smithbaffdb82016-12-08 12:58:55 +00001433IpltSection<ELFT>::IpltSection()
1434 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
1435 ".plt") {}
1436
1437template <class ELFT> void IpltSection<ELFT>::writeTo(uint8_t *Buf) {
1438 // The IRelative relocations do not support lazy binding so no header is
1439 // needed
1440 size_t Off = 0;
1441 for (auto &I : Entries) {
1442 const SymbolBody *B = I.first;
1443 unsigned RelOff = I.second + In<ELFT>::Plt->getSize();
1444 uint64_t Got = B->getGotPltVA<ELFT>();
1445 uint64_t Plt = this->getVA() + Off;
1446 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1447 Off += Target->PltEntrySize;
1448 }
1449}
1450
1451template <class ELFT> void IpltSection<ELFT>::addEntry(SymbolBody &Sym) {
1452 Sym.PltIndex = Entries.size();
1453 Sym.IsInIplt = true;
1454 unsigned RelOff = In<ELFT>::RelaIplt->getRelocOffset();
1455 Entries.push_back(std::make_pair(&Sym, RelOff));
1456}
1457
1458template <class ELFT> size_t IpltSection<ELFT>::getSize() const {
1459 return Entries.size() * Target->PltEntrySize;
1460}
1461
1462template <class ELFT>
Eugene Levianta113a412016-11-21 09:24:43 +00001463GdbIndexSection<ELFT>::GdbIndexSection()
1464 : SyntheticSection<ELFT>(0, SHT_PROGBITS, 1, ".gdb_index") {}
1465
1466template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
1467 std::vector<InputSection<ELFT> *> &IS =
1468 static_cast<OutputSection<ELFT> *>(Out<ELFT>::DebugInfo)->Sections;
1469
1470 for (InputSection<ELFT> *I : IS)
1471 readDwarf(I);
1472}
1473
1474template <class ELFT>
1475void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
1476 std::vector<std::pair<uintX_t, uintX_t>> CuList = readCuList(I);
1477 CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
1478}
1479
1480template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
1481 parseDebugSections();
1482
1483 // GdbIndex header consist from version fields
1484 // and 5 more fields with different kinds of offsets.
1485 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
1486}
1487
1488template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
1489 write32le(Buf, 7); // Write Version
1490 write32le(Buf + 4, CuListOffset); // CU list offset
1491 write32le(Buf + 8, CuTypesOffset); // Types CU list offset
1492 write32le(Buf + 12, CuTypesOffset); // Address area offset
1493 write32le(Buf + 16, CuTypesOffset); // Symbol table offset
1494 write32le(Buf + 20, CuTypesOffset); // Constant pool offset
1495 Buf += 24;
1496
1497 // Write the CU list.
1498 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1499 write64le(Buf, CU.first);
1500 write64le(Buf + 8, CU.second);
1501 Buf += 16;
1502 }
1503}
1504
George Rimar3fb5a6d2016-11-29 16:05:27 +00001505template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
1506 return !Out<ELFT>::DebugInfo;
1507}
1508
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001509template <class ELFT>
1510EhFrameHeader<ELFT>::EhFrameHeader()
1511 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
1512
1513// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1514// Each entry of the search table consists of two values,
1515// the starting PC from where FDEs covers, and the FDE's address.
1516// It is sorted by PC.
1517template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1518 const endianness E = ELFT::TargetEndianness;
1519
1520 // Sort the FDE list by their PC and uniqueify. Usually there is only
1521 // one FDE for a PC (i.e. function), but if ICF merges two functions
1522 // into one, there can be more than one FDEs pointing to the address.
1523 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1524 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1525 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1526 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1527
1528 Buf[0] = 1;
1529 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1530 Buf[2] = DW_EH_PE_udata4;
1531 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
1532 write32<E>(Buf + 4, Out<ELFT>::EhFrame->Addr - this->getVA() - 4);
1533 write32<E>(Buf + 8, Fdes.size());
1534 Buf += 12;
1535
1536 uintX_t VA = this->getVA();
1537 for (FdeData &Fde : Fdes) {
1538 write32<E>(Buf, Fde.Pc - VA);
1539 write32<E>(Buf + 4, Fde.FdeVA - VA);
1540 Buf += 8;
1541 }
1542}
1543
1544template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1545 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
1546 return 12 + Out<ELFT>::EhFrame->NumFdes * 8;
1547}
1548
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001549template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001550void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1551 Fdes.push_back({Pc, FdeVA});
1552}
1553
George Rimar11992c862016-11-25 08:05:41 +00001554template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
1555 return Out<ELFT>::EhFrame->empty();
1556}
1557
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001558template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001559VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1560 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1561 ".gnu.version_d") {}
1562
1563static StringRef getFileDefName() {
1564 if (!Config->SoName.empty())
1565 return Config->SoName;
1566 return Config->OutputFile;
1567}
1568
1569template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1570 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1571 for (VersionDefinition &V : Config->VersionDefinitions)
1572 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1573
1574 this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1575
1576 // sh_info should be set to the number of definitions. This fact is missed in
1577 // documentation, but confirmed by binutils community:
1578 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1579 this->OutSec->Info = this->Info = getVerDefNum();
1580}
1581
1582template <class ELFT>
1583void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1584 StringRef Name, size_t NameOff) {
1585 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1586 Verdef->vd_version = 1;
1587 Verdef->vd_cnt = 1;
1588 Verdef->vd_aux = sizeof(Elf_Verdef);
1589 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1590 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1591 Verdef->vd_ndx = Index;
1592 Verdef->vd_hash = hashSysV(Name);
1593
1594 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1595 Verdaux->vda_name = NameOff;
1596 Verdaux->vda_next = 0;
1597}
1598
1599template <class ELFT>
1600void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1601 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1602
1603 for (VersionDefinition &V : Config->VersionDefinitions) {
1604 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1605 writeOne(Buf, V.Id, V.Name, V.NameOff);
1606 }
1607
1608 // Need to terminate the last version definition.
1609 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1610 Verdef->vd_next = 0;
1611}
1612
1613template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1614 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1615}
1616
1617template <class ELFT>
1618VersionTableSection<ELFT>::VersionTableSection()
1619 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
1620 ".gnu.version") {}
1621
1622template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1623 this->OutSec->Entsize = this->Entsize = sizeof(Elf_Versym);
1624 // At the moment of june 2016 GNU docs does not mention that sh_link field
1625 // should be set, but Sun docs do. Also readelf relies on this field.
1626 this->OutSec->Link = this->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
1627}
1628
1629template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
1630 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
1631}
1632
1633template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1634 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1635 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1636 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
1637 ++OutVersym;
1638 }
1639}
1640
George Rimar11992c862016-11-25 08:05:41 +00001641template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
1642 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
1643}
1644
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001645template <class ELFT>
1646VersionNeedSection<ELFT>::VersionNeedSection()
1647 : SyntheticSection<ELFT>(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
1648 ".gnu.version_r") {
1649 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1650 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1651 // First identifiers are reserved by verdef section if it exist.
1652 NextIndex = getVerDefNum() + 1;
1653}
1654
1655template <class ELFT>
1656void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1657 if (!SS->Verdef) {
1658 SS->symbol()->VersionId = VER_NDX_GLOBAL;
1659 return;
1660 }
1661 SharedFile<ELFT> *F = SS->file();
1662 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1663 // to create one by adding it to our needed list and creating a dynstr entry
1664 // for the soname.
1665 if (F->VerdefMap.empty())
1666 Needed.push_back({F, In<ELFT>::DynStrTab->addString(F->getSoName())});
1667 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1668 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1669 // prepare to create one by allocating a version identifier and creating a
1670 // dynstr entry for the version name.
1671 if (NV.Index == 0) {
1672 NV.StrTab = In<ELFT>::DynStrTab->addString(
1673 SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1674 NV.Index = NextIndex++;
1675 }
1676 SS->symbol()->VersionId = NV.Index;
1677}
1678
1679template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1680 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1681 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1682 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1683
1684 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1685 // Create an Elf_Verneed for this DSO.
1686 Verneed->vn_version = 1;
1687 Verneed->vn_cnt = P.first->VerdefMap.size();
1688 Verneed->vn_file = P.second;
1689 Verneed->vn_aux =
1690 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1691 Verneed->vn_next = sizeof(Elf_Verneed);
1692 ++Verneed;
1693
1694 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1695 // VerdefMap, which will only contain references to needed version
1696 // definitions. Each Elf_Vernaux is based on the information contained in
1697 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1698 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1699 // data structures within a single input file.
1700 for (auto &NV : P.first->VerdefMap) {
1701 Vernaux->vna_hash = NV.first->vd_hash;
1702 Vernaux->vna_flags = 0;
1703 Vernaux->vna_other = NV.second.Index;
1704 Vernaux->vna_name = NV.second.StrTab;
1705 Vernaux->vna_next = sizeof(Elf_Vernaux);
1706 ++Vernaux;
1707 }
1708
1709 Vernaux[-1].vna_next = 0;
1710 }
1711 Verneed[-1].vn_next = 0;
1712}
1713
1714template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1715 this->OutSec->Link = this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
1716 this->OutSec->Info = this->Info = Needed.size();
1717}
1718
1719template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
1720 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1721 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1722 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1723 return Size;
1724}
1725
George Rimar11992c862016-11-25 08:05:41 +00001726template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
1727 return getNeedNum() == 0;
1728}
1729
Eugene Leviant17b7a572016-11-22 17:49:14 +00001730template <class ELFT>
Rui Ueyamabdfa1552016-11-22 19:24:52 +00001731MipsRldMapSection<ELFT>::MipsRldMapSection()
Eugene Leviant17b7a572016-11-22 17:49:14 +00001732 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1733 sizeof(typename ELFT::uint), ".rld_map") {}
1734
Rui Ueyamabdfa1552016-11-22 19:24:52 +00001735template <class ELFT> void MipsRldMapSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00001736 // Apply filler from linker script.
1737 uint64_t Filler = Script<ELFT>::X->getFiller(this->Name);
1738 Filler = (Filler << 32) | Filler;
1739 memcpy(Buf, &Filler, getSize());
1740}
1741
Peter Smith719eb8e2016-11-24 11:43:55 +00001742template <class ELFT>
1743ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
1744 : SyntheticSection<ELFT>(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
1745 sizeof(typename ELFT::uint), ".ARM.exidx") {}
1746
1747// Write a terminating sentinel entry to the end of the .ARM.exidx table.
1748// This section will have been sorted last in the .ARM.exidx table.
1749// This table entry will have the form:
1750// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
1751template <class ELFT> void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf){
1752 // Get the InputSection before us, we are by definition last
1753 auto RI = cast<OutputSection<ELFT>>(this->OutSec)->Sections.rbegin();
1754 InputSection<ELFT> *LE = *(++RI);
1755 InputSection<ELFT> *LC = cast<InputSection<ELFT>>(LE->getLinkOrderDep());
1756 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
1757 uint64_t P = this->getVA();
1758 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
1759 write32le(Buf + 4, 0x1);
1760}
1761
Rafael Espindola682a5bc2016-11-08 14:42:34 +00001762template InputSection<ELF32LE> *elf::createCommonSection();
1763template InputSection<ELF32BE> *elf::createCommonSection();
1764template InputSection<ELF64LE> *elf::createCommonSection();
1765template InputSection<ELF64BE> *elf::createCommonSection();
Rui Ueyamae8a61022016-11-05 23:05:47 +00001766
Rafael Espindolac0e47fb2016-11-08 14:56:27 +00001767template InputSection<ELF32LE> *elf::createInterpSection();
1768template InputSection<ELF32BE> *elf::createInterpSection();
1769template InputSection<ELF64LE> *elf::createInterpSection();
1770template InputSection<ELF64BE> *elf::createInterpSection();
Rui Ueyamae288eef2016-11-02 18:58:44 +00001771
Rui Ueyama3da3f062016-11-10 20:20:37 +00001772template MergeInputSection<ELF32LE> *elf::createCommentSection();
1773template MergeInputSection<ELF32BE> *elf::createCommentSection();
1774template MergeInputSection<ELF64LE> *elf::createCommentSection();
1775template MergeInputSection<ELF64BE> *elf::createCommentSection();
1776
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00001777template class elf::MipsAbiFlagsSection<ELF32LE>;
1778template class elf::MipsAbiFlagsSection<ELF32BE>;
1779template class elf::MipsAbiFlagsSection<ELF64LE>;
1780template class elf::MipsAbiFlagsSection<ELF64BE>;
1781
Simon Atanasyance02cf02016-11-09 21:36:56 +00001782template class elf::MipsOptionsSection<ELF32LE>;
1783template class elf::MipsOptionsSection<ELF32BE>;
1784template class elf::MipsOptionsSection<ELF64LE>;
1785template class elf::MipsOptionsSection<ELF64BE>;
1786
1787template class elf::MipsReginfoSection<ELF32LE>;
1788template class elf::MipsReginfoSection<ELF32BE>;
1789template class elf::MipsReginfoSection<ELF64LE>;
1790template class elf::MipsReginfoSection<ELF64BE>;
1791
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00001792template class elf::BuildIdSection<ELF32LE>;
1793template class elf::BuildIdSection<ELF32BE>;
1794template class elf::BuildIdSection<ELF64LE>;
1795template class elf::BuildIdSection<ELF64BE>;
1796
Eugene Leviantad4439e2016-11-11 11:33:32 +00001797template class elf::GotSection<ELF32LE>;
1798template class elf::GotSection<ELF32BE>;
1799template class elf::GotSection<ELF64LE>;
1800template class elf::GotSection<ELF64BE>;
1801
Simon Atanasyan725dc142016-11-16 21:01:02 +00001802template class elf::MipsGotSection<ELF32LE>;
1803template class elf::MipsGotSection<ELF32BE>;
1804template class elf::MipsGotSection<ELF64LE>;
1805template class elf::MipsGotSection<ELF64BE>;
1806
Eugene Leviant41ca3272016-11-10 09:48:29 +00001807template class elf::GotPltSection<ELF32LE>;
1808template class elf::GotPltSection<ELF32BE>;
1809template class elf::GotPltSection<ELF64LE>;
1810template class elf::GotPltSection<ELF64BE>;
Eugene Leviant22eb0262016-11-14 09:16:00 +00001811
Peter Smithbaffdb82016-12-08 12:58:55 +00001812template class elf::IgotPltSection<ELF32LE>;
1813template class elf::IgotPltSection<ELF32BE>;
1814template class elf::IgotPltSection<ELF64LE>;
1815template class elf::IgotPltSection<ELF64BE>;
1816
Eugene Leviant22eb0262016-11-14 09:16:00 +00001817template class elf::StringTableSection<ELF32LE>;
1818template class elf::StringTableSection<ELF32BE>;
1819template class elf::StringTableSection<ELF64LE>;
1820template class elf::StringTableSection<ELF64BE>;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001821
1822template class elf::DynamicSection<ELF32LE>;
1823template class elf::DynamicSection<ELF32BE>;
1824template class elf::DynamicSection<ELF64LE>;
1825template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00001826
1827template class elf::RelocationSection<ELF32LE>;
1828template class elf::RelocationSection<ELF32BE>;
1829template class elf::RelocationSection<ELF64LE>;
1830template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00001831
1832template class elf::SymbolTableSection<ELF32LE>;
1833template class elf::SymbolTableSection<ELF32BE>;
1834template class elf::SymbolTableSection<ELF64LE>;
1835template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001836
1837template class elf::GnuHashTableSection<ELF32LE>;
1838template class elf::GnuHashTableSection<ELF32BE>;
1839template class elf::GnuHashTableSection<ELF64LE>;
1840template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001841
1842template class elf::HashTableSection<ELF32LE>;
1843template class elf::HashTableSection<ELF32BE>;
1844template class elf::HashTableSection<ELF64LE>;
1845template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001846
1847template class elf::PltSection<ELF32LE>;
1848template class elf::PltSection<ELF32BE>;
1849template class elf::PltSection<ELF64LE>;
1850template class elf::PltSection<ELF64BE>;
Eugene Levianta113a412016-11-21 09:24:43 +00001851
Peter Smithbaffdb82016-12-08 12:58:55 +00001852template class elf::IpltSection<ELF32LE>;
1853template class elf::IpltSection<ELF32BE>;
1854template class elf::IpltSection<ELF64LE>;
1855template class elf::IpltSection<ELF64BE>;
1856
Eugene Levianta113a412016-11-21 09:24:43 +00001857template class elf::GdbIndexSection<ELF32LE>;
1858template class elf::GdbIndexSection<ELF32BE>;
1859template class elf::GdbIndexSection<ELF64LE>;
1860template class elf::GdbIndexSection<ELF64BE>;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001861
1862template class elf::EhFrameHeader<ELF32LE>;
1863template class elf::EhFrameHeader<ELF32BE>;
1864template class elf::EhFrameHeader<ELF64LE>;
1865template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001866
1867template class elf::VersionTableSection<ELF32LE>;
1868template class elf::VersionTableSection<ELF32BE>;
1869template class elf::VersionTableSection<ELF64LE>;
1870template class elf::VersionTableSection<ELF64BE>;
1871
1872template class elf::VersionNeedSection<ELF32LE>;
1873template class elf::VersionNeedSection<ELF32BE>;
1874template class elf::VersionNeedSection<ELF64LE>;
1875template class elf::VersionNeedSection<ELF64BE>;
1876
1877template class elf::VersionDefinitionSection<ELF32LE>;
1878template class elf::VersionDefinitionSection<ELF32BE>;
1879template class elf::VersionDefinitionSection<ELF64LE>;
1880template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00001881
Rui Ueyamabdfa1552016-11-22 19:24:52 +00001882template class elf::MipsRldMapSection<ELF32LE>;
1883template class elf::MipsRldMapSection<ELF32BE>;
1884template class elf::MipsRldMapSection<ELF64LE>;
1885template class elf::MipsRldMapSection<ELF64BE>;
Peter Smith719eb8e2016-11-24 11:43:55 +00001886
1887template class elf::ARMExidxSentinelSection<ELF32LE>;
1888template class elf::ARMExidxSentinelSection<ELF32BE>;
1889template class elf::ARMExidxSentinelSection<ELF64LE>;
1890template class elf::ARMExidxSentinelSection<ELF64BE>;