blob: 6810578a23022940d5ae3a1797396f4746df747c [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 Ueyama9381eb12016-12-18 14:06:06 +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 Ueyama3da3f062016-11-10 20:20:37 +000029#include "lld/Config/Version.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000030#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
31#include "llvm/Object/ELFObjectFile.h"
Eugene Leviant952eb4d2016-11-21 15:52:10 +000032#include "llvm/Support/Dwarf.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/MD5.h"
35#include "llvm/Support/RandomNumberGenerator.h"
36#include "llvm/Support/SHA1.h"
37#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000038#include <cstdlib>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000039
40using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000041using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000042using namespace llvm::ELF;
43using namespace llvm::object;
44using namespace llvm::support;
45using namespace llvm::support::endian;
46
47using namespace lld;
48using namespace lld::elf;
49
Rui Ueyama9320cb02017-02-27 02:56:02 +000050uint64_t SyntheticSection::getVA() const {
51 if (this->OutSec)
52 return this->OutSec->Addr + this->OutSecOff;
53 return 0;
54}
55
Rui Ueyamae8a61022016-11-05 23:05:47 +000056template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
57 std::vector<DefinedCommon *> V;
58 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
59 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
60 V.push_back(B);
61 return V;
62}
63
64// Find all common symbols and allocate space for them.
Rafael Espindola774ea7d2017-02-23 16:49:07 +000065template <class ELFT> InputSection *elf::createCommonSection() {
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000066 if (!Config->DefineCommon)
George Rimar176d6062017-03-17 13:31:07 +000067 return nullptr;
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000068
Rui Ueyamae8a61022016-11-05 23:05:47 +000069 // Sort the common symbols by alignment as an heuristic to pack them better.
70 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
George Rimar176d6062017-03-17 13:31:07 +000071 if (Syms.empty())
72 return nullptr;
73
Rui Ueyamae8a61022016-11-05 23:05:47 +000074 std::stable_sort(Syms.begin(), Syms.end(),
75 [](const DefinedCommon *A, const DefinedCommon *B) {
76 return A->Alignment > B->Alignment;
77 });
George Rimar176d6062017-03-17 13:31:07 +000078 BssSection *Ret = make<BssSection>("COMMON");
79 for (DefinedCommon *Sym : Syms)
80 Sym->Offset = Ret->reserveSpace(Sym->Alignment, Sym->Size);
Rui Ueyamae8a61022016-11-05 23:05:47 +000081
Rafael Espindola682a5bc2016-11-08 14:42:34 +000082 return Ret;
Rui Ueyamae8a61022016-11-05 23:05:47 +000083}
84
Rui Ueyama3da3f062016-11-10 20:20:37 +000085// Returns an LLD version string.
86static ArrayRef<uint8_t> getVersion() {
87 // Check LLD_VERSION first for ease of testing.
88 // You can get consitent output by using the environment variable.
89 // This is only for testing.
90 StringRef S = getenv("LLD_VERSION");
91 if (S.empty())
92 S = Saver.save(Twine("Linker: ") + getLLDVersion());
93
94 // +1 to include the terminating '\0'.
95 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000096}
Rui Ueyama3da3f062016-11-10 20:20:37 +000097
98// Creates a .comment section containing LLD version info.
99// With this feature, you can identify LLD-generated binaries easily
100// by "objdump -s -j .comment <file>".
101// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000102template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000103 typename ELFT::Shdr Hdr = {};
104 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
105 Hdr.sh_type = SHT_PROGBITS;
106 Hdr.sh_entsize = 1;
107 Hdr.sh_addralign = 1;
108
Rafael Espindola6119b862017-03-06 20:23:56 +0000109 auto *Ret =
110 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000111 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)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000119 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000120 Flags(Flags) {
121 this->Entsize = sizeof(Elf_Mips_ABIFlags);
122}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000123
124template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
125 memcpy(Buf, &Flags, sizeof(Flags));
126}
127
128template <class ELFT>
129MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
130 Elf_Mips_ABIFlags Flags = {};
131 bool Create = false;
132
Rui Ueyama536a2672017-02-27 02:32:08 +0000133 for (InputSectionBase *Sec : InputSections) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000134 if (!Sec->Live || Sec->Type != SHT_MIPS_ABIFLAGS)
135 continue;
136 Sec->Live = false;
137 Create = true;
138
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000139 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000140 const size_t Size = Sec->Data.size();
141 // Older version of BFD (such as the default FreeBSD linker) concatenate
142 // .MIPS.abiflags instead of merging. To allow for this case (or potential
143 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
144 if (Size < sizeof(Elf_Mips_ABIFlags)) {
145 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
146 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000147 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000148 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000149 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000150 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000151 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000152 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000153 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000154 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000155
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000156 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
157 // select the highest number of ISA/Rev/Ext.
158 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
159 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
160 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
161 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
162 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
163 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
164 Flags.ases |= S->ases;
165 Flags.flags1 |= S->flags1;
166 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000167 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000168 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000169
Rui Ueyama12f2da82016-11-22 03:57:06 +0000170 if (Create)
171 return make<MipsAbiFlagsSection<ELFT>>(Flags);
172 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000173}
174
Simon Atanasyance02cf02016-11-09 21:36:56 +0000175// .MIPS.options section.
176template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000177MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000178 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000179 Reginfo(Reginfo) {
180 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
181}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000182
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000183template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
184 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
185 Options->kind = ODK_REGINFO;
186 Options->size = getSize();
187
188 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000189 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000190 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000191}
192
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000193template <class ELFT>
194MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
195 // N64 ABI only.
196 if (!ELFT::Is64Bits)
197 return nullptr;
198
199 Elf_Mips_RegInfo Reginfo = {};
200 bool Create = false;
201
Rui Ueyama536a2672017-02-27 02:32:08 +0000202 for (InputSectionBase *Sec : InputSections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000203 if (!Sec->Live || Sec->Type != SHT_MIPS_OPTIONS)
204 continue;
205 Sec->Live = false;
206 Create = true;
207
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000208 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000209 ArrayRef<uint8_t> D = Sec->Data;
210
211 while (!D.empty()) {
212 if (D.size() < sizeof(Elf_Mips_Options)) {
213 error(Filename + ": invalid size of .MIPS.options section");
214 break;
215 }
216
217 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
218 if (Opt->kind == ODK_REGINFO) {
219 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
220 error(Filename + ": unsupported non-zero ri_gp_value");
221 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000222 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000223 break;
224 }
225
226 if (!Opt->size)
227 fatal(Filename + ": zero option descriptor size");
228 D = D.slice(Opt->size);
229 }
230 };
231
232 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000233 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000234 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000235}
236
237// MIPS .reginfo section.
238template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000239MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000240 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000241 Reginfo(Reginfo) {
242 this->Entsize = sizeof(Elf_Mips_RegInfo);
243}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000244
Rui Ueyamab71cae92016-11-22 03:57:08 +0000245template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000246 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000247 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000248 memcpy(Buf, &Reginfo, sizeof(Reginfo));
249}
250
251template <class ELFT>
252MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
253 // Section should be alive for O32 and N32 ABIs only.
254 if (ELFT::Is64Bits)
255 return nullptr;
256
257 Elf_Mips_RegInfo Reginfo = {};
258 bool Create = false;
259
Rui Ueyama536a2672017-02-27 02:32:08 +0000260 for (InputSectionBase *Sec : InputSections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000261 if (!Sec->Live || Sec->Type != SHT_MIPS_REGINFO)
262 continue;
263 Sec->Live = false;
264 Create = true;
265
266 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000267 error(toString(Sec->getFile<ELFT>()) +
268 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000269 return nullptr;
270 }
271 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
272 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000273 error(toString(Sec->getFile<ELFT>()) +
274 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000275
276 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000277 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000278 };
279
280 if (Create)
281 return make<MipsReginfoSection<ELFT>>(Reginfo);
282 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000283}
284
Rui Ueyama3255a522017-02-27 02:32:49 +0000285InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000286 // StringSaver guarantees that the returned string ends with '\0'.
287 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000288 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
289
290 auto *Sec =
291 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
292 Sec->Live = true;
293 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000294}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000295
Peter Smith96943762017-01-25 10:31:16 +0000296template <class ELFT>
Rui Ueyama65316d72017-02-23 03:15:57 +0000297SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
298 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000299 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
300 Value, Size, Section, nullptr);
Peter Smith96943762017-01-25 10:31:16 +0000301 if (In<ELFT>::SymTab)
Rui Ueyamab8dcdb52017-02-28 04:20:16 +0000302 In<ELFT>::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000303 return S;
304}
305
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000306static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000307 switch (Config->BuildId) {
308 case BuildIdKind::Fast:
309 return 8;
310 case BuildIdKind::Md5:
311 case BuildIdKind::Uuid:
312 return 16;
313 case BuildIdKind::Sha1:
314 return 20;
315 case BuildIdKind::Hexstring:
316 return Config->BuildIdVector.size();
317 default:
318 llvm_unreachable("unknown BuildIdKind");
319 }
320}
321
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000322template <class ELFT>
323BuildIdSection<ELFT>::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000324 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000325 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000326
327template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
328 const endianness E = ELFT::TargetEndianness;
329 write32<E>(Buf, 4); // Name size
330 write32<E>(Buf + 4, HashSize); // Content size
331 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
332 memcpy(Buf + 12, "GNU", 4); // Name string
333 HashBuf = Buf + 16;
334}
335
Rui Ueyama35e00752016-11-10 00:12:28 +0000336// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000337static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
338 size_t ChunkSize) {
339 std::vector<ArrayRef<uint8_t>> Ret;
340 while (Arr.size() > ChunkSize) {
341 Ret.push_back(Arr.take_front(ChunkSize));
342 Arr = Arr.drop_front(ChunkSize);
343 }
344 if (!Arr.empty())
345 Ret.push_back(Arr);
346 return Ret;
347}
348
Rui Ueyama35e00752016-11-10 00:12:28 +0000349// Computes a hash value of Data using a given hash function.
350// In order to utilize multiple cores, we first split data into 1MB
351// chunks, compute a hash for each chunk, and then compute a hash value
352// of the hash values.
George Rimar364b59e22016-11-06 07:42:55 +0000353template <class ELFT>
354void BuildIdSection<ELFT>::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000355 llvm::ArrayRef<uint8_t> Data,
356 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000357 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000358 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000359
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000360 // Compute hash values.
Rui Ueyama244a4352016-12-03 21:24:51 +0000361 forLoop(0, Chunks.size(),
362 [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); });
Rui Ueyama35e00752016-11-10 00:12:28 +0000363
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000364 // Write to the final output buffer.
365 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000366}
367
George Rimar1ab9cf42017-03-17 10:14:53 +0000368BssSection::BssSection(StringRef Name)
369 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
370
371size_t BssSection::reserveSpace(uint32_t Alignment, size_t Size) {
George Rimar176d6062017-03-17 13:31:07 +0000372 if (OutSec)
373 OutSec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000374 this->Size = alignTo(this->Size, Alignment) + Size;
375 this->Alignment = std::max<uint32_t>(this->Alignment, Alignment);
376 return this->Size - Size;
377}
Peter Smithebfe9942017-02-09 10:27:57 +0000378
379template <class ELFT>
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000380void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000381 switch (Config->BuildId) {
382 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000383 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000384 write64le(Dest, xxHash64(toStringRef(Arr)));
385 });
386 break;
387 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000388 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000389 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000390 });
391 break;
392 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000393 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000394 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000395 });
396 break;
397 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000398 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000399 error("entropy source failure");
400 break;
401 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000402 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000403 break;
404 default:
405 llvm_unreachable("unknown BuildIdKind");
406 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000407}
408
Eugene Leviant41ca3272016-11-10 09:48:29 +0000409template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000410EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000411 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000412
413// Search for an existing CIE record or create a new one.
414// CIE records from input object files are uniquified by their contents
415// and where their relocations point to.
416template <class ELFT>
417template <class RelTy>
418CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
419 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000420 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000421 const endianness E = ELFT::TargetEndianness;
422 if (read32<E>(Piece.data().data() + 4) != 0)
423 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
424
425 SymbolBody *Personality = nullptr;
426 unsigned FirstRelI = Piece.FirstRelocation;
427 if (FirstRelI != (unsigned)-1)
428 Personality =
429 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
430
431 // Search for an existing CIE by CIE contents/relocation target pair.
432 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
433
434 // If not found, create a new one.
435 if (Cie->Piece == nullptr) {
436 Cie->Piece = &Piece;
437 Cies.push_back(Cie);
438 }
439 return Cie;
440}
441
442// There is one FDE per function. Returns true if a given FDE
443// points to a live function.
444template <class ELFT>
445template <class RelTy>
446bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
447 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000448 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000449 unsigned FirstRelI = Piece.FirstRelocation;
450 if (FirstRelI == (unsigned)-1)
451 return false;
452 const RelTy &Rel = Rels[FirstRelI];
453 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000454 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000455 if (!D || !D->Section)
456 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000457 auto *Target =
458 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000459 return Target && Target->Live;
460}
461
462// .eh_frame is a sequence of CIE or FDE records. In general, there
463// is one CIE record per input object file which is followed by
464// a list of FDEs. This function searches an existing CIE or create a new
465// one and associates FDEs to the CIE.
466template <class ELFT>
467template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000468void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000469 ArrayRef<RelTy> Rels) {
470 const endianness E = ELFT::TargetEndianness;
471
472 DenseMap<size_t, CieRecord *> OffsetToCie;
473 for (EhSectionPiece &Piece : Sec->Pieces) {
474 // The empty record is the end marker.
475 if (Piece.size() == 4)
476 return;
477
478 size_t Offset = Piece.InputOff;
479 uint32_t ID = read32<E>(Piece.data().data() + 4);
480 if (ID == 0) {
481 OffsetToCie[Offset] = addCie(Piece, Rels);
482 continue;
483 }
484
485 uint32_t CieOffset = Offset + 4 - ID;
486 CieRecord *Cie = OffsetToCie[CieOffset];
487 if (!Cie)
488 fatal(toString(Sec) + ": invalid CIE reference");
489
490 if (!isFdeLive(Piece, Rels))
491 continue;
492 Cie->FdePieces.push_back(&Piece);
493 NumFdes++;
494 }
495}
496
497template <class ELFT>
498void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000499 auto *Sec = cast<EhInputSection>(C);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000500 Sec->EHSec = this;
501 updateAlignment(Sec->Alignment);
502 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000503 for (auto *DS : Sec->DependentSections)
504 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000505
506 // .eh_frame is a sequence of CIE or FDE records. This function
507 // splits it into pieces so that we can call
508 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000509 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000510 if (Sec->Pieces.empty())
511 return;
512
513 if (Sec->NumRelocations) {
514 if (Sec->AreRelocsRela)
515 addSectionAux(Sec, Sec->template relas<ELFT>());
516 else
517 addSectionAux(Sec, Sec->template rels<ELFT>());
518 return;
519 }
520 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
521}
522
523template <class ELFT>
524static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
525 memcpy(Buf, D.data(), D.size());
526
527 // Fix the size field. -4 since size does not include the size field itself.
528 const endianness E = ELFT::TargetEndianness;
529 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
530}
531
Rui Ueyama945055a2017-02-27 03:07:41 +0000532template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000533 if (this->Size)
534 return; // Already finalized.
535
536 size_t Off = 0;
537 for (CieRecord *Cie : Cies) {
538 Cie->Piece->OutputOff = Off;
539 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
540
541 for (EhSectionPiece *Fde : Cie->FdePieces) {
542 Fde->OutputOff = Off;
543 Off += alignTo(Fde->size(), sizeof(uintX_t));
544 }
545 }
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000546 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000547}
548
549template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
550 const endianness E = ELFT::TargetEndianness;
551 switch (Size) {
552 case DW_EH_PE_udata2:
553 return read16<E>(Buf);
554 case DW_EH_PE_udata4:
555 return read32<E>(Buf);
556 case DW_EH_PE_udata8:
557 return read64<E>(Buf);
558 case DW_EH_PE_absptr:
559 if (ELFT::Is64Bits)
560 return read64<E>(Buf);
561 return read32<E>(Buf);
562 }
563 fatal("unknown FDE size encoding");
564}
565
566// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
567// We need it to create .eh_frame_hdr section.
568template <class ELFT>
569typename ELFT::uint EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
570 uint8_t Enc) {
571 // The starting address to which this FDE applies is
572 // stored at FDE + 8 byte.
573 size_t Off = FdeOff + 8;
574 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
575 if ((Enc & 0x70) == DW_EH_PE_absptr)
576 return Addr;
577 if ((Enc & 0x70) == DW_EH_PE_pcrel)
578 return Addr + this->OutSec->Addr + Off;
579 fatal("unknown FDE size relative encoding");
580}
581
582template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
583 const endianness E = ELFT::TargetEndianness;
584 for (CieRecord *Cie : Cies) {
585 size_t CieOffset = Cie->Piece->OutputOff;
586 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
587
588 for (EhSectionPiece *Fde : Cie->FdePieces) {
589 size_t Off = Fde->OutputOff;
590 writeCieFde<ELFT>(Buf + Off, Fde->data());
591
592 // FDE's second word should have the offset to an associated CIE.
593 // Write it.
594 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
595 }
596 }
597
Rafael Espindola5c02b742017-03-06 21:17:18 +0000598 for (EhInputSection *S : Sections)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000599 S->template relocate<ELFT>(Buf, nullptr);
600
601 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
602 // to get a FDE from an address to which FDE is applied. So here
603 // we obtain two addresses and pass them to EhFrameHdr object.
604 if (In<ELFT>::EhFrameHdr) {
605 for (CieRecord *Cie : Cies) {
606 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
607 for (SectionPiece *Fde : Cie->FdePieces) {
608 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
609 uintX_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
610 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
611 }
612 }
613 }
614}
615
616template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000617GotSection<ELFT>::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000618 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
619 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000620
621template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000622 Sym.GotIndex = NumEntries;
623 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000624}
625
Simon Atanasyan725dc142016-11-16 21:01:02 +0000626template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
627 if (Sym.GlobalDynIndex != -1U)
628 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000629 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000630 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000631 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000632 return true;
633}
634
635// Reserves TLS entries for a TLS module ID and a TLS block offset.
636// In total it takes two GOT slots.
637template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
638 if (TlsIndexOff != uint32_t(-1))
639 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000640 TlsIndexOff = NumEntries * sizeof(uintX_t);
641 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000642 return true;
643}
644
Eugene Leviantad4439e2016-11-11 11:33:32 +0000645template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000646typename GotSection<ELFT>::uintX_t
647GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
648 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
649}
650
651template <class ELFT>
652typename GotSection<ELFT>::uintX_t
653GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
654 return B.GlobalDynIndex * sizeof(uintX_t);
655}
656
Rui Ueyama945055a2017-02-27 03:07:41 +0000657template <class ELFT> void GotSection<ELFT>::finalizeContents() {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000658 Size = NumEntries * sizeof(uintX_t);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000659}
660
George Rimar11992c862016-11-25 08:05:41 +0000661template <class ELFT> bool GotSection<ELFT>::empty() const {
662 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
663 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000664 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000665}
666
Simon Atanasyan725dc142016-11-16 21:01:02 +0000667template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000668 this->template relocate<ELFT>(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000669}
670
671template <class ELFT>
672MipsGotSection<ELFT>::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000673 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
674 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000675
676template <class ELFT>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000677void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, int64_t Addend,
Eugene Leviantad4439e2016-11-11 11:33:32 +0000678 RelExpr Expr) {
679 // For "true" local symbols which can be referenced from the same module
680 // only compiler creates two instructions for address loading:
681 //
682 // lw $8, 0($gp) # R_MIPS_GOT16
683 // addi $8, $8, 0 # R_MIPS_LO16
684 //
685 // The first instruction loads high 16 bits of the symbol address while
686 // the second adds an offset. That allows to reduce number of required
687 // GOT entries because only one global offset table entry is necessary
688 // for every 64 KBytes of local data. So for local symbols we need to
689 // allocate number of GOT entries to hold all required "page" addresses.
690 //
691 // All global symbols (hidden and regular) considered by compiler uniformly.
692 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
693 // to load address of the symbol. So for each such symbol we need to
694 // allocate dedicated GOT entry to store its address.
695 //
696 // If a symbol is preemptible we need help of dynamic linker to get its
697 // final address. The corresponding GOT entries are allocated in the
698 // "global" part of GOT. Entries for non preemptible global symbol allocated
699 // in the "local" part of GOT.
700 //
701 // See "Global Offset Table" in Chapter 5:
702 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
703 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
704 // At this point we do not know final symbol value so to reduce number
705 // of allocated GOT entries do the following trick. Save all output
706 // sections referenced by GOT relocations. Then later in the `finalize`
707 // method calculate number of "pages" required to cover all saved output
708 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000709 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000710 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000711 return;
712 }
713 if (Sym.isTls()) {
714 // GOT entries created for MIPS TLS relocations behave like
715 // almost GOT entries from other ABIs. They go to the end
716 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000717 Sym.GotIndex = TlsEntries.size();
718 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000719 return;
720 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000721 auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000722 if (S.isInGot() && !A)
723 return;
724 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000725 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 return;
727 Items.emplace_back(&S, A);
728 if (!A)
729 S.GotIndex = NewIndex;
730 };
731 if (Sym.isPreemptible()) {
732 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000733 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000734 Sym.IsInGlobalMipsGot = true;
735 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000736 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000737 Sym.Is32BitMipsGot = true;
738 } else {
739 // Hold local GOT entries accessed via a 16-bit index separately.
740 // That allows to write them in the beginning of the GOT and keep
741 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000742 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000743 }
744}
745
George Rimar879a6572016-12-15 15:38:58 +0000746template <class ELFT>
747bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000748 if (Sym.GlobalDynIndex != -1U)
749 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000750 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000751 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000752 TlsEntries.push_back(nullptr);
753 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000754 return true;
755}
756
757// Reserves TLS entries for a TLS module ID and a TLS block offset.
758// In total it takes two GOT slots.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000759template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000760 if (TlsIndexOff != uint32_t(-1))
761 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000762 TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
763 TlsEntries.push_back(nullptr);
764 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000765 return true;
766}
767
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000768static uint64_t getMipsPageAddr(uint64_t Addr) {
769 return (Addr + 0x8000) & ~0xffff;
770}
771
772static uint64_t getMipsPageCount(uint64_t Size) {
773 return (Size + 0xfffe) / 0xffff + 1;
774}
775
Eugene Leviantad4439e2016-11-11 11:33:32 +0000776template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000777typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000778MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000779 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000780 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000781 cast<DefinedRegular>(&B)->Section->getOutputSection();
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000782 uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
George Rimarf64618a2017-03-17 11:56:54 +0000783 uintX_t SymAddr = getMipsPageAddr(B.getVA(Addend));
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000784 uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
785 assert(Index < PageEntriesNum);
786 return (HeaderEntriesNum + Index) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000787}
788
789template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000790typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000791MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000792 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000793 // Calculate offset of the GOT entries block: TLS, global, local.
Simon Atanasyana0efc422016-11-29 10:23:50 +0000794 uintX_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000795 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000796 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000797 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000798 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000799 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000800 Index += LocalEntries.size();
801 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000802 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000803 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000805 auto It = EntryIndexMap.find({&B, Addend});
806 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000807 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000808 }
Simon Atanasyana0efc422016-11-29 10:23:50 +0000809 return Index * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000810}
811
812template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000813typename MipsGotSection<ELFT>::uintX_t
814MipsGotSection<ELFT>::getTlsOffset() const {
815 return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000816}
817
818template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000819typename MipsGotSection<ELFT>::uintX_t
820MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000821 return B.GlobalDynIndex * sizeof(uintX_t);
822}
823
824template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000825const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
826 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000827}
828
829template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000830unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000831 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
832 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000833}
834
Rui Ueyama945055a2017-02-27 03:07:41 +0000835template <class ELFT> void MipsGotSection<ELFT>::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000836 updateAllocSize();
837}
838
839template <class ELFT> void MipsGotSection<ELFT>::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000840 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000841 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000842 // For each output section referenced by GOT page relocations calculate
843 // and save into PageIndexMap an upper bound of MIPS GOT entries required
844 // to store page addresses of local symbols. We assume the worst case -
845 // each 64kb page of the output section has at least one GOT relocation
846 // against it. And take in account the case when the section intersects
847 // page boundaries.
848 P.second = PageEntriesNum;
849 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000850 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000851 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
852 sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000853}
854
George Rimar11992c862016-11-25 08:05:41 +0000855template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
856 // We add the .got section to the result for dynamic MIPS target because
857 // its address and properties are mentioned in the .dynamic section.
858 return Config->Relocatable;
859}
860
Simon Atanasyanb9666652016-12-12 14:30:18 +0000861template <class ELFT>
862typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000863 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000864}
865
Eugene Leviantad4439e2016-11-11 11:33:32 +0000866template <class ELFT>
867static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
868 typedef typename ELFT::uint uintX_t;
869 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
870}
871
Simon Atanasyan725dc142016-11-16 21:01:02 +0000872template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000873 // Set the MSB of the second GOT slot. This is not required by any
874 // MIPS ABI documentation, though.
875 //
876 // There is a comment in glibc saying that "The MSB of got[1] of a
877 // gnu object is set to identify gnu objects," and in GNU gold it
878 // says "the second entry will be used by some runtime loaders".
879 // But how this field is being used is unclear.
880 //
881 // We are not really willing to mimic other linkers behaviors
882 // without understanding why they do that, but because all files
883 // generated by GNU tools have this special GOT value, and because
884 // we've been doing this for years, it is probably a safe bet to
885 // keep doing this for now. We really need to revisit this to see
886 // if we had to do this.
887 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
888 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
Simon Atanasyana0efc422016-11-29 10:23:50 +0000889 Buf += HeaderEntriesNum * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000890 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000891 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000892 size_t PageCount = getMipsPageCount(L.first->Size);
893 uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
894 for (size_t PI = 0; PI < PageCount; ++PI) {
895 uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
896 writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
897 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000898 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000899 Buf += PageEntriesNum * sizeof(uintX_t);
900 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000901 uint8_t *Entry = Buf;
902 Buf += sizeof(uintX_t);
903 const SymbolBody *Body = SA.first;
George Rimarf64618a2017-03-17 11:56:54 +0000904 uintX_t VA = Body->getVA(SA.second);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000905 writeUint<ELFT>(Entry, VA);
906 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000907 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
908 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
909 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000910 // Initialize TLS-related GOT entries. If the entry has a corresponding
911 // dynamic relocations, leave it initialized by zero. Write down adjusted
912 // TLS symbol's values otherwise. To calculate the adjustments use offsets
913 // for thread-local storage.
914 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyama104e2352017-02-14 05:45:47 +0000915 if (TlsIndexOff != -1U && !Config->pic())
Eugene Leviantad4439e2016-11-11 11:33:32 +0000916 writeUint<ELFT>(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000917 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000918 if (!B || B->isPreemptible())
919 continue;
George Rimarf64618a2017-03-17 11:56:54 +0000920 uintX_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000921 if (B->GotIndex != -1U) {
922 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
923 writeUint<ELFT>(Entry, VA - 0x7000);
924 }
925 if (B->GlobalDynIndex != -1U) {
926 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
927 writeUint<ELFT>(Entry, 1);
928 Entry += sizeof(uintX_t);
929 writeUint<ELFT>(Entry, VA - 0x8000);
930 }
931 }
932}
933
George Rimar10f74fc2017-03-15 09:12:56 +0000934GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000935 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
936 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000937
George Rimar10f74fc2017-03-15 09:12:56 +0000938void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000939 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
940 Entries.push_back(&Sym);
941}
942
George Rimar10f74fc2017-03-15 09:12:56 +0000943size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000944 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
945 Target->GotPltEntrySize;
946}
947
George Rimar10f74fc2017-03-15 09:12:56 +0000948void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000949 Target->writeGotPltHeader(Buf);
950 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
951 for (const SymbolBody *B : Entries) {
952 Target->writeGotPlt(Buf, *B);
George Rimar7385d432017-03-16 13:41:29 +0000953 Buf += Config->is64() ? 8 : 4;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000954 }
955}
956
Peter Smithbaffdb82016-12-08 12:58:55 +0000957// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
958// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000959IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000960 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
961 Target->GotPltEntrySize,
962 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000963
George Rimar10f74fc2017-03-15 09:12:56 +0000964void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000965 Sym.IsInIgot = true;
966 Sym.GotPltIndex = Entries.size();
967 Entries.push_back(&Sym);
968}
969
George Rimar10f74fc2017-03-15 09:12:56 +0000970size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000971 return Entries.size() * Target->GotPltEntrySize;
972}
973
George Rimar10f74fc2017-03-15 09:12:56 +0000974void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000975 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000976 Target->writeIgotPlt(Buf, *B);
George Rimar7385d432017-03-16 13:41:29 +0000977 Buf += Config->is64() ? 8 : 4;
Peter Smithbaffdb82016-12-08 12:58:55 +0000978 }
979}
980
George Rimar49648002017-03-15 09:32:36 +0000981StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
982 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000983 Dynamic(Dynamic) {
984 // ELF string tables start with a NUL byte.
985 addString("");
986}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000987
988// Adds a string to the string table. If HashIt is true we hash and check for
989// duplicates. It is optional because the name of global symbols are already
990// uniqued and hashing them again has a big cost for a small value: uniquing
991// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000992unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000993 if (HashIt) {
994 auto R = StringMap.insert(std::make_pair(S, this->Size));
995 if (!R.second)
996 return R.first->second;
997 }
998 unsigned Ret = this->Size;
999 this->Size = this->Size + S.size() + 1;
1000 Strings.push_back(S);
1001 return Ret;
1002}
1003
George Rimar49648002017-03-15 09:32:36 +00001004void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001005 for (StringRef S : Strings) {
1006 memcpy(Buf, S.data(), S.size());
1007 Buf += S.size() + 1;
1008 }
1009}
1010
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001011// Returns the number of version definition entries. Because the first entry
1012// is for the version definition itself, it is the number of versioned symbols
1013// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001014static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1015
1016template <class ELFT>
1017DynamicSection<ELFT>::DynamicSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001018 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, sizeof(uintX_t),
1019 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001020 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001021
Eugene Leviant6380ce22016-11-15 12:26:55 +00001022 // .dynamic section is not writable on MIPS.
1023 // See "Special Section" in Chapter 4 in the following document:
1024 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1025 if (Config->EMachine == EM_MIPS)
1026 this->Flags = SHF_ALLOC;
1027
1028 addEntries();
1029}
1030
1031// There are some dynamic entries that don't depend on other sections.
1032// Such entries can be set early.
1033template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1034 // Add strings to .dynstr early so that .dynstr's size will be
1035 // fixed early.
1036 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +00001037 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001038 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001039 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001040 In<ELFT>::DynStrTab->addString(Config->RPath)});
1041 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1042 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +00001043 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001044 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001045 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001046
1047 // Set DT_FLAGS and DT_FLAGS_1.
1048 uint32_t DtFlags = 0;
1049 uint32_t DtFlags1 = 0;
1050 if (Config->Bsymbolic)
1051 DtFlags |= DF_SYMBOLIC;
1052 if (Config->ZNodelete)
1053 DtFlags1 |= DF_1_NODELETE;
1054 if (Config->ZNow) {
1055 DtFlags |= DF_BIND_NOW;
1056 DtFlags1 |= DF_1_NOW;
1057 }
1058 if (Config->ZOrigin) {
1059 DtFlags |= DF_ORIGIN;
1060 DtFlags1 |= DF_1_ORIGIN;
1061 }
1062
1063 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001064 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001065 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001066 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001067
Petr Hosek668bebe2016-12-07 02:05:42 +00001068 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +00001069 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001070}
1071
1072// Add remaining entries to complete .dynamic contents.
Rui Ueyama945055a2017-02-27 03:07:41 +00001073template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001074 if (this->Size)
1075 return; // Already finalized.
1076
1077 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001078 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001079 bool IsRela = Config->isRela();
Rui Ueyama729ac792016-11-17 04:10:09 +00001080 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001081 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001082 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001083 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1084
1085 // MIPS dynamic loader does not support RELCOUNT tag.
1086 // The problem is in the tight relation between dynamic
1087 // relocations and GOT. So do not emit this tag on MIPS.
1088 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001089 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001090 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001091 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001092 }
1093 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001094 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001095 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001096 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001097 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001098 In<ELFT>::GotPlt});
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001099 add({DT_PLTREL, uint64_t(Config->isRela() ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001100 }
1101
Eugene Leviant9230db92016-11-17 09:16:34 +00001102 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001103 add({DT_SYMENT, sizeof(Elf_Sym)});
1104 add({DT_STRTAB, In<ELFT>::DynStrTab});
1105 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001106 if (!Config->ZText)
1107 add({DT_TEXTREL, (uint64_t)0});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001108 if (In<ELFT>::GnuHashTab)
1109 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001110 if (In<ELFT>::HashTab)
1111 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001112
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001113 if (Out::PreinitArray) {
1114 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1115 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001116 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001117 if (Out::InitArray) {
1118 add({DT_INIT_ARRAY, Out::InitArray});
1119 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001120 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001121 if (Out::FiniArray) {
1122 add({DT_FINI_ARRAY, Out::FiniArray});
1123 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001124 }
1125
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001126 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001127 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001128 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001129 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001130
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001131 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1132 if (HasVerNeed || In<ELFT>::VerDef)
1133 add({DT_VERSYM, In<ELFT>::VerSym});
1134 if (In<ELFT>::VerDef) {
1135 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001136 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001137 }
1138 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001139 add({DT_VERNEED, In<ELFT>::VerNeed});
1140 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001141 }
1142
1143 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001144 add({DT_MIPS_RLD_VERSION, 1});
1145 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1146 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +00001147 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001148 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1149 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001150 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001151 else
Eugene Leviant9230db92016-11-17 09:16:34 +00001152 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +00001153 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +00001154 if (In<ELFT>::MipsRldMap)
1155 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001156 }
1157
Eugene Leviant6380ce22016-11-15 12:26:55 +00001158 this->OutSec->Link = this->Link;
1159
1160 // +1 for DT_NULL
1161 this->Size = (Entries.size() + 1) * this->Entsize;
1162}
1163
1164template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1165 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1166
1167 for (const Entry &E : Entries) {
1168 P->d_tag = E.Tag;
1169 switch (E.Kind) {
1170 case Entry::SecAddr:
1171 P->d_un.d_ptr = E.OutSec->Addr;
1172 break;
1173 case Entry::InSecAddr:
1174 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1175 break;
1176 case Entry::SecSize:
1177 P->d_un.d_val = E.OutSec->Size;
1178 break;
1179 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001180 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001181 break;
1182 case Entry::PlainInt:
1183 P->d_un.d_val = E.Val;
1184 break;
1185 }
1186 ++P;
1187 }
1188}
1189
George Rimar97def8c2017-03-17 12:07:44 +00001190uint64_t DynamicReloc::getOffset() const {
Rafael Espindolae1294092017-03-08 16:03:41 +00001191 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001192}
1193
George Rimar97def8c2017-03-17 12:07:44 +00001194int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001195 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001196 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001197 return Addend;
1198}
1199
George Rimar97def8c2017-03-17 12:07:44 +00001200uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001201 if (Sym && !UseSymVA)
1202 return Sym->DynsymIndex;
1203 return 0;
1204}
1205
1206template <class ELFT>
1207RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001208 : SyntheticSection(SHF_ALLOC, Config->isRela() ? SHT_RELA : SHT_REL,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001209 sizeof(uintX_t), Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001210 Sort(Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001211 this->Entsize = Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001212}
1213
1214template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001215void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001216 if (Reloc.Type == Target->RelativeRel)
1217 ++NumRelativeRelocs;
1218 Relocs.push_back(Reloc);
1219}
1220
1221template <class ELFT, class RelTy>
1222static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001223 bool AIsRel = A.getType(Config->isMips64EL()) == Target->RelativeRel;
1224 bool BIsRel = B.getType(Config->isMips64EL()) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001225 if (AIsRel != BIsRel)
1226 return AIsRel;
1227
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001228 return A.getSymbol(Config->isMips64EL()) < B.getSymbol(Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001229}
1230
1231template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1232 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001233 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001234 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001235 Buf += Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001236
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001237 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001238 P->r_addend = Rel.getAddend();
1239 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001240 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001241 // Dynamic relocation against MIPS GOT section make deal TLS entries
1242 // allocated in the end of the GOT. We need to adjust the offset to take
1243 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001244 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001245 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001246 }
1247
1248 if (Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001249 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001250 std::stable_sort((Elf_Rela *)BufBegin,
1251 (Elf_Rela *)BufBegin + Relocs.size(),
1252 compRelocations<ELFT, Elf_Rela>);
1253 else
1254 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1255 compRelocations<ELFT, Elf_Rel>);
1256 }
1257}
1258
1259template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1260 return this->Entsize * Relocs.size();
1261}
1262
Rui Ueyama945055a2017-02-27 03:07:41 +00001263template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001264 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1265 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001266
1267 // Set required output section properties.
1268 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001269}
1270
Eugene Leviant9230db92016-11-17 09:16:34 +00001271template <class ELFT>
George Rimar49648002017-03-15 09:32:36 +00001272SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001273 : SyntheticSection(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1274 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1275 sizeof(uintX_t),
1276 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
Eugene Leviant9230db92016-11-17 09:16:34 +00001277 StrTabSec(StrTabSec) {
1278 this->Entsize = sizeof(Elf_Sym);
1279}
1280
1281// Orders symbols according to their positions in the GOT,
1282// in compliance with MIPS ABI rules.
1283// See "Global Offset Table" in Chapter 5 in the following document
1284// for detailed description:
1285// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001286static bool sortMipsSymbols(const SymbolTableEntry &L, const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001287 // Sort entries related to non-local preemptible symbols by GOT indexes.
1288 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001289 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1290 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001291 if (LIsInLocalGot || RIsInLocalGot)
1292 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001293 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001294}
1295
Rui Ueyamabb07d102017-02-27 03:31:19 +00001296// Finalize a symbol table. The ELF spec requires that all local
1297// symbols precede global symbols, so we sort symbol entries in this
1298// function. (For .dynsym, we don't do that because symbols for
1299// dynamic linking are inherently all globals.)
Rui Ueyama945055a2017-02-27 03:07:41 +00001300template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001301 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001302
Rui Ueyama6e967342017-02-28 03:29:12 +00001303 // If it is a .dynsym, there should be no local symbols, but we need
1304 // to do a few things for the dynamic linker.
1305 if (this->Type == SHT_DYNSYM) {
1306 // Section's Info field has the index of the first non-local symbol.
1307 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001308 this->OutSec->Info = 1;
1309
1310 if (In<ELFT>::GnuHashTab) {
1311 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1312 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1313 } else if (Config->EMachine == EM_MIPS) {
1314 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1315 }
1316
1317 size_t I = 0;
1318 for (const SymbolTableEntry &S : Symbols)
1319 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001320 return;
Peter Smith55865432017-02-20 11:12:33 +00001321 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001322}
Peter Smith55865432017-02-20 11:12:33 +00001323
Peter Smith1ec42d92017-03-08 14:06:24 +00001324template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1325 if (this->Type == SHT_DYNSYM)
1326 return;
1327 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001328 auto It = std::stable_partition(
1329 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1330 return S.Symbol->isLocal() ||
1331 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1332 });
1333 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001334 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001335}
1336
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001337template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1338 // Adding a local symbol to a .dynsym is a bug.
1339 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001340
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001341 bool HashIt = B->isLocal();
1342 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001343}
1344
1345template <class ELFT>
1346size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001347 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1348 if (E.Symbol == Body)
1349 return true;
1350 // This is used for -r, so we have to handle multiple section
1351 // symbols being combined.
1352 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001353 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1354 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001355 return false;
1356 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001357 if (I == Symbols.end())
1358 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001359 return I - Symbols.begin() + 1;
1360}
1361
Rui Ueyama1f032532017-02-28 01:56:36 +00001362// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001363template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001364 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001365 Buf += sizeof(Elf_Sym);
1366
Eugene Leviant9230db92016-11-17 09:16:34 +00001367 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001368
Rui Ueyama1f032532017-02-28 01:56:36 +00001369 for (SymbolTableEntry &Ent : Symbols) {
1370 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001371
Rui Ueyama1b003182017-02-28 19:22:09 +00001372 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001373 if (Body->isLocal()) {
1374 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1375 } else {
1376 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1377 ESym->setVisibility(Body->symbol()->Visibility);
1378 }
1379
1380 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001381 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001382
Rui Ueyama1b003182017-02-28 19:22:09 +00001383 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001384 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001385 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001386 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001387 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001388 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001389 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001390
1391 // st_value is usually an address of a symbol, but that has a
1392 // special meaining for uninstantiated common symbols (this can
1393 // occur if -r is given).
1394 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001395 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001396 else
George Rimarf64618a2017-03-17 11:56:54 +00001397 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001398
Rui Ueyama1f032532017-02-28 01:56:36 +00001399 ++ESym;
1400 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001401
Rui Ueyama1f032532017-02-28 01:56:36 +00001402 // On MIPS we need to mark symbol which has a PLT entry and requires
1403 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1404 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1405 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1406 if (Config->EMachine == EM_MIPS) {
1407 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1408
1409 for (SymbolTableEntry &Ent : Symbols) {
1410 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001411 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001412 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001413
1414 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001415 if (auto *D = dyn_cast<DefinedRegular>(Body))
1416 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001417 ESym->st_other |= STO_MIPS_PIC;
1418 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001419 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001420 }
1421}
1422
Rui Ueyamae4120632017-02-28 22:05:13 +00001423// .hash and .gnu.hash sections contain on-disk hash tables that map
1424// symbol names to their dynamic symbol table indices. Their purpose
1425// is to help the dynamic linker resolve symbols quickly. If ELF files
1426// don't have them, the dynamic linker has to do linear search on all
1427// dynamic symbols, which makes programs slower. Therefore, a .hash
1428// section is added to a DSO by default. A .gnu.hash is added if you
1429// give the -hash-style=gnu or -hash-style=both option.
1430//
1431// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1432// Each ELF file has a list of DSOs that the ELF file depends on and a
1433// list of dynamic symbols that need to be resolved from any of the
1434// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1435// where m is the number of DSOs and n is the number of dynamic
1436// symbols. For modern large programs, both m and n are large. So
1437// making each step faster by using hash tables substiantially
1438// improves time to load programs.
1439//
1440// (Note that this is not the only way to design the shared library.
1441// For instance, the Windows DLL takes a different approach. On
1442// Windows, each dynamic symbol has a name of DLL from which the symbol
1443// has to be resolved. That makes the cost of symbol resolution O(n).
1444// This disables some hacky techniques you can use on Unix such as
1445// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1446//
1447// Due to historical reasons, we have two different hash tables, .hash
1448// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1449// and better version of .hash. .hash is just an on-disk hash table, but
1450// .gnu.hash has a bloom filter in addition to a hash table to skip
1451// DSOs very quickly. If you are sure that your dynamic linker knows
1452// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1453// safe bet is to specify -hash-style=both for backward compatibilty.
Eugene Leviant9230db92016-11-17 09:16:34 +00001454template <class ELFT>
Eugene Leviantbe809a72016-11-18 06:44:18 +00001455GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001456 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t), ".gnu.hash") {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001457 this->Entsize = ELFT::Is64Bits ? 0 : 4;
1458}
1459
Rui Ueyama945055a2017-02-27 03:07:41 +00001460template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001461 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001462
1463 // Computes bloom filter size in word size. We want to allocate 8
1464 // bits for each symbol. It must be a power of two.
1465 if (Symbols.empty())
1466 MaskWords = 1;
1467 else
1468 MaskWords = NextPowerOf2((Symbols.size() - 1) / sizeof(uintX_t));
1469
1470 Size = 16; // Header
1471 Size += sizeof(uintX_t) * MaskWords; // Bloom filter
1472 Size += NBuckets * 4; // Hash buckets
1473 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001474}
1475
1476template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001477 // Write a header.
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001478 const endianness E = ELFT::TargetEndianness;
1479 write32<E>(Buf, NBuckets);
1480 write32<E>(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size());
1481 write32<E>(Buf + 8, MaskWords);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001482 write32<E>(Buf + 12, getShift2());
1483 Buf += 16;
1484
Rui Ueyama7986b452017-03-01 18:09:09 +00001485 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001486 writeBloomFilter(Buf);
1487 Buf += sizeof(uintX_t) * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001488 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001489}
1490
Rui Ueyama7986b452017-03-01 18:09:09 +00001491// This function writes a 2-bit bloom filter. This bloom filter alone
1492// usually filters out 80% or more of all symbol lookups [1].
1493// The dynamic linker uses the hash table only when a symbol is not
1494// filtered out by a bloom filter.
1495//
1496// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1497// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
Eugene Leviantbe809a72016-11-18 06:44:18 +00001498template <class ELFT>
Rui Ueyamae13373b2017-03-01 02:51:42 +00001499void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001500 typedef typename ELFT::Off Elf_Off;
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001501 const unsigned C = sizeof(uintX_t) * 8;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001502
Rui Ueyamae13373b2017-03-01 02:51:42 +00001503 auto *Filter = reinterpret_cast<Elf_Off *>(Buf);
1504 for (const Entry &Sym : Symbols) {
1505 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1506 Filter[I] |= uintX_t(1) << (Sym.Hash % C);
1507 Filter[I] |= uintX_t(1) << ((Sym.Hash >> getShift2()) % C);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001508 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001509}
1510
1511template <class ELFT>
1512void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001513 // A 32-bit integer type in the target endianness.
1514 typedef typename ELFT::Word Elf_Word;
1515
Rui Ueyamae13373b2017-03-01 02:51:42 +00001516 // Group symbols by hash value.
1517 std::vector<std::vector<Entry>> Syms(NBuckets);
1518 for (const Entry &Ent : Symbols)
1519 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001520
Rui Ueyamae13373b2017-03-01 02:51:42 +00001521 // Write hash buckets. Hash buckets contain indices in the following
1522 // hash value table.
1523 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1524 for (size_t I = 0; I < NBuckets; ++I)
1525 if (!Syms[I].empty())
1526 Buckets[I] = Syms[I][0].Body->DynsymIndex;
1527
1528 // Write a hash value table. It represents a sequence of chains that
1529 // share the same hash modulo value. The last element of each chain
1530 // is terminated by LSB 1.
1531 Elf_Word *Values = Buckets + NBuckets;
1532 size_t I = 0;
1533 for (std::vector<Entry> &Vec : Syms) {
1534 if (Vec.empty())
1535 continue;
1536 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1537 Values[I++] = Ent.Hash & ~1;
1538 Values[I++] = Vec.back().Hash | 1;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001539 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001540}
1541
1542static uint32_t hashGnu(StringRef Name) {
1543 uint32_t H = 5381;
1544 for (uint8_t C : Name)
1545 H = (H << 5) + H + C;
1546 return H;
1547}
1548
Rui Ueyamae13373b2017-03-01 02:51:42 +00001549// Returns a number of hash buckets to accomodate given number of elements.
1550// We want to choose a moderate number that is not too small (which
1551// causes too many hash collisions) and not too large (which wastes
1552// disk space.)
1553//
1554// We return a prime number because it (is believed to) achieve good
1555// hash distribution.
1556static size_t getBucketSize(size_t NumSymbols) {
1557 // List of largest prime numbers that are not greater than 2^n + 1.
1558 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1559 251, 127, 61, 31, 13, 7, 3, 1})
1560 if (N <= NumSymbols)
1561 return N;
1562 return 0;
1563}
1564
Eugene Leviantbe809a72016-11-18 06:44:18 +00001565// Add symbols to this symbol hash table. Note that this function
1566// destructively sort a given vector -- which is needed because
1567// GNU-style hash table places some sorting requirements.
1568template <class ELFT>
1569void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001570 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1571 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001572 std::vector<SymbolTableEntry>::iterator Mid =
1573 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1574 return S.Symbol->isUndefined();
1575 });
1576 if (Mid == V.end())
1577 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001578
1579 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1580 SymbolBody *B = Ent.Symbol;
1581 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001582 }
1583
Rui Ueyamae13373b2017-03-01 02:51:42 +00001584 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001585 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001586 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001587 return L.Hash % NBuckets < R.Hash % NBuckets;
1588 });
1589
1590 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001591 for (const Entry &Ent : Symbols)
1592 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001593}
1594
Eugene Leviantb96e8092016-11-18 09:06:47 +00001595template <class ELFT>
1596HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001597 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1598 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001599}
1600
Rui Ueyama945055a2017-02-27 03:07:41 +00001601template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001602 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001603
1604 unsigned NumEntries = 2; // nbucket and nchain.
1605 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1606
1607 // Create as many buckets as there are symbols.
1608 // FIXME: This is simplistic. We can try to optimize it, but implementing
1609 // support for SHT_GNU_HASH is probably even more profitable.
1610 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001611 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001612}
1613
1614template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001615 // A 32-bit integer type in the target endianness.
1616 typedef typename ELFT::Word Elf_Word;
1617
Eugene Leviantb96e8092016-11-18 09:06:47 +00001618 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001619
Eugene Leviantb96e8092016-11-18 09:06:47 +00001620 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1621 *P++ = NumSymbols; // nbucket
1622 *P++ = NumSymbols; // nchain
1623
1624 Elf_Word *Buckets = P;
1625 Elf_Word *Chains = P + NumSymbols;
1626
1627 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1628 SymbolBody *Body = S.Symbol;
1629 StringRef Name = Body->getName();
1630 unsigned I = Body->DynsymIndex;
1631 uint32_t Hash = hashSysV(Name) % NumSymbols;
1632 Chains[I] = Buckets[Hash];
1633 Buckets[Hash] = I;
1634 }
1635}
1636
George Rimardfc020e2017-03-17 11:01:57 +00001637PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001638 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001639 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001640
George Rimardfc020e2017-03-17 11:01:57 +00001641void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001642 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1643 // linker to resolve dynsyms at runtime. Write such code.
1644 if (HeaderSize != 0)
1645 Target->writePltHeader(Buf);
1646 size_t Off = HeaderSize;
1647 // The IPlt is immediately after the Plt, account for this in RelOff
1648 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001649
1650 for (auto &I : Entries) {
1651 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001652 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001653 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001654 uint64_t Plt = this->getVA() + Off;
1655 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1656 Off += Target->PltEntrySize;
1657 }
1658}
1659
George Rimardfc020e2017-03-17 11:01:57 +00001660template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001661 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001662 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1663 if (HeaderSize == 0) {
1664 PltRelocSection = In<ELFT>::RelaIplt;
1665 Sym.IsInIplt = true;
1666 }
1667 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001668 Entries.push_back(std::make_pair(&Sym, RelOff));
1669}
1670
George Rimardfc020e2017-03-17 11:01:57 +00001671size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001672 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001673}
1674
Peter Smith96943762017-01-25 10:31:16 +00001675// Some architectures such as additional symbols in the PLT section. For
1676// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001677void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001678 // The PLT may have symbols defined for the Header, the IPLT has no header
1679 if (HeaderSize != 0)
1680 Target->addPltHeaderSymbols(this);
1681 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001682 for (size_t I = 0; I < Entries.size(); ++I) {
1683 Target->addPltSymbols(this, Off);
1684 Off += Target->PltEntrySize;
1685 }
1686}
1687
George Rimardfc020e2017-03-17 11:01:57 +00001688unsigned PltSection::getPltRelocOff() const {
1689 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001690}
1691
Peter Smithbaffdb82016-12-08 12:58:55 +00001692template <class ELFT>
Eugene Levianta113a412016-11-21 09:24:43 +00001693GdbIndexSection<ELFT>::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001694 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001695 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001696
George Rimarec02b8d2016-12-15 12:07:53 +00001697// Iterative hash function for symbol's name is described in .gdb_index format
1698// specification. Note that we use one for version 5 to 7 here, it is different
1699// for version 4.
1700static uint32_t hash(StringRef Str) {
1701 uint32_t R = 0;
1702 for (uint8_t C : Str)
1703 R = R * 67 + tolower(C) - 113;
1704 return R;
1705}
1706
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001707static std::vector<std::pair<uint64_t, uint64_t>>
1708readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1709 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1710 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1711 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1712 return Ret;
1713}
1714
1715template <class ELFT>
1716static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1717 uint64_t Offset) {
1718 for (InputSectionBase *S : Arr)
1719 if (S && S != &InputSection::Discarded)
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001720 if (Offset >= S->getOffsetInFile() &&
1721 Offset < S->getOffsetInFile() + S->getSize())
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001722 return S;
1723 return nullptr;
1724}
1725
1726template <class ELFT>
1727static std::vector<AddressEntry>
1728readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1729 std::vector<AddressEntry> Ret;
1730
1731 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1732 DWARFAddressRangesVector Ranges;
1733 CU->collectAddressRanges(Ranges);
1734
1735 ArrayRef<InputSectionBase *> Sections =
1736 Sec->template getFile<ELFT>()->getSections();
1737
1738 for (std::pair<uint64_t, uint64_t> &R : Ranges)
1739 if (InputSectionBase *S = findSection<ELFT>(Sections, R.first))
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001740 Ret.push_back({S, R.first - S->getOffsetInFile(),
1741 R.second - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001742 ++CurrentCU;
1743 }
1744 return Ret;
1745}
1746
1747static std::vector<std::pair<StringRef, uint8_t>>
1748readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1749 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1750 Dwarf.getGnuPubTypesSection()};
1751
1752 std::vector<std::pair<StringRef, uint8_t>> Ret;
1753 for (StringRef D : Data) {
1754 DWARFDebugPubTable PubTable(D, IsLE, true);
1755 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1756 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1757 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1758 }
1759 return Ret;
1760}
1761
1762class ObjInfoTy : public llvm::LoadedObjectInfo {
1763 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1764 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1765 if (S.getFlags() & ELF::SHF_ALLOC)
1766 return S.getOffset();
1767 return 0;
1768 }
1769
1770 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1771};
1772
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001773template <class ELFT> void GdbIndexSection<ELFT>::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001774 elf::ObjectFile<ELFT> *File = Sec->template getFile<ELFT>();
1775
1776 Expected<std::unique_ptr<object::ObjectFile>> Obj =
1777 object::ObjectFile::createObjectFile(File->MB);
1778 if (!Obj) {
1779 error(toString(File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001780 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001781 }
1782
1783 ObjInfoTy ObjInfo;
1784 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001785
1786 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001787 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1788 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001789
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001790 for (AddressEntry &Ent : readAddressArea<ELFT>(Dwarf, Sec, CuId))
1791 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001792
1793 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001794 readPubNamesAndTypes(Dwarf, ELFT::TargetEndianness == support::little);
George Rimarec02b8d2016-12-15 12:07:53 +00001795
1796 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1797 uint32_t Hash = hash(Pair.first);
1798 size_t Offset = StringPool.add(Pair.first);
1799
1800 bool IsNew;
1801 GdbSymbol *Sym;
1802 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1803 if (IsNew) {
1804 Sym->CuVectorIndex = CuVectors.size();
1805 CuVectors.push_back({{CuId, Pair.second}});
1806 continue;
1807 }
1808
Rui Ueyamaaab18c02017-03-01 22:24:46 +00001809 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
George Rimarec02b8d2016-12-15 12:07:53 +00001810 }
Eugene Levianta113a412016-11-21 09:24:43 +00001811}
1812
Rui Ueyama945055a2017-02-27 03:07:41 +00001813template <class ELFT> void GdbIndexSection<ELFT>::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001814 if (Finalized)
1815 return;
1816 Finalized = true;
1817
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001818 for (InputSectionBase *S : InputSections)
1819 if (InputSection *IS = dyn_cast<InputSection>(S))
1820 if (IS->OutSec && IS->Name == ".debug_info")
1821 readDwarf(IS);
1822
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001823 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001824
1825 // GdbIndex header consist from version fields
1826 // and 5 more fields with different kinds of offsets.
1827 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001828 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001829
1830 ConstantPoolOffset =
1831 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1832
1833 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1834 CuVectorsOffset.push_back(CuVectorsSize);
1835 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1836 }
1837 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1838
1839 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001840}
1841
1842template <class ELFT> size_t GdbIndexSection<ELFT>::getSize() const {
Rui Ueyama945055a2017-02-27 03:07:41 +00001843 const_cast<GdbIndexSection<ELFT> *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001844 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001845}
1846
1847template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001848 write32le(Buf, 7); // Write version.
1849 write32le(Buf + 4, CuListOffset); // CU list offset.
1850 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1851 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1852 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1853 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001854 Buf += 24;
1855
1856 // Write the CU list.
1857 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1858 write64le(Buf, CU.first);
1859 write64le(Buf + 8, CU.second);
1860 Buf += 16;
1861 }
George Rimar8b547392016-12-15 09:08:13 +00001862
1863 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001864 for (AddressEntry &E : AddressArea) {
Rafael Espindolae1294092017-03-08 16:03:41 +00001865 uintX_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001866 write64le(Buf, BaseAddr + E.LowAddress);
1867 write64le(Buf + 8, BaseAddr + E.HighAddress);
1868 write32le(Buf + 16, E.CuIndex);
1869 Buf += 20;
1870 }
George Rimarec02b8d2016-12-15 12:07:53 +00001871
1872 // Write the symbol table.
1873 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1874 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1875 if (Sym) {
1876 size_t NameOffset =
1877 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1878 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1879 write32le(Buf, NameOffset);
1880 write32le(Buf + 4, CuVectorOffset);
1881 }
1882 Buf += 8;
1883 }
1884
1885 // Write the CU vectors into the constant pool.
1886 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1887 write32le(Buf, CuVec.size());
1888 Buf += 4;
1889 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1890 uint32_t Index = P.first;
1891 uint8_t Flags = P.second;
1892 Index |= Flags << 24;
1893 write32le(Buf, Index);
1894 Buf += 4;
1895 }
1896 }
1897
1898 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001899}
1900
George Rimar3fb5a6d2016-11-29 16:05:27 +00001901template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001902 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001903}
1904
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001905template <class ELFT>
1906EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001907 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001908
1909// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1910// Each entry of the search table consists of two values,
1911// the starting PC from where FDEs covers, and the FDE's address.
1912// It is sorted by PC.
1913template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1914 const endianness E = ELFT::TargetEndianness;
1915
1916 // Sort the FDE list by their PC and uniqueify. Usually there is only
1917 // one FDE for a PC (i.e. function), but if ICF merges two functions
1918 // into one, there can be more than one FDEs pointing to the address.
1919 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1920 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1921 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1922 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1923
1924 Buf[0] = 1;
1925 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1926 Buf[2] = DW_EH_PE_udata4;
1927 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001928 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001929 write32<E>(Buf + 8, Fdes.size());
1930 Buf += 12;
1931
1932 uintX_t VA = this->getVA();
1933 for (FdeData &Fde : Fdes) {
1934 write32<E>(Buf, Fde.Pc - VA);
1935 write32<E>(Buf + 4, Fde.FdeVA - VA);
1936 Buf += 8;
1937 }
1938}
1939
1940template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1941 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001942 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001943}
1944
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001945template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001946void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1947 Fdes.push_back({Pc, FdeVA});
1948}
1949
George Rimar11992c862016-11-25 08:05:41 +00001950template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001951 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001952}
1953
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001954template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001955VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001956 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1957 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001958
1959static StringRef getFileDefName() {
1960 if (!Config->SoName.empty())
1961 return Config->SoName;
1962 return Config->OutputFile;
1963}
1964
Rui Ueyama945055a2017-02-27 03:07:41 +00001965template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001966 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1967 for (VersionDefinition &V : Config->VersionDefinitions)
1968 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1969
Rui Ueyamac3726f82017-02-28 04:41:20 +00001970 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001971
1972 // sh_info should be set to the number of definitions. This fact is missed in
1973 // documentation, but confirmed by binutils community:
1974 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001975 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001976}
1977
1978template <class ELFT>
1979void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1980 StringRef Name, size_t NameOff) {
1981 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1982 Verdef->vd_version = 1;
1983 Verdef->vd_cnt = 1;
1984 Verdef->vd_aux = sizeof(Elf_Verdef);
1985 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1986 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1987 Verdef->vd_ndx = Index;
1988 Verdef->vd_hash = hashSysV(Name);
1989
1990 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1991 Verdaux->vda_name = NameOff;
1992 Verdaux->vda_next = 0;
1993}
1994
1995template <class ELFT>
1996void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1997 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1998
1999 for (VersionDefinition &V : Config->VersionDefinitions) {
2000 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2001 writeOne(Buf, V.Id, V.Name, V.NameOff);
2002 }
2003
2004 // Need to terminate the last version definition.
2005 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2006 Verdef->vd_next = 0;
2007}
2008
2009template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2010 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2011}
2012
2013template <class ELFT>
2014VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002015 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002016 ".gnu.version") {
2017 this->Entsize = sizeof(Elf_Versym);
2018}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002019
Rui Ueyama945055a2017-02-27 03:07:41 +00002020template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002021 // At the moment of june 2016 GNU docs does not mention that sh_link field
2022 // should be set, but Sun docs do. Also readelf relies on this field.
Rui Ueyamac3726f82017-02-28 04:41:20 +00002023 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002024}
2025
2026template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2027 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2028}
2029
2030template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2031 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2032 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2033 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2034 ++OutVersym;
2035 }
2036}
2037
George Rimar11992c862016-11-25 08:05:41 +00002038template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2039 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2040}
2041
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002042template <class ELFT>
2043VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002044 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2045 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002046 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2047 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2048 // First identifiers are reserved by verdef section if it exist.
2049 NextIndex = getVerDefNum() + 1;
2050}
2051
2052template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002053void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2054 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2055 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002056 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2057 return;
2058 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002059
2060 auto *File = cast<SharedFile<ELFT>>(SS->File);
2061
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002062 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2063 // to create one by adding it to our needed list and creating a dynstr entry
2064 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002065 if (File->VerdefMap.empty())
2066 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->getSoName())});
2067 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002068 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2069 // prepare to create one by allocating a version identifier and creating a
2070 // dynstr entry for the version name.
2071 if (NV.Index == 0) {
Rui Ueyama4076fa12017-02-26 23:35:34 +00002072 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2073 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002074 NV.Index = NextIndex++;
2075 }
2076 SS->symbol()->VersionId = NV.Index;
2077}
2078
2079template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2080 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2081 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2082 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2083
2084 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2085 // Create an Elf_Verneed for this DSO.
2086 Verneed->vn_version = 1;
2087 Verneed->vn_cnt = P.first->VerdefMap.size();
2088 Verneed->vn_file = P.second;
2089 Verneed->vn_aux =
2090 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2091 Verneed->vn_next = sizeof(Elf_Verneed);
2092 ++Verneed;
2093
2094 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2095 // VerdefMap, which will only contain references to needed version
2096 // definitions. Each Elf_Vernaux is based on the information contained in
2097 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2098 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2099 // data structures within a single input file.
2100 for (auto &NV : P.first->VerdefMap) {
2101 Vernaux->vna_hash = NV.first->vd_hash;
2102 Vernaux->vna_flags = 0;
2103 Vernaux->vna_other = NV.second.Index;
2104 Vernaux->vna_name = NV.second.StrTab;
2105 Vernaux->vna_next = sizeof(Elf_Vernaux);
2106 ++Vernaux;
2107 }
2108
2109 Vernaux[-1].vna_next = 0;
2110 }
2111 Verneed[-1].vn_next = 0;
2112}
2113
Rui Ueyama945055a2017-02-27 03:07:41 +00002114template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00002115 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2116 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002117}
2118
2119template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2120 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2121 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2122 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2123 return Size;
2124}
2125
George Rimar11992c862016-11-25 08:05:41 +00002126template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2127 return getNeedNum() == 0;
2128}
2129
Rafael Espindola6119b862017-03-06 20:23:56 +00002130MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002131 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002132 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002133 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002134
Rafael Espindola6119b862017-03-06 20:23:56 +00002135void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002136 assert(!Finalized);
2137 MS->MergeSec = this;
2138 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002139}
2140
Rafael Espindola6119b862017-03-06 20:23:56 +00002141void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002142
Rafael Espindola6119b862017-03-06 20:23:56 +00002143bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002144 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2145}
2146
Rafael Espindola6119b862017-03-06 20:23:56 +00002147void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002148 // Add all string pieces to the string table builder to create section
2149 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002150 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002151 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2152 if (Sec->Pieces[I].Live)
2153 Builder.add(Sec->getData(I));
2154
2155 // Fix the string table content. After this, the contents will never change.
2156 Builder.finalize();
2157
2158 // finalize() fixed tail-optimized strings, so we can now get
2159 // offsets of strings. Get an offset for each string and save it
2160 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002161 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002162 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2163 if (Sec->Pieces[I].Live)
2164 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2165}
2166
Rafael Espindola6119b862017-03-06 20:23:56 +00002167void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002168 // Add all string pieces to the string table builder to create section
2169 // contents. Because we are not tail-optimizing, offsets of strings are
2170 // fixed when they are added to the builder (string table builder contains
2171 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002172 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002173 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2174 if (Sec->Pieces[I].Live)
2175 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2176
2177 Builder.finalizeInOrder();
2178}
2179
Rafael Espindola6119b862017-03-06 20:23:56 +00002180void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002181 if (Finalized)
2182 return;
2183 Finalized = true;
2184 if (shouldTailMerge())
2185 finalizeTailMerge();
2186 else
2187 finalizeNoTailMerge();
2188}
2189
Rafael Espindola6119b862017-03-06 20:23:56 +00002190size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002191 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002192 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002193 return Builder.getSize();
2194}
2195
George Rimar42886c42017-03-15 12:02:31 +00002196MipsRldMapSection::MipsRldMapSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002197 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
George Rimar7385d432017-03-16 13:41:29 +00002198 Config->is64() ? 8 : 4, ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002199
George Rimar42886c42017-03-15 12:02:31 +00002200void MipsRldMapSection::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00002201 // Apply filler from linker script.
George Rimar42886c42017-03-15 12:02:31 +00002202 uint64_t Filler = ScriptBase->getFiller(this->Name);
Eugene Leviant17b7a572016-11-22 17:49:14 +00002203 Filler = (Filler << 32) | Filler;
2204 memcpy(Buf, &Filler, getSize());
2205}
2206
Peter Smith719eb8e2016-11-24 11:43:55 +00002207template <class ELFT>
2208ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002209 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2210 sizeof(typename ELFT::uint), ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002211
2212// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2213// This section will have been sorted last in the .ARM.exidx table.
2214// This table entry will have the form:
2215// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
George Rimar879a6572016-12-15 15:38:58 +00002216template <class ELFT>
2217void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf) {
Peter Smith719eb8e2016-11-24 11:43:55 +00002218 // Get the InputSection before us, we are by definition last
Rafael Espindola24e6f362017-02-24 15:07:30 +00002219 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002220 InputSection *LE = *(++RI);
2221 InputSection *LC = cast<InputSection>(LE->template getLinkOrderDep<ELFT>());
Rafael Espindolae1294092017-03-08 16:03:41 +00002222 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
Peter Smith719eb8e2016-11-24 11:43:55 +00002223 uint64_t P = this->getVA();
2224 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2225 write32le(Buf + 4, 0x1);
2226}
2227
George Rimar7b827042017-03-16 10:40:50 +00002228ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002229 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
George Rimar7385d432017-03-16 13:41:29 +00002230 Config->is64() ? 8 : 4, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002231 this->OutSec = OS;
2232 this->OutSecOff = Off;
2233}
2234
George Rimar7b827042017-03-16 10:40:50 +00002235void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002236 uint64_t Off = alignTo(Size, T->alignment);
2237 T->Offset = Off;
2238 Thunks.push_back(T);
2239 T->addSymbols(*this);
2240 Size = Off + T->size();
2241}
2242
George Rimar7b827042017-03-16 10:40:50 +00002243void ThunkSection::writeTo(uint8_t *Buf) {
2244 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002245 T->writeTo(Buf + T->Offset, *this);
2246}
2247
George Rimar7b827042017-03-16 10:40:50 +00002248InputSection *ThunkSection::getTargetInputSection() const {
2249 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002250 return T->getTargetInputSection();
2251}
2252
George Rimardfc020e2017-03-17 11:01:57 +00002253namespace lld {
2254namespace elf {
2255template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2256template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2257template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2258template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2259}
2260}
2261
George Rimar9782ca52017-03-15 15:29:29 +00002262InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002263BssSection *InX::Bss;
2264BssSection *InX::BssRelRo;
George Rimar9782ca52017-03-15 15:29:29 +00002265InputSection *InX::Common;
2266StringTableSection *InX::DynStrTab;
2267InputSection *InX::Interp;
2268GotPltSection *InX::GotPlt;
2269IgotPltSection *InX::IgotPlt;
2270MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002271PltSection *InX::Plt;
2272PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002273StringTableSection *InX::ShStrTab;
2274StringTableSection *InX::StrTab;
2275
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002276template InputSection *elf::createCommonSection<ELF32LE>();
2277template InputSection *elf::createCommonSection<ELF32BE>();
2278template InputSection *elf::createCommonSection<ELF64LE>();
2279template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002280
Rafael Espindola6119b862017-03-06 20:23:56 +00002281template MergeInputSection *elf::createCommentSection<ELF32LE>();
2282template MergeInputSection *elf::createCommentSection<ELF32BE>();
2283template MergeInputSection *elf::createCommentSection<ELF64LE>();
2284template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002285
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002286template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002287 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002288 InputSectionBase *);
2289template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002290 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002291 InputSectionBase *);
2292template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002293 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002294 InputSectionBase *);
2295template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002296 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002297 InputSectionBase *);
Peter Smith96943762017-01-25 10:31:16 +00002298
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002299template class elf::MipsAbiFlagsSection<ELF32LE>;
2300template class elf::MipsAbiFlagsSection<ELF32BE>;
2301template class elf::MipsAbiFlagsSection<ELF64LE>;
2302template class elf::MipsAbiFlagsSection<ELF64BE>;
2303
Simon Atanasyance02cf02016-11-09 21:36:56 +00002304template class elf::MipsOptionsSection<ELF32LE>;
2305template class elf::MipsOptionsSection<ELF32BE>;
2306template class elf::MipsOptionsSection<ELF64LE>;
2307template class elf::MipsOptionsSection<ELF64BE>;
2308
2309template class elf::MipsReginfoSection<ELF32LE>;
2310template class elf::MipsReginfoSection<ELF32BE>;
2311template class elf::MipsReginfoSection<ELF64LE>;
2312template class elf::MipsReginfoSection<ELF64BE>;
2313
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00002314template class elf::BuildIdSection<ELF32LE>;
2315template class elf::BuildIdSection<ELF32BE>;
2316template class elf::BuildIdSection<ELF64LE>;
2317template class elf::BuildIdSection<ELF64BE>;
2318
Eugene Leviantad4439e2016-11-11 11:33:32 +00002319template class elf::GotSection<ELF32LE>;
2320template class elf::GotSection<ELF32BE>;
2321template class elf::GotSection<ELF64LE>;
2322template class elf::GotSection<ELF64BE>;
2323
Simon Atanasyan725dc142016-11-16 21:01:02 +00002324template class elf::MipsGotSection<ELF32LE>;
2325template class elf::MipsGotSection<ELF32BE>;
2326template class elf::MipsGotSection<ELF64LE>;
2327template class elf::MipsGotSection<ELF64BE>;
2328
Eugene Leviant6380ce22016-11-15 12:26:55 +00002329template class elf::DynamicSection<ELF32LE>;
2330template class elf::DynamicSection<ELF32BE>;
2331template class elf::DynamicSection<ELF64LE>;
2332template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002333
2334template class elf::RelocationSection<ELF32LE>;
2335template class elf::RelocationSection<ELF32BE>;
2336template class elf::RelocationSection<ELF64LE>;
2337template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002338
2339template class elf::SymbolTableSection<ELF32LE>;
2340template class elf::SymbolTableSection<ELF32BE>;
2341template class elf::SymbolTableSection<ELF64LE>;
2342template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002343
2344template class elf::GnuHashTableSection<ELF32LE>;
2345template class elf::GnuHashTableSection<ELF32BE>;
2346template class elf::GnuHashTableSection<ELF64LE>;
2347template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002348
2349template class elf::HashTableSection<ELF32LE>;
2350template class elf::HashTableSection<ELF32BE>;
2351template class elf::HashTableSection<ELF64LE>;
2352template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002353
Eugene Levianta113a412016-11-21 09:24:43 +00002354template class elf::GdbIndexSection<ELF32LE>;
2355template class elf::GdbIndexSection<ELF32BE>;
2356template class elf::GdbIndexSection<ELF64LE>;
2357template class elf::GdbIndexSection<ELF64BE>;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002358
2359template class elf::EhFrameHeader<ELF32LE>;
2360template class elf::EhFrameHeader<ELF32BE>;
2361template class elf::EhFrameHeader<ELF64LE>;
2362template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002363
2364template class elf::VersionTableSection<ELF32LE>;
2365template class elf::VersionTableSection<ELF32BE>;
2366template class elf::VersionTableSection<ELF64LE>;
2367template class elf::VersionTableSection<ELF64BE>;
2368
2369template class elf::VersionNeedSection<ELF32LE>;
2370template class elf::VersionNeedSection<ELF32BE>;
2371template class elf::VersionNeedSection<ELF64LE>;
2372template class elf::VersionNeedSection<ELF64BE>;
2373
2374template class elf::VersionDefinitionSection<ELF32LE>;
2375template class elf::VersionDefinitionSection<ELF32BE>;
2376template class elf::VersionDefinitionSection<ELF64LE>;
2377template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002378
Peter Smith719eb8e2016-11-24 11:43:55 +00002379template class elf::ARMExidxSentinelSection<ELF32LE>;
2380template class elf::ARMExidxSentinelSection<ELF32BE>;
2381template class elf::ARMExidxSentinelSection<ELF64LE>;
2382template class elf::ARMExidxSentinelSection<ELF64BE>;
Peter Smith3a52eb02017-02-01 10:26:03 +00002383
Rafael Espindola66b4e212017-02-23 22:06:28 +00002384template class elf::EhFrameSection<ELF32LE>;
2385template class elf::EhFrameSection<ELF32BE>;
2386template class elf::EhFrameSection<ELF64LE>;
2387template class elf::EhFrameSection<ELF64BE>;