blob: 159891274cd58acbd147f8858dcd6dba84ad5b15 [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() {
George Rimar4ddd9c92017-03-17 13:21:22 +000066 auto *Ret = make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
67 ArrayRef<uint8_t>(), "COMMON");
68 Ret->Live = true;
69
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000070 if (!Config->DefineCommon)
George Rimar4ddd9c92017-03-17 13:21:22 +000071 return Ret;
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000072
Rui Ueyamae8a61022016-11-05 23:05:47 +000073 // Sort the common symbols by alignment as an heuristic to pack them better.
74 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
75 std::stable_sort(Syms.begin(), Syms.end(),
76 [](const DefinedCommon *A, const DefinedCommon *B) {
77 return A->Alignment > B->Alignment;
78 });
79
George Rimar4ddd9c92017-03-17 13:21:22 +000080 // Assign offsets to symbols.
81 size_t Size = 0;
82 uint32_t Alignment = 1;
83 for (DefinedCommon *Sym : Syms) {
84 Alignment = std::max(Alignment, Sym->Alignment);
85 Size = alignTo(Size, Sym->Alignment);
86
87 // Compute symbol offset relative to beginning of input section.
88 Sym->Offset = Size;
89 Size += Sym->Size;
90 }
91 Ret->Alignment = Alignment;
92 Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
Rafael Espindola682a5bc2016-11-08 14:42:34 +000093 return Ret;
Rui Ueyamae8a61022016-11-05 23:05:47 +000094}
95
Rui Ueyama3da3f062016-11-10 20:20:37 +000096// Returns an LLD version string.
97static ArrayRef<uint8_t> getVersion() {
98 // Check LLD_VERSION first for ease of testing.
99 // You can get consitent output by using the environment variable.
100 // This is only for testing.
101 StringRef S = getenv("LLD_VERSION");
102 if (S.empty())
103 S = Saver.save(Twine("Linker: ") + getLLDVersion());
104
105 // +1 to include the terminating '\0'.
106 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +0000107}
Rui Ueyama3da3f062016-11-10 20:20:37 +0000108
109// Creates a .comment section containing LLD version info.
110// With this feature, you can identify LLD-generated binaries easily
111// by "objdump -s -j .comment <file>".
112// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000113template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000114 typename ELFT::Shdr Hdr = {};
115 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
116 Hdr.sh_type = SHT_PROGBITS;
117 Hdr.sh_entsize = 1;
118 Hdr.sh_addralign = 1;
119
Rafael Espindola6119b862017-03-06 20:23:56 +0000120 auto *Ret =
121 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000122 Ret->Data = getVersion();
123 Ret->splitIntoPieces();
124 return Ret;
125}
126
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000127// .MIPS.abiflags section.
128template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000129MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000130 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000131 Flags(Flags) {
132 this->Entsize = sizeof(Elf_Mips_ABIFlags);
133}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000134
135template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
136 memcpy(Buf, &Flags, sizeof(Flags));
137}
138
139template <class ELFT>
140MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
141 Elf_Mips_ABIFlags Flags = {};
142 bool Create = false;
143
Rui Ueyama536a2672017-02-27 02:32:08 +0000144 for (InputSectionBase *Sec : InputSections) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000145 if (!Sec->Live || Sec->Type != SHT_MIPS_ABIFLAGS)
146 continue;
147 Sec->Live = false;
148 Create = true;
149
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000150 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000151 const size_t Size = Sec->Data.size();
152 // Older version of BFD (such as the default FreeBSD linker) concatenate
153 // .MIPS.abiflags instead of merging. To allow for this case (or potential
154 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
155 if (Size < sizeof(Elf_Mips_ABIFlags)) {
156 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
157 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000158 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000159 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000160 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000161 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000162 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000163 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000164 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000165 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000166
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000167 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
168 // select the highest number of ISA/Rev/Ext.
169 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
170 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
171 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
172 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
173 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
174 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
175 Flags.ases |= S->ases;
176 Flags.flags1 |= S->flags1;
177 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000178 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000179 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000180
Rui Ueyama12f2da82016-11-22 03:57:06 +0000181 if (Create)
182 return make<MipsAbiFlagsSection<ELFT>>(Flags);
183 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000184}
185
Simon Atanasyance02cf02016-11-09 21:36:56 +0000186// .MIPS.options section.
187template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000188MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000189 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000190 Reginfo(Reginfo) {
191 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
192}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000193
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000194template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
195 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
196 Options->kind = ODK_REGINFO;
197 Options->size = getSize();
198
199 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000200 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000201 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000202}
203
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000204template <class ELFT>
205MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
206 // N64 ABI only.
207 if (!ELFT::Is64Bits)
208 return nullptr;
209
210 Elf_Mips_RegInfo Reginfo = {};
211 bool Create = false;
212
Rui Ueyama536a2672017-02-27 02:32:08 +0000213 for (InputSectionBase *Sec : InputSections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000214 if (!Sec->Live || Sec->Type != SHT_MIPS_OPTIONS)
215 continue;
216 Sec->Live = false;
217 Create = true;
218
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000219 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000220 ArrayRef<uint8_t> D = Sec->Data;
221
222 while (!D.empty()) {
223 if (D.size() < sizeof(Elf_Mips_Options)) {
224 error(Filename + ": invalid size of .MIPS.options section");
225 break;
226 }
227
228 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
229 if (Opt->kind == ODK_REGINFO) {
230 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
231 error(Filename + ": unsupported non-zero ri_gp_value");
232 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000233 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000234 break;
235 }
236
237 if (!Opt->size)
238 fatal(Filename + ": zero option descriptor size");
239 D = D.slice(Opt->size);
240 }
241 };
242
243 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000244 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000245 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000246}
247
248// MIPS .reginfo section.
249template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000250MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000251 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000252 Reginfo(Reginfo) {
253 this->Entsize = sizeof(Elf_Mips_RegInfo);
254}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000255
Rui Ueyamab71cae92016-11-22 03:57:08 +0000256template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000257 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000258 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000259 memcpy(Buf, &Reginfo, sizeof(Reginfo));
260}
261
262template <class ELFT>
263MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
264 // Section should be alive for O32 and N32 ABIs only.
265 if (ELFT::Is64Bits)
266 return nullptr;
267
268 Elf_Mips_RegInfo Reginfo = {};
269 bool Create = false;
270
Rui Ueyama536a2672017-02-27 02:32:08 +0000271 for (InputSectionBase *Sec : InputSections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000272 if (!Sec->Live || Sec->Type != SHT_MIPS_REGINFO)
273 continue;
274 Sec->Live = false;
275 Create = true;
276
277 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000278 error(toString(Sec->getFile<ELFT>()) +
279 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000280 return nullptr;
281 }
282 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
283 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000284 error(toString(Sec->getFile<ELFT>()) +
285 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000286
287 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000288 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000289 };
290
291 if (Create)
292 return make<MipsReginfoSection<ELFT>>(Reginfo);
293 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000294}
295
Rui Ueyama3255a522017-02-27 02:32:49 +0000296InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000297 // StringSaver guarantees that the returned string ends with '\0'.
298 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000299 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
300
301 auto *Sec =
302 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
303 Sec->Live = true;
304 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000305}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000306
Peter Smith96943762017-01-25 10:31:16 +0000307template <class ELFT>
Rui Ueyama65316d72017-02-23 03:15:57 +0000308SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
309 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000310 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
311 Value, Size, Section, nullptr);
Peter Smith96943762017-01-25 10:31:16 +0000312 if (In<ELFT>::SymTab)
Rui Ueyamab8dcdb52017-02-28 04:20:16 +0000313 In<ELFT>::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000314 return S;
315}
316
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000317static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000318 switch (Config->BuildId) {
319 case BuildIdKind::Fast:
320 return 8;
321 case BuildIdKind::Md5:
322 case BuildIdKind::Uuid:
323 return 16;
324 case BuildIdKind::Sha1:
325 return 20;
326 case BuildIdKind::Hexstring:
327 return Config->BuildIdVector.size();
328 default:
329 llvm_unreachable("unknown BuildIdKind");
330 }
331}
332
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000333template <class ELFT>
334BuildIdSection<ELFT>::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000335 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000336 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000337
338template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
339 const endianness E = ELFT::TargetEndianness;
340 write32<E>(Buf, 4); // Name size
341 write32<E>(Buf + 4, HashSize); // Content size
342 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
343 memcpy(Buf + 12, "GNU", 4); // Name string
344 HashBuf = Buf + 16;
345}
346
Rui Ueyama35e00752016-11-10 00:12:28 +0000347// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000348static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
349 size_t ChunkSize) {
350 std::vector<ArrayRef<uint8_t>> Ret;
351 while (Arr.size() > ChunkSize) {
352 Ret.push_back(Arr.take_front(ChunkSize));
353 Arr = Arr.drop_front(ChunkSize);
354 }
355 if (!Arr.empty())
356 Ret.push_back(Arr);
357 return Ret;
358}
359
Rui Ueyama35e00752016-11-10 00:12:28 +0000360// Computes a hash value of Data using a given hash function.
361// In order to utilize multiple cores, we first split data into 1MB
362// chunks, compute a hash for each chunk, and then compute a hash value
363// of the hash values.
George Rimar364b59e22016-11-06 07:42:55 +0000364template <class ELFT>
365void BuildIdSection<ELFT>::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000366 llvm::ArrayRef<uint8_t> Data,
367 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000368 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000369 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000370
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000371 // Compute hash values.
Rui Ueyama244a4352016-12-03 21:24:51 +0000372 forLoop(0, Chunks.size(),
373 [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); });
Rui Ueyama35e00752016-11-10 00:12:28 +0000374
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000375 // Write to the final output buffer.
376 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000377}
378
George Rimar1ab9cf42017-03-17 10:14:53 +0000379BssSection::BssSection(StringRef Name)
380 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
381
382size_t BssSection::reserveSpace(uint32_t Alignment, size_t Size) {
George Rimar4ddd9c92017-03-17 13:21:22 +0000383 OutSec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000384 this->Size = alignTo(this->Size, Alignment) + Size;
385 this->Alignment = std::max<uint32_t>(this->Alignment, Alignment);
386 return this->Size - Size;
387}
Peter Smithebfe9942017-02-09 10:27:57 +0000388
389template <class ELFT>
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000390void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000391 switch (Config->BuildId) {
392 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000393 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000394 write64le(Dest, xxHash64(toStringRef(Arr)));
395 });
396 break;
397 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000398 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000399 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000400 });
401 break;
402 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000403 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000404 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000405 });
406 break;
407 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000408 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000409 error("entropy source failure");
410 break;
411 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000412 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000413 break;
414 default:
415 llvm_unreachable("unknown BuildIdKind");
416 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000417}
418
Eugene Leviant41ca3272016-11-10 09:48:29 +0000419template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000420EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000421 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000422
423// Search for an existing CIE record or create a new one.
424// CIE records from input object files are uniquified by their contents
425// and where their relocations point to.
426template <class ELFT>
427template <class RelTy>
428CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
429 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000430 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000431 const endianness E = ELFT::TargetEndianness;
432 if (read32<E>(Piece.data().data() + 4) != 0)
433 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
434
435 SymbolBody *Personality = nullptr;
436 unsigned FirstRelI = Piece.FirstRelocation;
437 if (FirstRelI != (unsigned)-1)
438 Personality =
439 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
440
441 // Search for an existing CIE by CIE contents/relocation target pair.
442 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
443
444 // If not found, create a new one.
445 if (Cie->Piece == nullptr) {
446 Cie->Piece = &Piece;
447 Cies.push_back(Cie);
448 }
449 return Cie;
450}
451
452// There is one FDE per function. Returns true if a given FDE
453// points to a live function.
454template <class ELFT>
455template <class RelTy>
456bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
457 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000458 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000459 unsigned FirstRelI = Piece.FirstRelocation;
460 if (FirstRelI == (unsigned)-1)
461 return false;
462 const RelTy &Rel = Rels[FirstRelI];
463 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000464 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000465 if (!D || !D->Section)
466 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000467 auto *Target =
468 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000469 return Target && Target->Live;
470}
471
472// .eh_frame is a sequence of CIE or FDE records. In general, there
473// is one CIE record per input object file which is followed by
474// a list of FDEs. This function searches an existing CIE or create a new
475// one and associates FDEs to the CIE.
476template <class ELFT>
477template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000478void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000479 ArrayRef<RelTy> Rels) {
480 const endianness E = ELFT::TargetEndianness;
481
482 DenseMap<size_t, CieRecord *> OffsetToCie;
483 for (EhSectionPiece &Piece : Sec->Pieces) {
484 // The empty record is the end marker.
485 if (Piece.size() == 4)
486 return;
487
488 size_t Offset = Piece.InputOff;
489 uint32_t ID = read32<E>(Piece.data().data() + 4);
490 if (ID == 0) {
491 OffsetToCie[Offset] = addCie(Piece, Rels);
492 continue;
493 }
494
495 uint32_t CieOffset = Offset + 4 - ID;
496 CieRecord *Cie = OffsetToCie[CieOffset];
497 if (!Cie)
498 fatal(toString(Sec) + ": invalid CIE reference");
499
500 if (!isFdeLive(Piece, Rels))
501 continue;
502 Cie->FdePieces.push_back(&Piece);
503 NumFdes++;
504 }
505}
506
507template <class ELFT>
508void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000509 auto *Sec = cast<EhInputSection>(C);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000510 Sec->EHSec = this;
511 updateAlignment(Sec->Alignment);
512 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000513 for (auto *DS : Sec->DependentSections)
514 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000515
516 // .eh_frame is a sequence of CIE or FDE records. This function
517 // splits it into pieces so that we can call
518 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000519 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000520 if (Sec->Pieces.empty())
521 return;
522
523 if (Sec->NumRelocations) {
524 if (Sec->AreRelocsRela)
525 addSectionAux(Sec, Sec->template relas<ELFT>());
526 else
527 addSectionAux(Sec, Sec->template rels<ELFT>());
528 return;
529 }
530 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
531}
532
533template <class ELFT>
534static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
535 memcpy(Buf, D.data(), D.size());
536
537 // Fix the size field. -4 since size does not include the size field itself.
538 const endianness E = ELFT::TargetEndianness;
539 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
540}
541
Rui Ueyama945055a2017-02-27 03:07:41 +0000542template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000543 if (this->Size)
544 return; // Already finalized.
545
546 size_t Off = 0;
547 for (CieRecord *Cie : Cies) {
548 Cie->Piece->OutputOff = Off;
549 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
550
551 for (EhSectionPiece *Fde : Cie->FdePieces) {
552 Fde->OutputOff = Off;
553 Off += alignTo(Fde->size(), sizeof(uintX_t));
554 }
555 }
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000556 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000557}
558
559template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
560 const endianness E = ELFT::TargetEndianness;
561 switch (Size) {
562 case DW_EH_PE_udata2:
563 return read16<E>(Buf);
564 case DW_EH_PE_udata4:
565 return read32<E>(Buf);
566 case DW_EH_PE_udata8:
567 return read64<E>(Buf);
568 case DW_EH_PE_absptr:
569 if (ELFT::Is64Bits)
570 return read64<E>(Buf);
571 return read32<E>(Buf);
572 }
573 fatal("unknown FDE size encoding");
574}
575
576// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
577// We need it to create .eh_frame_hdr section.
578template <class ELFT>
579typename ELFT::uint EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
580 uint8_t Enc) {
581 // The starting address to which this FDE applies is
582 // stored at FDE + 8 byte.
583 size_t Off = FdeOff + 8;
584 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
585 if ((Enc & 0x70) == DW_EH_PE_absptr)
586 return Addr;
587 if ((Enc & 0x70) == DW_EH_PE_pcrel)
588 return Addr + this->OutSec->Addr + Off;
589 fatal("unknown FDE size relative encoding");
590}
591
592template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
593 const endianness E = ELFT::TargetEndianness;
594 for (CieRecord *Cie : Cies) {
595 size_t CieOffset = Cie->Piece->OutputOff;
596 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
597
598 for (EhSectionPiece *Fde : Cie->FdePieces) {
599 size_t Off = Fde->OutputOff;
600 writeCieFde<ELFT>(Buf + Off, Fde->data());
601
602 // FDE's second word should have the offset to an associated CIE.
603 // Write it.
604 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
605 }
606 }
607
Rafael Espindola5c02b742017-03-06 21:17:18 +0000608 for (EhInputSection *S : Sections)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000609 S->template relocate<ELFT>(Buf, nullptr);
610
611 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
612 // to get a FDE from an address to which FDE is applied. So here
613 // we obtain two addresses and pass them to EhFrameHdr object.
614 if (In<ELFT>::EhFrameHdr) {
615 for (CieRecord *Cie : Cies) {
616 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
617 for (SectionPiece *Fde : Cie->FdePieces) {
618 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
619 uintX_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
620 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
621 }
622 }
623 }
624}
625
626template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000627GotSection<ELFT>::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000628 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
629 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000630
631template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000632 Sym.GotIndex = NumEntries;
633 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000634}
635
Simon Atanasyan725dc142016-11-16 21:01:02 +0000636template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
637 if (Sym.GlobalDynIndex != -1U)
638 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000639 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000641 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000642 return true;
643}
644
645// Reserves TLS entries for a TLS module ID and a TLS block offset.
646// In total it takes two GOT slots.
647template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
648 if (TlsIndexOff != uint32_t(-1))
649 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000650 TlsIndexOff = NumEntries * sizeof(uintX_t);
651 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000652 return true;
653}
654
Eugene Leviantad4439e2016-11-11 11:33:32 +0000655template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000656typename GotSection<ELFT>::uintX_t
657GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
658 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
659}
660
661template <class ELFT>
662typename GotSection<ELFT>::uintX_t
663GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
664 return B.GlobalDynIndex * sizeof(uintX_t);
665}
666
Rui Ueyama945055a2017-02-27 03:07:41 +0000667template <class ELFT> void GotSection<ELFT>::finalizeContents() {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000668 Size = NumEntries * sizeof(uintX_t);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000669}
670
George Rimar11992c862016-11-25 08:05:41 +0000671template <class ELFT> bool GotSection<ELFT>::empty() const {
672 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
673 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000674 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000675}
676
Simon Atanasyan725dc142016-11-16 21:01:02 +0000677template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000678 this->template relocate<ELFT>(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000679}
680
681template <class ELFT>
682MipsGotSection<ELFT>::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000683 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
684 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000685
686template <class ELFT>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000687void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, int64_t Addend,
Eugene Leviantad4439e2016-11-11 11:33:32 +0000688 RelExpr Expr) {
689 // For "true" local symbols which can be referenced from the same module
690 // only compiler creates two instructions for address loading:
691 //
692 // lw $8, 0($gp) # R_MIPS_GOT16
693 // addi $8, $8, 0 # R_MIPS_LO16
694 //
695 // The first instruction loads high 16 bits of the symbol address while
696 // the second adds an offset. That allows to reduce number of required
697 // GOT entries because only one global offset table entry is necessary
698 // for every 64 KBytes of local data. So for local symbols we need to
699 // allocate number of GOT entries to hold all required "page" addresses.
700 //
701 // All global symbols (hidden and regular) considered by compiler uniformly.
702 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
703 // to load address of the symbol. So for each such symbol we need to
704 // allocate dedicated GOT entry to store its address.
705 //
706 // If a symbol is preemptible we need help of dynamic linker to get its
707 // final address. The corresponding GOT entries are allocated in the
708 // "global" part of GOT. Entries for non preemptible global symbol allocated
709 // in the "local" part of GOT.
710 //
711 // See "Global Offset Table" in Chapter 5:
712 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
713 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
714 // At this point we do not know final symbol value so to reduce number
715 // of allocated GOT entries do the following trick. Save all output
716 // sections referenced by GOT relocations. Then later in the `finalize`
717 // method calculate number of "pages" required to cover all saved output
718 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000719 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000720 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000721 return;
722 }
723 if (Sym.isTls()) {
724 // GOT entries created for MIPS TLS relocations behave like
725 // almost GOT entries from other ABIs. They go to the end
726 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000727 Sym.GotIndex = TlsEntries.size();
728 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 return;
730 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000731 auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000732 if (S.isInGot() && !A)
733 return;
734 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000735 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000736 return;
737 Items.emplace_back(&S, A);
738 if (!A)
739 S.GotIndex = NewIndex;
740 };
741 if (Sym.isPreemptible()) {
742 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000743 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000744 Sym.IsInGlobalMipsGot = true;
745 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000746 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000747 Sym.Is32BitMipsGot = true;
748 } else {
749 // Hold local GOT entries accessed via a 16-bit index separately.
750 // That allows to write them in the beginning of the GOT and keep
751 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000752 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000753 }
754}
755
George Rimar879a6572016-12-15 15:38:58 +0000756template <class ELFT>
757bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000758 if (Sym.GlobalDynIndex != -1U)
759 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000760 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000761 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000762 TlsEntries.push_back(nullptr);
763 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000764 return true;
765}
766
767// Reserves TLS entries for a TLS module ID and a TLS block offset.
768// In total it takes two GOT slots.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000769template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000770 if (TlsIndexOff != uint32_t(-1))
771 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000772 TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
773 TlsEntries.push_back(nullptr);
774 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000775 return true;
776}
777
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000778static uint64_t getMipsPageAddr(uint64_t Addr) {
779 return (Addr + 0x8000) & ~0xffff;
780}
781
782static uint64_t getMipsPageCount(uint64_t Size) {
783 return (Size + 0xfffe) / 0xffff + 1;
784}
785
Eugene Leviantad4439e2016-11-11 11:33:32 +0000786template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000787typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000788MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000789 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000790 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000791 cast<DefinedRegular>(&B)->Section->getOutputSection();
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000792 uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
George Rimarf64618a2017-03-17 11:56:54 +0000793 uintX_t SymAddr = getMipsPageAddr(B.getVA(Addend));
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000794 uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
795 assert(Index < PageEntriesNum);
796 return (HeaderEntriesNum + Index) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000797}
798
799template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000800typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000801MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000802 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000803 // Calculate offset of the GOT entries block: TLS, global, local.
Simon Atanasyana0efc422016-11-29 10:23:50 +0000804 uintX_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000805 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000806 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000807 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000808 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000809 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000810 Index += LocalEntries.size();
811 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000812 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000813 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000814 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000815 auto It = EntryIndexMap.find({&B, Addend});
816 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000817 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000818 }
Simon Atanasyana0efc422016-11-29 10:23:50 +0000819 return Index * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000820}
821
822template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000823typename MipsGotSection<ELFT>::uintX_t
824MipsGotSection<ELFT>::getTlsOffset() const {
825 return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000826}
827
828template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000829typename MipsGotSection<ELFT>::uintX_t
830MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000831 return B.GlobalDynIndex * sizeof(uintX_t);
832}
833
834template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000835const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
836 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000837}
838
839template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000840unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000841 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
842 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000843}
844
Rui Ueyama945055a2017-02-27 03:07:41 +0000845template <class ELFT> void MipsGotSection<ELFT>::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000846 updateAllocSize();
847}
848
849template <class ELFT> void MipsGotSection<ELFT>::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000850 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000851 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000852 // For each output section referenced by GOT page relocations calculate
853 // and save into PageIndexMap an upper bound of MIPS GOT entries required
854 // to store page addresses of local symbols. We assume the worst case -
855 // each 64kb page of the output section has at least one GOT relocation
856 // against it. And take in account the case when the section intersects
857 // page boundaries.
858 P.second = PageEntriesNum;
859 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000860 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000861 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
862 sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000863}
864
George Rimar11992c862016-11-25 08:05:41 +0000865template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
866 // We add the .got section to the result for dynamic MIPS target because
867 // its address and properties are mentioned in the .dynamic section.
868 return Config->Relocatable;
869}
870
Simon Atanasyanb9666652016-12-12 14:30:18 +0000871template <class ELFT>
872typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000873 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000874}
875
Eugene Leviantad4439e2016-11-11 11:33:32 +0000876template <class ELFT>
877static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
878 typedef typename ELFT::uint uintX_t;
879 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
880}
881
Simon Atanasyan725dc142016-11-16 21:01:02 +0000882template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000883 // Set the MSB of the second GOT slot. This is not required by any
884 // MIPS ABI documentation, though.
885 //
886 // There is a comment in glibc saying that "The MSB of got[1] of a
887 // gnu object is set to identify gnu objects," and in GNU gold it
888 // says "the second entry will be used by some runtime loaders".
889 // But how this field is being used is unclear.
890 //
891 // We are not really willing to mimic other linkers behaviors
892 // without understanding why they do that, but because all files
893 // generated by GNU tools have this special GOT value, and because
894 // we've been doing this for years, it is probably a safe bet to
895 // keep doing this for now. We really need to revisit this to see
896 // if we had to do this.
897 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
898 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
Simon Atanasyana0efc422016-11-29 10:23:50 +0000899 Buf += HeaderEntriesNum * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000900 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000901 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000902 size_t PageCount = getMipsPageCount(L.first->Size);
903 uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
904 for (size_t PI = 0; PI < PageCount; ++PI) {
905 uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
906 writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
907 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000908 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000909 Buf += PageEntriesNum * sizeof(uintX_t);
910 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000911 uint8_t *Entry = Buf;
912 Buf += sizeof(uintX_t);
913 const SymbolBody *Body = SA.first;
George Rimarf64618a2017-03-17 11:56:54 +0000914 uintX_t VA = Body->getVA(SA.second);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000915 writeUint<ELFT>(Entry, VA);
916 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000917 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
918 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
919 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000920 // Initialize TLS-related GOT entries. If the entry has a corresponding
921 // dynamic relocations, leave it initialized by zero. Write down adjusted
922 // TLS symbol's values otherwise. To calculate the adjustments use offsets
923 // for thread-local storage.
924 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyama104e2352017-02-14 05:45:47 +0000925 if (TlsIndexOff != -1U && !Config->pic())
Eugene Leviantad4439e2016-11-11 11:33:32 +0000926 writeUint<ELFT>(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000927 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000928 if (!B || B->isPreemptible())
929 continue;
George Rimarf64618a2017-03-17 11:56:54 +0000930 uintX_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000931 if (B->GotIndex != -1U) {
932 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
933 writeUint<ELFT>(Entry, VA - 0x7000);
934 }
935 if (B->GlobalDynIndex != -1U) {
936 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
937 writeUint<ELFT>(Entry, 1);
938 Entry += sizeof(uintX_t);
939 writeUint<ELFT>(Entry, VA - 0x8000);
940 }
941 }
942}
943
George Rimar10f74fc2017-03-15 09:12:56 +0000944GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000945 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
946 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000947
George Rimar10f74fc2017-03-15 09:12:56 +0000948void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000949 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
950 Entries.push_back(&Sym);
951}
952
George Rimar10f74fc2017-03-15 09:12:56 +0000953size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000954 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
955 Target->GotPltEntrySize;
956}
957
George Rimar10f74fc2017-03-15 09:12:56 +0000958void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000959 Target->writeGotPltHeader(Buf);
960 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
961 for (const SymbolBody *B : Entries) {
962 Target->writeGotPlt(Buf, *B);
George Rimar7385d432017-03-16 13:41:29 +0000963 Buf += Config->is64() ? 8 : 4;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000964 }
965}
966
Peter Smithbaffdb82016-12-08 12:58:55 +0000967// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
968// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000969IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000970 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
971 Target->GotPltEntrySize,
972 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000973
George Rimar10f74fc2017-03-15 09:12:56 +0000974void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000975 Sym.IsInIgot = true;
976 Sym.GotPltIndex = Entries.size();
977 Entries.push_back(&Sym);
978}
979
George Rimar10f74fc2017-03-15 09:12:56 +0000980size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000981 return Entries.size() * Target->GotPltEntrySize;
982}
983
George Rimar10f74fc2017-03-15 09:12:56 +0000984void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000985 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000986 Target->writeIgotPlt(Buf, *B);
George Rimar7385d432017-03-16 13:41:29 +0000987 Buf += Config->is64() ? 8 : 4;
Peter Smithbaffdb82016-12-08 12:58:55 +0000988 }
989}
990
George Rimar49648002017-03-15 09:32:36 +0000991StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
992 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000993 Dynamic(Dynamic) {
994 // ELF string tables start with a NUL byte.
995 addString("");
996}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000997
998// Adds a string to the string table. If HashIt is true we hash and check for
999// duplicates. It is optional because the name of global symbols are already
1000// uniqued and hashing them again has a big cost for a small value: uniquing
1001// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +00001002unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001003 if (HashIt) {
1004 auto R = StringMap.insert(std::make_pair(S, this->Size));
1005 if (!R.second)
1006 return R.first->second;
1007 }
1008 unsigned Ret = this->Size;
1009 this->Size = this->Size + S.size() + 1;
1010 Strings.push_back(S);
1011 return Ret;
1012}
1013
George Rimar49648002017-03-15 09:32:36 +00001014void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001015 for (StringRef S : Strings) {
1016 memcpy(Buf, S.data(), S.size());
1017 Buf += S.size() + 1;
1018 }
1019}
1020
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001021// Returns the number of version definition entries. Because the first entry
1022// is for the version definition itself, it is the number of versioned symbols
1023// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001024static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1025
1026template <class ELFT>
1027DynamicSection<ELFT>::DynamicSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001028 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, sizeof(uintX_t),
1029 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001030 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001031
Eugene Leviant6380ce22016-11-15 12:26:55 +00001032 // .dynamic section is not writable on MIPS.
1033 // See "Special Section" in Chapter 4 in the following document:
1034 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1035 if (Config->EMachine == EM_MIPS)
1036 this->Flags = SHF_ALLOC;
1037
1038 addEntries();
1039}
1040
1041// There are some dynamic entries that don't depend on other sections.
1042// Such entries can be set early.
1043template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1044 // Add strings to .dynstr early so that .dynstr's size will be
1045 // fixed early.
1046 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +00001047 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001048 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001049 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001050 In<ELFT>::DynStrTab->addString(Config->RPath)});
1051 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1052 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +00001053 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001054 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001055 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001056
1057 // Set DT_FLAGS and DT_FLAGS_1.
1058 uint32_t DtFlags = 0;
1059 uint32_t DtFlags1 = 0;
1060 if (Config->Bsymbolic)
1061 DtFlags |= DF_SYMBOLIC;
1062 if (Config->ZNodelete)
1063 DtFlags1 |= DF_1_NODELETE;
1064 if (Config->ZNow) {
1065 DtFlags |= DF_BIND_NOW;
1066 DtFlags1 |= DF_1_NOW;
1067 }
1068 if (Config->ZOrigin) {
1069 DtFlags |= DF_ORIGIN;
1070 DtFlags1 |= DF_1_ORIGIN;
1071 }
1072
1073 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001074 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001075 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001076 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001077
Petr Hosek668bebe2016-12-07 02:05:42 +00001078 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +00001079 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001080}
1081
1082// Add remaining entries to complete .dynamic contents.
Rui Ueyama945055a2017-02-27 03:07:41 +00001083template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001084 if (this->Size)
1085 return; // Already finalized.
1086
1087 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001088 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001089 bool IsRela = Config->isRela();
Rui Ueyama729ac792016-11-17 04:10:09 +00001090 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001091 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001092 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001093 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1094
1095 // MIPS dynamic loader does not support RELCOUNT tag.
1096 // The problem is in the tight relation between dynamic
1097 // relocations and GOT. So do not emit this tag on MIPS.
1098 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001099 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001100 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001101 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001102 }
1103 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001104 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001105 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001106 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001107 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001108 In<ELFT>::GotPlt});
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001109 add({DT_PLTREL, uint64_t(Config->isRela() ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001110 }
1111
Eugene Leviant9230db92016-11-17 09:16:34 +00001112 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001113 add({DT_SYMENT, sizeof(Elf_Sym)});
1114 add({DT_STRTAB, In<ELFT>::DynStrTab});
1115 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001116 if (!Config->ZText)
1117 add({DT_TEXTREL, (uint64_t)0});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001118 if (In<ELFT>::GnuHashTab)
1119 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001120 if (In<ELFT>::HashTab)
1121 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001122
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001123 if (Out::PreinitArray) {
1124 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1125 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001126 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001127 if (Out::InitArray) {
1128 add({DT_INIT_ARRAY, Out::InitArray});
1129 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001130 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001131 if (Out::FiniArray) {
1132 add({DT_FINI_ARRAY, Out::FiniArray});
1133 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001134 }
1135
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001136 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001137 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001138 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001139 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001140
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001141 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1142 if (HasVerNeed || In<ELFT>::VerDef)
1143 add({DT_VERSYM, In<ELFT>::VerSym});
1144 if (In<ELFT>::VerDef) {
1145 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001146 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001147 }
1148 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001149 add({DT_VERNEED, In<ELFT>::VerNeed});
1150 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001151 }
1152
1153 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001154 add({DT_MIPS_RLD_VERSION, 1});
1155 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1156 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +00001157 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001158 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1159 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001160 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001161 else
Eugene Leviant9230db92016-11-17 09:16:34 +00001162 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +00001163 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +00001164 if (In<ELFT>::MipsRldMap)
1165 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001166 }
1167
Eugene Leviant6380ce22016-11-15 12:26:55 +00001168 this->OutSec->Link = this->Link;
1169
1170 // +1 for DT_NULL
1171 this->Size = (Entries.size() + 1) * this->Entsize;
1172}
1173
1174template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1175 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1176
1177 for (const Entry &E : Entries) {
1178 P->d_tag = E.Tag;
1179 switch (E.Kind) {
1180 case Entry::SecAddr:
1181 P->d_un.d_ptr = E.OutSec->Addr;
1182 break;
1183 case Entry::InSecAddr:
1184 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1185 break;
1186 case Entry::SecSize:
1187 P->d_un.d_val = E.OutSec->Size;
1188 break;
1189 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001190 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001191 break;
1192 case Entry::PlainInt:
1193 P->d_un.d_val = E.Val;
1194 break;
1195 }
1196 ++P;
1197 }
1198}
1199
George Rimar97def8c2017-03-17 12:07:44 +00001200uint64_t DynamicReloc::getOffset() const {
Rafael Espindolae1294092017-03-08 16:03:41 +00001201 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001202}
1203
George Rimar97def8c2017-03-17 12:07:44 +00001204int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001205 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001206 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001207 return Addend;
1208}
1209
George Rimar97def8c2017-03-17 12:07:44 +00001210uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001211 if (Sym && !UseSymVA)
1212 return Sym->DynsymIndex;
1213 return 0;
1214}
1215
1216template <class ELFT>
1217RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001218 : SyntheticSection(SHF_ALLOC, Config->isRela() ? SHT_RELA : SHT_REL,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001219 sizeof(uintX_t), Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001220 Sort(Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001221 this->Entsize = Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001222}
1223
1224template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001225void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001226 if (Reloc.Type == Target->RelativeRel)
1227 ++NumRelativeRelocs;
1228 Relocs.push_back(Reloc);
1229}
1230
1231template <class ELFT, class RelTy>
1232static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001233 bool AIsRel = A.getType(Config->isMips64EL()) == Target->RelativeRel;
1234 bool BIsRel = B.getType(Config->isMips64EL()) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001235 if (AIsRel != BIsRel)
1236 return AIsRel;
1237
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001238 return A.getSymbol(Config->isMips64EL()) < B.getSymbol(Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001239}
1240
1241template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1242 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001243 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001244 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001245 Buf += Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001246
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001247 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001248 P->r_addend = Rel.getAddend();
1249 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001250 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001251 // Dynamic relocation against MIPS GOT section make deal TLS entries
1252 // allocated in the end of the GOT. We need to adjust the offset to take
1253 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001254 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001255 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001256 }
1257
1258 if (Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001259 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001260 std::stable_sort((Elf_Rela *)BufBegin,
1261 (Elf_Rela *)BufBegin + Relocs.size(),
1262 compRelocations<ELFT, Elf_Rela>);
1263 else
1264 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1265 compRelocations<ELFT, Elf_Rel>);
1266 }
1267}
1268
1269template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1270 return this->Entsize * Relocs.size();
1271}
1272
Rui Ueyama945055a2017-02-27 03:07:41 +00001273template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001274 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1275 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001276
1277 // Set required output section properties.
1278 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001279}
1280
Eugene Leviant9230db92016-11-17 09:16:34 +00001281template <class ELFT>
George Rimar49648002017-03-15 09:32:36 +00001282SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001283 : SyntheticSection(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1284 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1285 sizeof(uintX_t),
1286 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
Eugene Leviant9230db92016-11-17 09:16:34 +00001287 StrTabSec(StrTabSec) {
1288 this->Entsize = sizeof(Elf_Sym);
1289}
1290
1291// Orders symbols according to their positions in the GOT,
1292// in compliance with MIPS ABI rules.
1293// See "Global Offset Table" in Chapter 5 in the following document
1294// for detailed description:
1295// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001296static bool sortMipsSymbols(const SymbolTableEntry &L, const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001297 // Sort entries related to non-local preemptible symbols by GOT indexes.
1298 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001299 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1300 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001301 if (LIsInLocalGot || RIsInLocalGot)
1302 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001303 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001304}
1305
Rui Ueyamabb07d102017-02-27 03:31:19 +00001306// Finalize a symbol table. The ELF spec requires that all local
1307// symbols precede global symbols, so we sort symbol entries in this
1308// function. (For .dynsym, we don't do that because symbols for
1309// dynamic linking are inherently all globals.)
Rui Ueyama945055a2017-02-27 03:07:41 +00001310template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001311 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001312
Rui Ueyama6e967342017-02-28 03:29:12 +00001313 // If it is a .dynsym, there should be no local symbols, but we need
1314 // to do a few things for the dynamic linker.
1315 if (this->Type == SHT_DYNSYM) {
1316 // Section's Info field has the index of the first non-local symbol.
1317 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001318 this->OutSec->Info = 1;
1319
1320 if (In<ELFT>::GnuHashTab) {
1321 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1322 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1323 } else if (Config->EMachine == EM_MIPS) {
1324 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1325 }
1326
1327 size_t I = 0;
1328 for (const SymbolTableEntry &S : Symbols)
1329 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001330 return;
Peter Smith55865432017-02-20 11:12:33 +00001331 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001332}
Peter Smith55865432017-02-20 11:12:33 +00001333
Peter Smith1ec42d92017-03-08 14:06:24 +00001334template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1335 if (this->Type == SHT_DYNSYM)
1336 return;
1337 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001338 auto It = std::stable_partition(
1339 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1340 return S.Symbol->isLocal() ||
1341 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1342 });
1343 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001344 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001345}
1346
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001347template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1348 // Adding a local symbol to a .dynsym is a bug.
1349 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001350
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001351 bool HashIt = B->isLocal();
1352 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001353}
1354
1355template <class ELFT>
1356size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001357 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1358 if (E.Symbol == Body)
1359 return true;
1360 // This is used for -r, so we have to handle multiple section
1361 // symbols being combined.
1362 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001363 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1364 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001365 return false;
1366 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001367 if (I == Symbols.end())
1368 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001369 return I - Symbols.begin() + 1;
1370}
1371
Rui Ueyama1f032532017-02-28 01:56:36 +00001372// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001373template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001374 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001375 Buf += sizeof(Elf_Sym);
1376
Eugene Leviant9230db92016-11-17 09:16:34 +00001377 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001378
Rui Ueyama1f032532017-02-28 01:56:36 +00001379 for (SymbolTableEntry &Ent : Symbols) {
1380 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001381
Rui Ueyama1b003182017-02-28 19:22:09 +00001382 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001383 if (Body->isLocal()) {
1384 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1385 } else {
1386 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1387 ESym->setVisibility(Body->symbol()->Visibility);
1388 }
1389
1390 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001391 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001392
Rui Ueyama1b003182017-02-28 19:22:09 +00001393 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001394 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001395 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001396 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001397 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001398 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001399 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001400
1401 // st_value is usually an address of a symbol, but that has a
1402 // special meaining for uninstantiated common symbols (this can
1403 // occur if -r is given).
1404 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001405 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001406 else
George Rimarf64618a2017-03-17 11:56:54 +00001407 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001408
Rui Ueyama1f032532017-02-28 01:56:36 +00001409 ++ESym;
1410 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001411
Rui Ueyama1f032532017-02-28 01:56:36 +00001412 // On MIPS we need to mark symbol which has a PLT entry and requires
1413 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1414 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1415 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1416 if (Config->EMachine == EM_MIPS) {
1417 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1418
1419 for (SymbolTableEntry &Ent : Symbols) {
1420 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001421 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001422 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001423
1424 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001425 if (auto *D = dyn_cast<DefinedRegular>(Body))
1426 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001427 ESym->st_other |= STO_MIPS_PIC;
1428 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001429 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001430 }
1431}
1432
Rui Ueyamae4120632017-02-28 22:05:13 +00001433// .hash and .gnu.hash sections contain on-disk hash tables that map
1434// symbol names to their dynamic symbol table indices. Their purpose
1435// is to help the dynamic linker resolve symbols quickly. If ELF files
1436// don't have them, the dynamic linker has to do linear search on all
1437// dynamic symbols, which makes programs slower. Therefore, a .hash
1438// section is added to a DSO by default. A .gnu.hash is added if you
1439// give the -hash-style=gnu or -hash-style=both option.
1440//
1441// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1442// Each ELF file has a list of DSOs that the ELF file depends on and a
1443// list of dynamic symbols that need to be resolved from any of the
1444// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1445// where m is the number of DSOs and n is the number of dynamic
1446// symbols. For modern large programs, both m and n are large. So
1447// making each step faster by using hash tables substiantially
1448// improves time to load programs.
1449//
1450// (Note that this is not the only way to design the shared library.
1451// For instance, the Windows DLL takes a different approach. On
1452// Windows, each dynamic symbol has a name of DLL from which the symbol
1453// has to be resolved. That makes the cost of symbol resolution O(n).
1454// This disables some hacky techniques you can use on Unix such as
1455// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1456//
1457// Due to historical reasons, we have two different hash tables, .hash
1458// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1459// and better version of .hash. .hash is just an on-disk hash table, but
1460// .gnu.hash has a bloom filter in addition to a hash table to skip
1461// DSOs very quickly. If you are sure that your dynamic linker knows
1462// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1463// safe bet is to specify -hash-style=both for backward compatibilty.
Eugene Leviant9230db92016-11-17 09:16:34 +00001464template <class ELFT>
Eugene Leviantbe809a72016-11-18 06:44:18 +00001465GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001466 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t), ".gnu.hash") {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001467 this->Entsize = ELFT::Is64Bits ? 0 : 4;
1468}
1469
Rui Ueyama945055a2017-02-27 03:07:41 +00001470template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001471 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001472
1473 // Computes bloom filter size in word size. We want to allocate 8
1474 // bits for each symbol. It must be a power of two.
1475 if (Symbols.empty())
1476 MaskWords = 1;
1477 else
1478 MaskWords = NextPowerOf2((Symbols.size() - 1) / sizeof(uintX_t));
1479
1480 Size = 16; // Header
1481 Size += sizeof(uintX_t) * MaskWords; // Bloom filter
1482 Size += NBuckets * 4; // Hash buckets
1483 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001484}
1485
1486template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001487 // Write a header.
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001488 const endianness E = ELFT::TargetEndianness;
1489 write32<E>(Buf, NBuckets);
1490 write32<E>(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size());
1491 write32<E>(Buf + 8, MaskWords);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001492 write32<E>(Buf + 12, getShift2());
1493 Buf += 16;
1494
Rui Ueyama7986b452017-03-01 18:09:09 +00001495 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001496 writeBloomFilter(Buf);
1497 Buf += sizeof(uintX_t) * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001498 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001499}
1500
Rui Ueyama7986b452017-03-01 18:09:09 +00001501// This function writes a 2-bit bloom filter. This bloom filter alone
1502// usually filters out 80% or more of all symbol lookups [1].
1503// The dynamic linker uses the hash table only when a symbol is not
1504// filtered out by a bloom filter.
1505//
1506// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1507// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
Eugene Leviantbe809a72016-11-18 06:44:18 +00001508template <class ELFT>
Rui Ueyamae13373b2017-03-01 02:51:42 +00001509void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001510 typedef typename ELFT::Off Elf_Off;
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001511 const unsigned C = sizeof(uintX_t) * 8;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001512
Rui Ueyamae13373b2017-03-01 02:51:42 +00001513 auto *Filter = reinterpret_cast<Elf_Off *>(Buf);
1514 for (const Entry &Sym : Symbols) {
1515 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1516 Filter[I] |= uintX_t(1) << (Sym.Hash % C);
1517 Filter[I] |= uintX_t(1) << ((Sym.Hash >> getShift2()) % C);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001518 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001519}
1520
1521template <class ELFT>
1522void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001523 // A 32-bit integer type in the target endianness.
1524 typedef typename ELFT::Word Elf_Word;
1525
Rui Ueyamae13373b2017-03-01 02:51:42 +00001526 // Group symbols by hash value.
1527 std::vector<std::vector<Entry>> Syms(NBuckets);
1528 for (const Entry &Ent : Symbols)
1529 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001530
Rui Ueyamae13373b2017-03-01 02:51:42 +00001531 // Write hash buckets. Hash buckets contain indices in the following
1532 // hash value table.
1533 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1534 for (size_t I = 0; I < NBuckets; ++I)
1535 if (!Syms[I].empty())
1536 Buckets[I] = Syms[I][0].Body->DynsymIndex;
1537
1538 // Write a hash value table. It represents a sequence of chains that
1539 // share the same hash modulo value. The last element of each chain
1540 // is terminated by LSB 1.
1541 Elf_Word *Values = Buckets + NBuckets;
1542 size_t I = 0;
1543 for (std::vector<Entry> &Vec : Syms) {
1544 if (Vec.empty())
1545 continue;
1546 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1547 Values[I++] = Ent.Hash & ~1;
1548 Values[I++] = Vec.back().Hash | 1;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001549 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001550}
1551
1552static uint32_t hashGnu(StringRef Name) {
1553 uint32_t H = 5381;
1554 for (uint8_t C : Name)
1555 H = (H << 5) + H + C;
1556 return H;
1557}
1558
Rui Ueyamae13373b2017-03-01 02:51:42 +00001559// Returns a number of hash buckets to accomodate given number of elements.
1560// We want to choose a moderate number that is not too small (which
1561// causes too many hash collisions) and not too large (which wastes
1562// disk space.)
1563//
1564// We return a prime number because it (is believed to) achieve good
1565// hash distribution.
1566static size_t getBucketSize(size_t NumSymbols) {
1567 // List of largest prime numbers that are not greater than 2^n + 1.
1568 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1569 251, 127, 61, 31, 13, 7, 3, 1})
1570 if (N <= NumSymbols)
1571 return N;
1572 return 0;
1573}
1574
Eugene Leviantbe809a72016-11-18 06:44:18 +00001575// Add symbols to this symbol hash table. Note that this function
1576// destructively sort a given vector -- which is needed because
1577// GNU-style hash table places some sorting requirements.
1578template <class ELFT>
1579void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001580 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1581 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001582 std::vector<SymbolTableEntry>::iterator Mid =
1583 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1584 return S.Symbol->isUndefined();
1585 });
1586 if (Mid == V.end())
1587 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001588
1589 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1590 SymbolBody *B = Ent.Symbol;
1591 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001592 }
1593
Rui Ueyamae13373b2017-03-01 02:51:42 +00001594 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001595 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001596 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001597 return L.Hash % NBuckets < R.Hash % NBuckets;
1598 });
1599
1600 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001601 for (const Entry &Ent : Symbols)
1602 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001603}
1604
Eugene Leviantb96e8092016-11-18 09:06:47 +00001605template <class ELFT>
1606HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001607 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1608 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001609}
1610
Rui Ueyama945055a2017-02-27 03:07:41 +00001611template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001612 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001613
1614 unsigned NumEntries = 2; // nbucket and nchain.
1615 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1616
1617 // Create as many buckets as there are symbols.
1618 // FIXME: This is simplistic. We can try to optimize it, but implementing
1619 // support for SHT_GNU_HASH is probably even more profitable.
1620 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001621 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001622}
1623
1624template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001625 // A 32-bit integer type in the target endianness.
1626 typedef typename ELFT::Word Elf_Word;
1627
Eugene Leviantb96e8092016-11-18 09:06:47 +00001628 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001629
Eugene Leviantb96e8092016-11-18 09:06:47 +00001630 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1631 *P++ = NumSymbols; // nbucket
1632 *P++ = NumSymbols; // nchain
1633
1634 Elf_Word *Buckets = P;
1635 Elf_Word *Chains = P + NumSymbols;
1636
1637 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1638 SymbolBody *Body = S.Symbol;
1639 StringRef Name = Body->getName();
1640 unsigned I = Body->DynsymIndex;
1641 uint32_t Hash = hashSysV(Name) % NumSymbols;
1642 Chains[I] = Buckets[Hash];
1643 Buckets[Hash] = I;
1644 }
1645}
1646
George Rimardfc020e2017-03-17 11:01:57 +00001647PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001648 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001649 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001650
George Rimardfc020e2017-03-17 11:01:57 +00001651void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001652 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1653 // linker to resolve dynsyms at runtime. Write such code.
1654 if (HeaderSize != 0)
1655 Target->writePltHeader(Buf);
1656 size_t Off = HeaderSize;
1657 // The IPlt is immediately after the Plt, account for this in RelOff
1658 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001659
1660 for (auto &I : Entries) {
1661 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001662 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001663 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001664 uint64_t Plt = this->getVA() + Off;
1665 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1666 Off += Target->PltEntrySize;
1667 }
1668}
1669
George Rimardfc020e2017-03-17 11:01:57 +00001670template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001671 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001672 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1673 if (HeaderSize == 0) {
1674 PltRelocSection = In<ELFT>::RelaIplt;
1675 Sym.IsInIplt = true;
1676 }
1677 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001678 Entries.push_back(std::make_pair(&Sym, RelOff));
1679}
1680
George Rimardfc020e2017-03-17 11:01:57 +00001681size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001682 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001683}
1684
Peter Smith96943762017-01-25 10:31:16 +00001685// Some architectures such as additional symbols in the PLT section. For
1686// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001687void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001688 // The PLT may have symbols defined for the Header, the IPLT has no header
1689 if (HeaderSize != 0)
1690 Target->addPltHeaderSymbols(this);
1691 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001692 for (size_t I = 0; I < Entries.size(); ++I) {
1693 Target->addPltSymbols(this, Off);
1694 Off += Target->PltEntrySize;
1695 }
1696}
1697
George Rimardfc020e2017-03-17 11:01:57 +00001698unsigned PltSection::getPltRelocOff() const {
1699 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001700}
1701
Peter Smithbaffdb82016-12-08 12:58:55 +00001702template <class ELFT>
Eugene Levianta113a412016-11-21 09:24:43 +00001703GdbIndexSection<ELFT>::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001704 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001705 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001706
George Rimarec02b8d2016-12-15 12:07:53 +00001707// Iterative hash function for symbol's name is described in .gdb_index format
1708// specification. Note that we use one for version 5 to 7 here, it is different
1709// for version 4.
1710static uint32_t hash(StringRef Str) {
1711 uint32_t R = 0;
1712 for (uint8_t C : Str)
1713 R = R * 67 + tolower(C) - 113;
1714 return R;
1715}
1716
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001717static std::vector<std::pair<uint64_t, uint64_t>>
1718readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1719 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1720 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1721 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1722 return Ret;
1723}
1724
1725template <class ELFT>
1726static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1727 uint64_t Offset) {
1728 for (InputSectionBase *S : Arr)
1729 if (S && S != &InputSection::Discarded)
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001730 if (Offset >= S->getOffsetInFile() &&
1731 Offset < S->getOffsetInFile() + S->getSize())
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001732 return S;
1733 return nullptr;
1734}
1735
1736template <class ELFT>
1737static std::vector<AddressEntry>
1738readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1739 std::vector<AddressEntry> Ret;
1740
1741 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1742 DWARFAddressRangesVector Ranges;
1743 CU->collectAddressRanges(Ranges);
1744
1745 ArrayRef<InputSectionBase *> Sections =
1746 Sec->template getFile<ELFT>()->getSections();
1747
1748 for (std::pair<uint64_t, uint64_t> &R : Ranges)
1749 if (InputSectionBase *S = findSection<ELFT>(Sections, R.first))
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001750 Ret.push_back({S, R.first - S->getOffsetInFile(),
1751 R.second - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001752 ++CurrentCU;
1753 }
1754 return Ret;
1755}
1756
1757static std::vector<std::pair<StringRef, uint8_t>>
1758readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1759 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1760 Dwarf.getGnuPubTypesSection()};
1761
1762 std::vector<std::pair<StringRef, uint8_t>> Ret;
1763 for (StringRef D : Data) {
1764 DWARFDebugPubTable PubTable(D, IsLE, true);
1765 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1766 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1767 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1768 }
1769 return Ret;
1770}
1771
1772class ObjInfoTy : public llvm::LoadedObjectInfo {
1773 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1774 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1775 if (S.getFlags() & ELF::SHF_ALLOC)
1776 return S.getOffset();
1777 return 0;
1778 }
1779
1780 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1781};
1782
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001783template <class ELFT> void GdbIndexSection<ELFT>::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001784 elf::ObjectFile<ELFT> *File = Sec->template getFile<ELFT>();
1785
1786 Expected<std::unique_ptr<object::ObjectFile>> Obj =
1787 object::ObjectFile::createObjectFile(File->MB);
1788 if (!Obj) {
1789 error(toString(File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001790 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001791 }
1792
1793 ObjInfoTy ObjInfo;
1794 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001795
1796 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001797 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1798 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001799
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001800 for (AddressEntry &Ent : readAddressArea<ELFT>(Dwarf, Sec, CuId))
1801 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001802
1803 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001804 readPubNamesAndTypes(Dwarf, ELFT::TargetEndianness == support::little);
George Rimarec02b8d2016-12-15 12:07:53 +00001805
1806 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1807 uint32_t Hash = hash(Pair.first);
1808 size_t Offset = StringPool.add(Pair.first);
1809
1810 bool IsNew;
1811 GdbSymbol *Sym;
1812 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1813 if (IsNew) {
1814 Sym->CuVectorIndex = CuVectors.size();
1815 CuVectors.push_back({{CuId, Pair.second}});
1816 continue;
1817 }
1818
Rui Ueyamaaab18c02017-03-01 22:24:46 +00001819 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
George Rimarec02b8d2016-12-15 12:07:53 +00001820 }
Eugene Levianta113a412016-11-21 09:24:43 +00001821}
1822
Rui Ueyama945055a2017-02-27 03:07:41 +00001823template <class ELFT> void GdbIndexSection<ELFT>::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001824 if (Finalized)
1825 return;
1826 Finalized = true;
1827
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001828 for (InputSectionBase *S : InputSections)
1829 if (InputSection *IS = dyn_cast<InputSection>(S))
1830 if (IS->OutSec && IS->Name == ".debug_info")
1831 readDwarf(IS);
1832
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001833 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001834
1835 // GdbIndex header consist from version fields
1836 // and 5 more fields with different kinds of offsets.
1837 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001838 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001839
1840 ConstantPoolOffset =
1841 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1842
1843 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1844 CuVectorsOffset.push_back(CuVectorsSize);
1845 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1846 }
1847 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1848
1849 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001850}
1851
1852template <class ELFT> size_t GdbIndexSection<ELFT>::getSize() const {
Rui Ueyama945055a2017-02-27 03:07:41 +00001853 const_cast<GdbIndexSection<ELFT> *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001854 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001855}
1856
1857template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001858 write32le(Buf, 7); // Write version.
1859 write32le(Buf + 4, CuListOffset); // CU list offset.
1860 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1861 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1862 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1863 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001864 Buf += 24;
1865
1866 // Write the CU list.
1867 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1868 write64le(Buf, CU.first);
1869 write64le(Buf + 8, CU.second);
1870 Buf += 16;
1871 }
George Rimar8b547392016-12-15 09:08:13 +00001872
1873 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001874 for (AddressEntry &E : AddressArea) {
Rafael Espindolae1294092017-03-08 16:03:41 +00001875 uintX_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001876 write64le(Buf, BaseAddr + E.LowAddress);
1877 write64le(Buf + 8, BaseAddr + E.HighAddress);
1878 write32le(Buf + 16, E.CuIndex);
1879 Buf += 20;
1880 }
George Rimarec02b8d2016-12-15 12:07:53 +00001881
1882 // Write the symbol table.
1883 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1884 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1885 if (Sym) {
1886 size_t NameOffset =
1887 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1888 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1889 write32le(Buf, NameOffset);
1890 write32le(Buf + 4, CuVectorOffset);
1891 }
1892 Buf += 8;
1893 }
1894
1895 // Write the CU vectors into the constant pool.
1896 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1897 write32le(Buf, CuVec.size());
1898 Buf += 4;
1899 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1900 uint32_t Index = P.first;
1901 uint8_t Flags = P.second;
1902 Index |= Flags << 24;
1903 write32le(Buf, Index);
1904 Buf += 4;
1905 }
1906 }
1907
1908 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001909}
1910
George Rimar3fb5a6d2016-11-29 16:05:27 +00001911template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001912 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001913}
1914
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001915template <class ELFT>
1916EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001917 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001918
1919// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1920// Each entry of the search table consists of two values,
1921// the starting PC from where FDEs covers, and the FDE's address.
1922// It is sorted by PC.
1923template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1924 const endianness E = ELFT::TargetEndianness;
1925
1926 // Sort the FDE list by their PC and uniqueify. Usually there is only
1927 // one FDE for a PC (i.e. function), but if ICF merges two functions
1928 // into one, there can be more than one FDEs pointing to the address.
1929 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1930 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1931 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1932 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1933
1934 Buf[0] = 1;
1935 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1936 Buf[2] = DW_EH_PE_udata4;
1937 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001938 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001939 write32<E>(Buf + 8, Fdes.size());
1940 Buf += 12;
1941
1942 uintX_t VA = this->getVA();
1943 for (FdeData &Fde : Fdes) {
1944 write32<E>(Buf, Fde.Pc - VA);
1945 write32<E>(Buf + 4, Fde.FdeVA - VA);
1946 Buf += 8;
1947 }
1948}
1949
1950template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1951 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001952 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001953}
1954
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001955template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001956void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1957 Fdes.push_back({Pc, FdeVA});
1958}
1959
George Rimar11992c862016-11-25 08:05:41 +00001960template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001961 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001962}
1963
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001964template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001965VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001966 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1967 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001968
1969static StringRef getFileDefName() {
1970 if (!Config->SoName.empty())
1971 return Config->SoName;
1972 return Config->OutputFile;
1973}
1974
Rui Ueyama945055a2017-02-27 03:07:41 +00001975template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001976 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1977 for (VersionDefinition &V : Config->VersionDefinitions)
1978 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1979
Rui Ueyamac3726f82017-02-28 04:41:20 +00001980 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001981
1982 // sh_info should be set to the number of definitions. This fact is missed in
1983 // documentation, but confirmed by binutils community:
1984 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001985 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001986}
1987
1988template <class ELFT>
1989void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1990 StringRef Name, size_t NameOff) {
1991 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1992 Verdef->vd_version = 1;
1993 Verdef->vd_cnt = 1;
1994 Verdef->vd_aux = sizeof(Elf_Verdef);
1995 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1996 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1997 Verdef->vd_ndx = Index;
1998 Verdef->vd_hash = hashSysV(Name);
1999
2000 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2001 Verdaux->vda_name = NameOff;
2002 Verdaux->vda_next = 0;
2003}
2004
2005template <class ELFT>
2006void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2007 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2008
2009 for (VersionDefinition &V : Config->VersionDefinitions) {
2010 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2011 writeOne(Buf, V.Id, V.Name, V.NameOff);
2012 }
2013
2014 // Need to terminate the last version definition.
2015 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2016 Verdef->vd_next = 0;
2017}
2018
2019template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2020 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2021}
2022
2023template <class ELFT>
2024VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002025 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002026 ".gnu.version") {
2027 this->Entsize = sizeof(Elf_Versym);
2028}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002029
Rui Ueyama945055a2017-02-27 03:07:41 +00002030template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002031 // At the moment of june 2016 GNU docs does not mention that sh_link field
2032 // should be set, but Sun docs do. Also readelf relies on this field.
Rui Ueyamac3726f82017-02-28 04:41:20 +00002033 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002034}
2035
2036template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2037 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2038}
2039
2040template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2041 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2042 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2043 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2044 ++OutVersym;
2045 }
2046}
2047
George Rimar11992c862016-11-25 08:05:41 +00002048template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2049 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2050}
2051
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002052template <class ELFT>
2053VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002054 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2055 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002056 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2057 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2058 // First identifiers are reserved by verdef section if it exist.
2059 NextIndex = getVerDefNum() + 1;
2060}
2061
2062template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002063void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2064 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2065 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002066 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2067 return;
2068 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002069
2070 auto *File = cast<SharedFile<ELFT>>(SS->File);
2071
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002072 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2073 // to create one by adding it to our needed list and creating a dynstr entry
2074 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002075 if (File->VerdefMap.empty())
2076 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->getSoName())});
2077 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002078 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2079 // prepare to create one by allocating a version identifier and creating a
2080 // dynstr entry for the version name.
2081 if (NV.Index == 0) {
Rui Ueyama4076fa12017-02-26 23:35:34 +00002082 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2083 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002084 NV.Index = NextIndex++;
2085 }
2086 SS->symbol()->VersionId = NV.Index;
2087}
2088
2089template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2090 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2091 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2092 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2093
2094 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2095 // Create an Elf_Verneed for this DSO.
2096 Verneed->vn_version = 1;
2097 Verneed->vn_cnt = P.first->VerdefMap.size();
2098 Verneed->vn_file = P.second;
2099 Verneed->vn_aux =
2100 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2101 Verneed->vn_next = sizeof(Elf_Verneed);
2102 ++Verneed;
2103
2104 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2105 // VerdefMap, which will only contain references to needed version
2106 // definitions. Each Elf_Vernaux is based on the information contained in
2107 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2108 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2109 // data structures within a single input file.
2110 for (auto &NV : P.first->VerdefMap) {
2111 Vernaux->vna_hash = NV.first->vd_hash;
2112 Vernaux->vna_flags = 0;
2113 Vernaux->vna_other = NV.second.Index;
2114 Vernaux->vna_name = NV.second.StrTab;
2115 Vernaux->vna_next = sizeof(Elf_Vernaux);
2116 ++Vernaux;
2117 }
2118
2119 Vernaux[-1].vna_next = 0;
2120 }
2121 Verneed[-1].vn_next = 0;
2122}
2123
Rui Ueyama945055a2017-02-27 03:07:41 +00002124template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00002125 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2126 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002127}
2128
2129template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2130 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2131 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2132 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2133 return Size;
2134}
2135
George Rimar11992c862016-11-25 08:05:41 +00002136template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2137 return getNeedNum() == 0;
2138}
2139
Rafael Espindola6119b862017-03-06 20:23:56 +00002140MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002141 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002142 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002143 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002144
Rafael Espindola6119b862017-03-06 20:23:56 +00002145void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002146 assert(!Finalized);
2147 MS->MergeSec = this;
2148 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002149}
2150
Rafael Espindola6119b862017-03-06 20:23:56 +00002151void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002152
Rafael Espindola6119b862017-03-06 20:23:56 +00002153bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002154 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2155}
2156
Rafael Espindola6119b862017-03-06 20:23:56 +00002157void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002158 // Add all string pieces to the string table builder to create section
2159 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002160 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002161 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2162 if (Sec->Pieces[I].Live)
2163 Builder.add(Sec->getData(I));
2164
2165 // Fix the string table content. After this, the contents will never change.
2166 Builder.finalize();
2167
2168 // finalize() fixed tail-optimized strings, so we can now get
2169 // offsets of strings. Get an offset for each string and save it
2170 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002171 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002172 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2173 if (Sec->Pieces[I].Live)
2174 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2175}
2176
Rafael Espindola6119b862017-03-06 20:23:56 +00002177void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002178 // Add all string pieces to the string table builder to create section
2179 // contents. Because we are not tail-optimizing, offsets of strings are
2180 // fixed when they are added to the builder (string table builder contains
2181 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002182 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002183 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2184 if (Sec->Pieces[I].Live)
2185 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2186
2187 Builder.finalizeInOrder();
2188}
2189
Rafael Espindola6119b862017-03-06 20:23:56 +00002190void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002191 if (Finalized)
2192 return;
2193 Finalized = true;
2194 if (shouldTailMerge())
2195 finalizeTailMerge();
2196 else
2197 finalizeNoTailMerge();
2198}
2199
Rafael Espindola6119b862017-03-06 20:23:56 +00002200size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002201 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002202 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002203 return Builder.getSize();
2204}
2205
George Rimar42886c42017-03-15 12:02:31 +00002206MipsRldMapSection::MipsRldMapSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002207 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
George Rimar7385d432017-03-16 13:41:29 +00002208 Config->is64() ? 8 : 4, ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002209
George Rimar42886c42017-03-15 12:02:31 +00002210void MipsRldMapSection::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00002211 // Apply filler from linker script.
George Rimar42886c42017-03-15 12:02:31 +00002212 uint64_t Filler = ScriptBase->getFiller(this->Name);
Eugene Leviant17b7a572016-11-22 17:49:14 +00002213 Filler = (Filler << 32) | Filler;
2214 memcpy(Buf, &Filler, getSize());
2215}
2216
Peter Smith719eb8e2016-11-24 11:43:55 +00002217template <class ELFT>
2218ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002219 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2220 sizeof(typename ELFT::uint), ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002221
2222// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2223// This section will have been sorted last in the .ARM.exidx table.
2224// This table entry will have the form:
2225// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
George Rimar879a6572016-12-15 15:38:58 +00002226template <class ELFT>
2227void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf) {
Peter Smith719eb8e2016-11-24 11:43:55 +00002228 // Get the InputSection before us, we are by definition last
Rafael Espindola24e6f362017-02-24 15:07:30 +00002229 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002230 InputSection *LE = *(++RI);
2231 InputSection *LC = cast<InputSection>(LE->template getLinkOrderDep<ELFT>());
Rafael Espindolae1294092017-03-08 16:03:41 +00002232 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
Peter Smith719eb8e2016-11-24 11:43:55 +00002233 uint64_t P = this->getVA();
2234 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2235 write32le(Buf + 4, 0x1);
2236}
2237
George Rimar7b827042017-03-16 10:40:50 +00002238ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002239 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
George Rimar7385d432017-03-16 13:41:29 +00002240 Config->is64() ? 8 : 4, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002241 this->OutSec = OS;
2242 this->OutSecOff = Off;
2243}
2244
George Rimar7b827042017-03-16 10:40:50 +00002245void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002246 uint64_t Off = alignTo(Size, T->alignment);
2247 T->Offset = Off;
2248 Thunks.push_back(T);
2249 T->addSymbols(*this);
2250 Size = Off + T->size();
2251}
2252
George Rimar7b827042017-03-16 10:40:50 +00002253void ThunkSection::writeTo(uint8_t *Buf) {
2254 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002255 T->writeTo(Buf + T->Offset, *this);
2256}
2257
George Rimar7b827042017-03-16 10:40:50 +00002258InputSection *ThunkSection::getTargetInputSection() const {
2259 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002260 return T->getTargetInputSection();
2261}
2262
George Rimardfc020e2017-03-17 11:01:57 +00002263namespace lld {
2264namespace elf {
2265template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2266template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2267template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2268template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2269}
2270}
2271
George Rimar9782ca52017-03-15 15:29:29 +00002272InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002273BssSection *InX::Bss;
2274BssSection *InX::BssRelRo;
George Rimar9782ca52017-03-15 15:29:29 +00002275InputSection *InX::Common;
2276StringTableSection *InX::DynStrTab;
2277InputSection *InX::Interp;
2278GotPltSection *InX::GotPlt;
2279IgotPltSection *InX::IgotPlt;
2280MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002281PltSection *InX::Plt;
2282PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002283StringTableSection *InX::ShStrTab;
2284StringTableSection *InX::StrTab;
2285
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002286template InputSection *elf::createCommonSection<ELF32LE>();
2287template InputSection *elf::createCommonSection<ELF32BE>();
2288template InputSection *elf::createCommonSection<ELF64LE>();
2289template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002290
Rafael Espindola6119b862017-03-06 20:23:56 +00002291template MergeInputSection *elf::createCommentSection<ELF32LE>();
2292template MergeInputSection *elf::createCommentSection<ELF32BE>();
2293template MergeInputSection *elf::createCommentSection<ELF64LE>();
2294template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002295
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002296template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002297 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002298 InputSectionBase *);
2299template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002300 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002301 InputSectionBase *);
2302template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002303 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002304 InputSectionBase *);
2305template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002306 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002307 InputSectionBase *);
Peter Smith96943762017-01-25 10:31:16 +00002308
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002309template class elf::MipsAbiFlagsSection<ELF32LE>;
2310template class elf::MipsAbiFlagsSection<ELF32BE>;
2311template class elf::MipsAbiFlagsSection<ELF64LE>;
2312template class elf::MipsAbiFlagsSection<ELF64BE>;
2313
Simon Atanasyance02cf02016-11-09 21:36:56 +00002314template class elf::MipsOptionsSection<ELF32LE>;
2315template class elf::MipsOptionsSection<ELF32BE>;
2316template class elf::MipsOptionsSection<ELF64LE>;
2317template class elf::MipsOptionsSection<ELF64BE>;
2318
2319template class elf::MipsReginfoSection<ELF32LE>;
2320template class elf::MipsReginfoSection<ELF32BE>;
2321template class elf::MipsReginfoSection<ELF64LE>;
2322template class elf::MipsReginfoSection<ELF64BE>;
2323
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00002324template class elf::BuildIdSection<ELF32LE>;
2325template class elf::BuildIdSection<ELF32BE>;
2326template class elf::BuildIdSection<ELF64LE>;
2327template class elf::BuildIdSection<ELF64BE>;
2328
Eugene Leviantad4439e2016-11-11 11:33:32 +00002329template class elf::GotSection<ELF32LE>;
2330template class elf::GotSection<ELF32BE>;
2331template class elf::GotSection<ELF64LE>;
2332template class elf::GotSection<ELF64BE>;
2333
Simon Atanasyan725dc142016-11-16 21:01:02 +00002334template class elf::MipsGotSection<ELF32LE>;
2335template class elf::MipsGotSection<ELF32BE>;
2336template class elf::MipsGotSection<ELF64LE>;
2337template class elf::MipsGotSection<ELF64BE>;
2338
Eugene Leviant6380ce22016-11-15 12:26:55 +00002339template class elf::DynamicSection<ELF32LE>;
2340template class elf::DynamicSection<ELF32BE>;
2341template class elf::DynamicSection<ELF64LE>;
2342template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002343
2344template class elf::RelocationSection<ELF32LE>;
2345template class elf::RelocationSection<ELF32BE>;
2346template class elf::RelocationSection<ELF64LE>;
2347template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002348
2349template class elf::SymbolTableSection<ELF32LE>;
2350template class elf::SymbolTableSection<ELF32BE>;
2351template class elf::SymbolTableSection<ELF64LE>;
2352template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002353
2354template class elf::GnuHashTableSection<ELF32LE>;
2355template class elf::GnuHashTableSection<ELF32BE>;
2356template class elf::GnuHashTableSection<ELF64LE>;
2357template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002358
2359template class elf::HashTableSection<ELF32LE>;
2360template class elf::HashTableSection<ELF32BE>;
2361template class elf::HashTableSection<ELF64LE>;
2362template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002363
Eugene Levianta113a412016-11-21 09:24:43 +00002364template class elf::GdbIndexSection<ELF32LE>;
2365template class elf::GdbIndexSection<ELF32BE>;
2366template class elf::GdbIndexSection<ELF64LE>;
2367template class elf::GdbIndexSection<ELF64BE>;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002368
2369template class elf::EhFrameHeader<ELF32LE>;
2370template class elf::EhFrameHeader<ELF32BE>;
2371template class elf::EhFrameHeader<ELF64LE>;
2372template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002373
2374template class elf::VersionTableSection<ELF32LE>;
2375template class elf::VersionTableSection<ELF32BE>;
2376template class elf::VersionTableSection<ELF64LE>;
2377template class elf::VersionTableSection<ELF64BE>;
2378
2379template class elf::VersionNeedSection<ELF32LE>;
2380template class elf::VersionNeedSection<ELF32BE>;
2381template class elf::VersionNeedSection<ELF64LE>;
2382template class elf::VersionNeedSection<ELF64BE>;
2383
2384template class elf::VersionDefinitionSection<ELF32LE>;
2385template class elf::VersionDefinitionSection<ELF32BE>;
2386template class elf::VersionDefinitionSection<ELF64LE>;
2387template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002388
Peter Smith719eb8e2016-11-24 11:43:55 +00002389template class elf::ARMExidxSentinelSection<ELF32LE>;
2390template class elf::ARMExidxSentinelSection<ELF32BE>;
2391template class elf::ARMExidxSentinelSection<ELF64LE>;
2392template class elf::ARMExidxSentinelSection<ELF64BE>;
Peter Smith3a52eb02017-02-01 10:26:03 +00002393
Rafael Espindola66b4e212017-02-23 22:06:28 +00002394template class elf::EhFrameSection<ELF32LE>;
2395template class elf::EhFrameSection<ELF32BE>;
2396template class elf::EhFrameSection<ELF64LE>;
2397template class elf::EhFrameSection<ELF64BE>;