blob: 7c1c203d0e68ca299a287db5e62f6577d804d4e4 [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() {
66 auto *Ret = make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 1,
67 ArrayRef<uint8_t>(), "COMMON");
Rafael Espindola682a5bc2016-11-08 14:42:34 +000068 Ret->Live = true;
Rui Ueyamae8a61022016-11-05 23:05:47 +000069
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000070 if (!Config->DefineCommon)
71 return Ret;
72
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
80 // Assign offsets to symbols.
81 size_t Size = 0;
Rafael Espindola48200602017-03-15 12:43:54 +000082 uint32_t Alignment = 1;
Rui Ueyamae8a61022016-11-05 23:05:47 +000083 for (DefinedCommon *Sym : Syms) {
Rafael Espindola48200602017-03-15 12:43:54 +000084 Alignment = std::max(Alignment, Sym->Alignment);
Rui Ueyamae8a61022016-11-05 23:05:47 +000085 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 }
Rafael Espindola682a5bc2016-11-08 14:42:34 +000091 Ret->Alignment = Alignment;
92 Ret->Data = makeArrayRef<uint8_t>(nullptr, Size);
93 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 Rimar47bed8c2017-03-16 08:44:53 +0000379template <class ELFT>
380CopyRelSection<ELFT>::CopyRelSection(bool ReadOnly, uint32_t Alignment,
381 size_t S)
382 : SyntheticSection(SHF_ALLOC, SHT_NOBITS, Alignment,
383 ReadOnly ? ".bss.rel.ro" : ".bss"),
384 Size(S) {}
Peter Smithebfe9942017-02-09 10:27:57 +0000385
386template <class ELFT>
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000387void BuildIdSection<ELFT>::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000388 switch (Config->BuildId) {
389 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000390 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000391 write64le(Dest, xxHash64(toStringRef(Arr)));
392 });
393 break;
394 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000395 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000396 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000397 });
398 break;
399 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000400 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000401 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000402 });
403 break;
404 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000405 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000406 error("entropy source failure");
407 break;
408 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000409 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000410 break;
411 default:
412 llvm_unreachable("unknown BuildIdKind");
413 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000414}
415
Eugene Leviant41ca3272016-11-10 09:48:29 +0000416template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000417EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000418 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000419
420// Search for an existing CIE record or create a new one.
421// CIE records from input object files are uniquified by their contents
422// and where their relocations point to.
423template <class ELFT>
424template <class RelTy>
425CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
426 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000427 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000428 const endianness E = ELFT::TargetEndianness;
429 if (read32<E>(Piece.data().data() + 4) != 0)
430 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
431
432 SymbolBody *Personality = nullptr;
433 unsigned FirstRelI = Piece.FirstRelocation;
434 if (FirstRelI != (unsigned)-1)
435 Personality =
436 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
437
438 // Search for an existing CIE by CIE contents/relocation target pair.
439 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
440
441 // If not found, create a new one.
442 if (Cie->Piece == nullptr) {
443 Cie->Piece = &Piece;
444 Cies.push_back(Cie);
445 }
446 return Cie;
447}
448
449// There is one FDE per function. Returns true if a given FDE
450// points to a live function.
451template <class ELFT>
452template <class RelTy>
453bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
454 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000455 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000456 unsigned FirstRelI = Piece.FirstRelocation;
457 if (FirstRelI == (unsigned)-1)
458 return false;
459 const RelTy &Rel = Rels[FirstRelI];
460 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000461 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000462 if (!D || !D->Section)
463 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000464 auto *Target =
465 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000466 return Target && Target->Live;
467}
468
469// .eh_frame is a sequence of CIE or FDE records. In general, there
470// is one CIE record per input object file which is followed by
471// a list of FDEs. This function searches an existing CIE or create a new
472// one and associates FDEs to the CIE.
473template <class ELFT>
474template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000475void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000476 ArrayRef<RelTy> Rels) {
477 const endianness E = ELFT::TargetEndianness;
478
479 DenseMap<size_t, CieRecord *> OffsetToCie;
480 for (EhSectionPiece &Piece : Sec->Pieces) {
481 // The empty record is the end marker.
482 if (Piece.size() == 4)
483 return;
484
485 size_t Offset = Piece.InputOff;
486 uint32_t ID = read32<E>(Piece.data().data() + 4);
487 if (ID == 0) {
488 OffsetToCie[Offset] = addCie(Piece, Rels);
489 continue;
490 }
491
492 uint32_t CieOffset = Offset + 4 - ID;
493 CieRecord *Cie = OffsetToCie[CieOffset];
494 if (!Cie)
495 fatal(toString(Sec) + ": invalid CIE reference");
496
497 if (!isFdeLive(Piece, Rels))
498 continue;
499 Cie->FdePieces.push_back(&Piece);
500 NumFdes++;
501 }
502}
503
504template <class ELFT>
505void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000506 auto *Sec = cast<EhInputSection>(C);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000507 Sec->EHSec = this;
508 updateAlignment(Sec->Alignment);
509 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000510 for (auto *DS : Sec->DependentSections)
511 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000512
513 // .eh_frame is a sequence of CIE or FDE records. This function
514 // splits it into pieces so that we can call
515 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000516 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000517 if (Sec->Pieces.empty())
518 return;
519
520 if (Sec->NumRelocations) {
521 if (Sec->AreRelocsRela)
522 addSectionAux(Sec, Sec->template relas<ELFT>());
523 else
524 addSectionAux(Sec, Sec->template rels<ELFT>());
525 return;
526 }
527 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
528}
529
530template <class ELFT>
531static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
532 memcpy(Buf, D.data(), D.size());
533
534 // Fix the size field. -4 since size does not include the size field itself.
535 const endianness E = ELFT::TargetEndianness;
536 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
537}
538
Rui Ueyama945055a2017-02-27 03:07:41 +0000539template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000540 if (this->Size)
541 return; // Already finalized.
542
543 size_t Off = 0;
544 for (CieRecord *Cie : Cies) {
545 Cie->Piece->OutputOff = Off;
546 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
547
548 for (EhSectionPiece *Fde : Cie->FdePieces) {
549 Fde->OutputOff = Off;
550 Off += alignTo(Fde->size(), sizeof(uintX_t));
551 }
552 }
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000553 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000554}
555
556template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
557 const endianness E = ELFT::TargetEndianness;
558 switch (Size) {
559 case DW_EH_PE_udata2:
560 return read16<E>(Buf);
561 case DW_EH_PE_udata4:
562 return read32<E>(Buf);
563 case DW_EH_PE_udata8:
564 return read64<E>(Buf);
565 case DW_EH_PE_absptr:
566 if (ELFT::Is64Bits)
567 return read64<E>(Buf);
568 return read32<E>(Buf);
569 }
570 fatal("unknown FDE size encoding");
571}
572
573// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
574// We need it to create .eh_frame_hdr section.
575template <class ELFT>
576typename ELFT::uint EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
577 uint8_t Enc) {
578 // The starting address to which this FDE applies is
579 // stored at FDE + 8 byte.
580 size_t Off = FdeOff + 8;
581 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
582 if ((Enc & 0x70) == DW_EH_PE_absptr)
583 return Addr;
584 if ((Enc & 0x70) == DW_EH_PE_pcrel)
585 return Addr + this->OutSec->Addr + Off;
586 fatal("unknown FDE size relative encoding");
587}
588
589template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
590 const endianness E = ELFT::TargetEndianness;
591 for (CieRecord *Cie : Cies) {
592 size_t CieOffset = Cie->Piece->OutputOff;
593 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
594
595 for (EhSectionPiece *Fde : Cie->FdePieces) {
596 size_t Off = Fde->OutputOff;
597 writeCieFde<ELFT>(Buf + Off, Fde->data());
598
599 // FDE's second word should have the offset to an associated CIE.
600 // Write it.
601 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
602 }
603 }
604
Rafael Espindola5c02b742017-03-06 21:17:18 +0000605 for (EhInputSection *S : Sections)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000606 S->template relocate<ELFT>(Buf, nullptr);
607
608 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
609 // to get a FDE from an address to which FDE is applied. So here
610 // we obtain two addresses and pass them to EhFrameHdr object.
611 if (In<ELFT>::EhFrameHdr) {
612 for (CieRecord *Cie : Cies) {
613 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
614 for (SectionPiece *Fde : Cie->FdePieces) {
615 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
616 uintX_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
617 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
618 }
619 }
620 }
621}
622
623template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000624GotSection<ELFT>::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000625 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
626 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000627
628template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000629 Sym.GotIndex = NumEntries;
630 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000631}
632
Simon Atanasyan725dc142016-11-16 21:01:02 +0000633template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
634 if (Sym.GlobalDynIndex != -1U)
635 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000636 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000637 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000638 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000639 return true;
640}
641
642// Reserves TLS entries for a TLS module ID and a TLS block offset.
643// In total it takes two GOT slots.
644template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
645 if (TlsIndexOff != uint32_t(-1))
646 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000647 TlsIndexOff = NumEntries * sizeof(uintX_t);
648 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000649 return true;
650}
651
Eugene Leviantad4439e2016-11-11 11:33:32 +0000652template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000653typename GotSection<ELFT>::uintX_t
654GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
655 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
656}
657
658template <class ELFT>
659typename GotSection<ELFT>::uintX_t
660GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
661 return B.GlobalDynIndex * sizeof(uintX_t);
662}
663
Rui Ueyama945055a2017-02-27 03:07:41 +0000664template <class ELFT> void GotSection<ELFT>::finalizeContents() {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000665 Size = NumEntries * sizeof(uintX_t);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000666}
667
George Rimar11992c862016-11-25 08:05:41 +0000668template <class ELFT> bool GotSection<ELFT>::empty() const {
669 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
670 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000671 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000672}
673
Simon Atanasyan725dc142016-11-16 21:01:02 +0000674template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000675 this->template relocate<ELFT>(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000676}
677
678template <class ELFT>
679MipsGotSection<ELFT>::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000680 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
681 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000682
683template <class ELFT>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000684void MipsGotSection<ELFT>::addEntry(SymbolBody &Sym, int64_t Addend,
Eugene Leviantad4439e2016-11-11 11:33:32 +0000685 RelExpr Expr) {
686 // For "true" local symbols which can be referenced from the same module
687 // only compiler creates two instructions for address loading:
688 //
689 // lw $8, 0($gp) # R_MIPS_GOT16
690 // addi $8, $8, 0 # R_MIPS_LO16
691 //
692 // The first instruction loads high 16 bits of the symbol address while
693 // the second adds an offset. That allows to reduce number of required
694 // GOT entries because only one global offset table entry is necessary
695 // for every 64 KBytes of local data. So for local symbols we need to
696 // allocate number of GOT entries to hold all required "page" addresses.
697 //
698 // All global symbols (hidden and regular) considered by compiler uniformly.
699 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
700 // to load address of the symbol. So for each such symbol we need to
701 // allocate dedicated GOT entry to store its address.
702 //
703 // If a symbol is preemptible we need help of dynamic linker to get its
704 // final address. The corresponding GOT entries are allocated in the
705 // "global" part of GOT. Entries for non preemptible global symbol allocated
706 // in the "local" part of GOT.
707 //
708 // See "Global Offset Table" in Chapter 5:
709 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
710 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
711 // At this point we do not know final symbol value so to reduce number
712 // of allocated GOT entries do the following trick. Save all output
713 // sections referenced by GOT relocations. Then later in the `finalize`
714 // method calculate number of "pages" required to cover all saved output
715 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000716 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000717 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 return;
719 }
720 if (Sym.isTls()) {
721 // GOT entries created for MIPS TLS relocations behave like
722 // almost GOT entries from other ABIs. They go to the end
723 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000724 Sym.GotIndex = TlsEntries.size();
725 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 return;
727 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000728 auto AddEntry = [&](SymbolBody &S, uintX_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 if (S.isInGot() && !A)
730 return;
731 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000732 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000733 return;
734 Items.emplace_back(&S, A);
735 if (!A)
736 S.GotIndex = NewIndex;
737 };
738 if (Sym.isPreemptible()) {
739 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000740 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000741 Sym.IsInGlobalMipsGot = true;
742 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000743 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000744 Sym.Is32BitMipsGot = true;
745 } else {
746 // Hold local GOT entries accessed via a 16-bit index separately.
747 // That allows to write them in the beginning of the GOT and keep
748 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000749 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000750 }
751}
752
George Rimar879a6572016-12-15 15:38:58 +0000753template <class ELFT>
754bool MipsGotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000755 if (Sym.GlobalDynIndex != -1U)
756 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000757 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000758 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000759 TlsEntries.push_back(nullptr);
760 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000761 return true;
762}
763
764// Reserves TLS entries for a TLS module ID and a TLS block offset.
765// In total it takes two GOT slots.
Simon Atanasyan725dc142016-11-16 21:01:02 +0000766template <class ELFT> bool MipsGotSection<ELFT>::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000767 if (TlsIndexOff != uint32_t(-1))
768 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000769 TlsIndexOff = TlsEntries.size() * sizeof(uintX_t);
770 TlsEntries.push_back(nullptr);
771 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000772 return true;
773}
774
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000775static uint64_t getMipsPageAddr(uint64_t Addr) {
776 return (Addr + 0x8000) & ~0xffff;
777}
778
779static uint64_t getMipsPageCount(uint64_t Size) {
780 return (Size + 0xfffe) / 0xffff + 1;
781}
782
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000784typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000785MipsGotSection<ELFT>::getPageEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000786 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000787 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000788 cast<DefinedRegular>(&B)->Section->getOutputSection();
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000789 uintX_t SecAddr = getMipsPageAddr(OutSec->Addr);
790 uintX_t SymAddr = getMipsPageAddr(B.getVA<ELFT>(Addend));
791 uintX_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
792 assert(Index < PageEntriesNum);
793 return (HeaderEntriesNum + Index) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794}
795
796template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000797typename MipsGotSection<ELFT>::uintX_t
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000798MipsGotSection<ELFT>::getBodyEntryOffset(const SymbolBody &B,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000799 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000800 // Calculate offset of the GOT entries block: TLS, global, local.
Simon Atanasyana0efc422016-11-29 10:23:50 +0000801 uintX_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000802 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000803 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000805 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000806 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000807 Index += LocalEntries.size();
808 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000809 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000810 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000811 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000812 auto It = EntryIndexMap.find({&B, Addend});
813 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000814 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000815 }
Simon Atanasyana0efc422016-11-29 10:23:50 +0000816 return Index * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000817}
818
819template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000820typename MipsGotSection<ELFT>::uintX_t
821MipsGotSection<ELFT>::getTlsOffset() const {
822 return (getLocalEntriesNum() + GlobalEntries.size()) * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000823}
824
825template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000826typename MipsGotSection<ELFT>::uintX_t
827MipsGotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000828 return B.GlobalDynIndex * sizeof(uintX_t);
829}
830
831template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000832const SymbolBody *MipsGotSection<ELFT>::getFirstGlobalEntry() const {
833 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000834}
835
836template <class ELFT>
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000837unsigned MipsGotSection<ELFT>::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000838 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
839 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000840}
841
Rui Ueyama945055a2017-02-27 03:07:41 +0000842template <class ELFT> void MipsGotSection<ELFT>::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000843 updateAllocSize();
844}
845
846template <class ELFT> void MipsGotSection<ELFT>::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000847 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000848 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000849 // For each output section referenced by GOT page relocations calculate
850 // and save into PageIndexMap an upper bound of MIPS GOT entries required
851 // to store page addresses of local symbols. We assume the worst case -
852 // each 64kb page of the output section has at least one GOT relocation
853 // against it. And take in account the case when the section intersects
854 // page boundaries.
855 P.second = PageEntriesNum;
856 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000857 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000858 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
859 sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000860}
861
George Rimar11992c862016-11-25 08:05:41 +0000862template <class ELFT> bool MipsGotSection<ELFT>::empty() const {
863 // We add the .got section to the result for dynamic MIPS target because
864 // its address and properties are mentioned in the .dynamic section.
865 return Config->Relocatable;
866}
867
Simon Atanasyanb9666652016-12-12 14:30:18 +0000868template <class ELFT>
869typename MipsGotSection<ELFT>::uintX_t MipsGotSection<ELFT>::getGp() const {
Rui Ueyama80474a22017-02-28 19:29:55 +0000870 return ElfSym::MipsGp->template getVA<ELFT>(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000871}
872
Eugene Leviantad4439e2016-11-11 11:33:32 +0000873template <class ELFT>
874static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
875 typedef typename ELFT::uint uintX_t;
876 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
877}
878
Simon Atanasyan725dc142016-11-16 21:01:02 +0000879template <class ELFT> void MipsGotSection<ELFT>::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000880 // Set the MSB of the second GOT slot. This is not required by any
881 // MIPS ABI documentation, though.
882 //
883 // There is a comment in glibc saying that "The MSB of got[1] of a
884 // gnu object is set to identify gnu objects," and in GNU gold it
885 // says "the second entry will be used by some runtime loaders".
886 // But how this field is being used is unclear.
887 //
888 // We are not really willing to mimic other linkers behaviors
889 // without understanding why they do that, but because all files
890 // generated by GNU tools have this special GOT value, and because
891 // we've been doing this for years, it is probably a safe bet to
892 // keep doing this for now. We really need to revisit this to see
893 // if we had to do this.
894 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
895 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
Simon Atanasyana0efc422016-11-29 10:23:50 +0000896 Buf += HeaderEntriesNum * sizeof(uintX_t);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000897 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000898 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000899 size_t PageCount = getMipsPageCount(L.first->Size);
900 uintX_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
901 for (size_t PI = 0; PI < PageCount; ++PI) {
902 uint8_t *Entry = Buf + (L.second + PI) * sizeof(uintX_t);
903 writeUint<ELFT>(Entry, FirstPageAddr + PI * 0x10000);
904 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000905 }
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000906 Buf += PageEntriesNum * sizeof(uintX_t);
907 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000908 uint8_t *Entry = Buf;
909 Buf += sizeof(uintX_t);
910 const SymbolBody *Body = SA.first;
911 uintX_t VA = Body->template getVA<ELFT>(SA.second);
912 writeUint<ELFT>(Entry, VA);
913 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000914 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
915 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
916 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000917 // Initialize TLS-related GOT entries. If the entry has a corresponding
918 // dynamic relocations, leave it initialized by zero. Write down adjusted
919 // TLS symbol's values otherwise. To calculate the adjustments use offsets
920 // for thread-local storage.
921 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyama104e2352017-02-14 05:45:47 +0000922 if (TlsIndexOff != -1U && !Config->pic())
Eugene Leviantad4439e2016-11-11 11:33:32 +0000923 writeUint<ELFT>(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000924 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000925 if (!B || B->isPreemptible())
926 continue;
927 uintX_t VA = B->getVA<ELFT>();
928 if (B->GotIndex != -1U) {
929 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
930 writeUint<ELFT>(Entry, VA - 0x7000);
931 }
932 if (B->GlobalDynIndex != -1U) {
933 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
934 writeUint<ELFT>(Entry, 1);
935 Entry += sizeof(uintX_t);
936 writeUint<ELFT>(Entry, VA - 0x8000);
937 }
938 }
939}
940
George Rimar10f74fc2017-03-15 09:12:56 +0000941GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000942 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
943 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000944
George Rimar10f74fc2017-03-15 09:12:56 +0000945void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000946 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
947 Entries.push_back(&Sym);
948}
949
George Rimar10f74fc2017-03-15 09:12:56 +0000950size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000951 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
952 Target->GotPltEntrySize;
953}
954
George Rimar10f74fc2017-03-15 09:12:56 +0000955void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000956 Target->writeGotPltHeader(Buf);
957 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
958 for (const SymbolBody *B : Entries) {
959 Target->writeGotPlt(Buf, *B);
George Rimar10f74fc2017-03-15 09:12:56 +0000960 Buf += Config->is64Bit() ? 8 : 4;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000961 }
962}
963
Peter Smithbaffdb82016-12-08 12:58:55 +0000964// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
965// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000966IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000967 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
968 Target->GotPltEntrySize,
969 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000970
George Rimar10f74fc2017-03-15 09:12:56 +0000971void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000972 Sym.IsInIgot = true;
973 Sym.GotPltIndex = Entries.size();
974 Entries.push_back(&Sym);
975}
976
George Rimar10f74fc2017-03-15 09:12:56 +0000977size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000978 return Entries.size() * Target->GotPltEntrySize;
979}
980
George Rimar10f74fc2017-03-15 09:12:56 +0000981void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000982 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000983 Target->writeIgotPlt(Buf, *B);
George Rimar10f74fc2017-03-15 09:12:56 +0000984 Buf += Config->is64Bit() ? 8 : 4;
Peter Smithbaffdb82016-12-08 12:58:55 +0000985 }
986}
987
George Rimar49648002017-03-15 09:32:36 +0000988StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
989 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000990 Dynamic(Dynamic) {
991 // ELF string tables start with a NUL byte.
992 addString("");
993}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000994
995// Adds a string to the string table. If HashIt is true we hash and check for
996// duplicates. It is optional because the name of global symbols are already
997// uniqued and hashing them again has a big cost for a small value: uniquing
998// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000999unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001000 if (HashIt) {
1001 auto R = StringMap.insert(std::make_pair(S, this->Size));
1002 if (!R.second)
1003 return R.first->second;
1004 }
1005 unsigned Ret = this->Size;
1006 this->Size = this->Size + S.size() + 1;
1007 Strings.push_back(S);
1008 return Ret;
1009}
1010
George Rimar49648002017-03-15 09:32:36 +00001011void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001012 for (StringRef S : Strings) {
1013 memcpy(Buf, S.data(), S.size());
1014 Buf += S.size() + 1;
1015 }
1016}
1017
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001018// Returns the number of version definition entries. Because the first entry
1019// is for the version definition itself, it is the number of versioned symbols
1020// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001021static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1022
1023template <class ELFT>
1024DynamicSection<ELFT>::DynamicSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001025 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, sizeof(uintX_t),
1026 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001027 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001028
Eugene Leviant6380ce22016-11-15 12:26:55 +00001029 // .dynamic section is not writable on MIPS.
1030 // See "Special Section" in Chapter 4 in the following document:
1031 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1032 if (Config->EMachine == EM_MIPS)
1033 this->Flags = SHF_ALLOC;
1034
1035 addEntries();
1036}
1037
1038// There are some dynamic entries that don't depend on other sections.
1039// Such entries can be set early.
1040template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1041 // Add strings to .dynstr early so that .dynstr's size will be
1042 // fixed early.
1043 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +00001044 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001045 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001046 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001047 In<ELFT>::DynStrTab->addString(Config->RPath)});
1048 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1049 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +00001050 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001051 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001052 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001053
1054 // Set DT_FLAGS and DT_FLAGS_1.
1055 uint32_t DtFlags = 0;
1056 uint32_t DtFlags1 = 0;
1057 if (Config->Bsymbolic)
1058 DtFlags |= DF_SYMBOLIC;
1059 if (Config->ZNodelete)
1060 DtFlags1 |= DF_1_NODELETE;
1061 if (Config->ZNow) {
1062 DtFlags |= DF_BIND_NOW;
1063 DtFlags1 |= DF_1_NOW;
1064 }
1065 if (Config->ZOrigin) {
1066 DtFlags |= DF_ORIGIN;
1067 DtFlags1 |= DF_1_ORIGIN;
1068 }
1069
1070 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001071 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001072 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001073 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001074
Petr Hosek668bebe2016-12-07 02:05:42 +00001075 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +00001076 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001077}
1078
1079// Add remaining entries to complete .dynamic contents.
Rui Ueyama945055a2017-02-27 03:07:41 +00001080template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001081 if (this->Size)
1082 return; // Already finalized.
1083
1084 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001085 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001086 bool IsRela = Config->isRela();
Rui Ueyama729ac792016-11-17 04:10:09 +00001087 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001088 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001089 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001090 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1091
1092 // MIPS dynamic loader does not support RELCOUNT tag.
1093 // The problem is in the tight relation between dynamic
1094 // relocations and GOT. So do not emit this tag on MIPS.
1095 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001096 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001097 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001098 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001099 }
1100 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001101 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001102 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001103 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001104 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001105 In<ELFT>::GotPlt});
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001106 add({DT_PLTREL, uint64_t(Config->isRela() ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001107 }
1108
Eugene Leviant9230db92016-11-17 09:16:34 +00001109 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001110 add({DT_SYMENT, sizeof(Elf_Sym)});
1111 add({DT_STRTAB, In<ELFT>::DynStrTab});
1112 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001113 if (!Config->ZText)
1114 add({DT_TEXTREL, (uint64_t)0});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001115 if (In<ELFT>::GnuHashTab)
1116 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001117 if (In<ELFT>::HashTab)
1118 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001119
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001120 if (Out::PreinitArray) {
1121 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1122 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001123 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001124 if (Out::InitArray) {
1125 add({DT_INIT_ARRAY, Out::InitArray});
1126 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001127 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001128 if (Out::FiniArray) {
1129 add({DT_FINI_ARRAY, Out::FiniArray});
1130 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001131 }
1132
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001133 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001134 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001135 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001136 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001137
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001138 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139 if (HasVerNeed || In<ELFT>::VerDef)
1140 add({DT_VERSYM, In<ELFT>::VerSym});
1141 if (In<ELFT>::VerDef) {
1142 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001143 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001144 }
1145 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001146 add({DT_VERNEED, In<ELFT>::VerNeed});
1147 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001148 }
1149
1150 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001151 add({DT_MIPS_RLD_VERSION, 1});
1152 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1153 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +00001154 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001155 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1156 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001157 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001158 else
Eugene Leviant9230db92016-11-17 09:16:34 +00001159 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +00001160 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +00001161 if (In<ELFT>::MipsRldMap)
1162 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001163 }
1164
Eugene Leviant6380ce22016-11-15 12:26:55 +00001165 this->OutSec->Link = this->Link;
1166
1167 // +1 for DT_NULL
1168 this->Size = (Entries.size() + 1) * this->Entsize;
1169}
1170
1171template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1172 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1173
1174 for (const Entry &E : Entries) {
1175 P->d_tag = E.Tag;
1176 switch (E.Kind) {
1177 case Entry::SecAddr:
1178 P->d_un.d_ptr = E.OutSec->Addr;
1179 break;
1180 case Entry::InSecAddr:
1181 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1182 break;
1183 case Entry::SecSize:
1184 P->d_un.d_val = E.OutSec->Size;
1185 break;
1186 case Entry::SymAddr:
1187 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
1188 break;
1189 case Entry::PlainInt:
1190 P->d_un.d_val = E.Val;
1191 break;
1192 }
1193 ++P;
1194 }
1195}
1196
Eugene Levianta96d9022016-11-16 10:02:27 +00001197template <class ELFT>
George Rimarf00c1832017-03-16 12:20:19 +00001198uint64_t DynamicReloc<ELFT>::getOffset() const {
Rafael Espindolae1294092017-03-08 16:03:41 +00001199 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001200}
1201
Rafael Espindola7386cea2017-02-16 00:12:34 +00001202template <class ELFT> int64_t DynamicReloc<ELFT>::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001203 if (UseSymVA)
1204 return Sym->getVA<ELFT>(Addend);
1205 return Addend;
1206}
1207
1208template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
1209 if (Sym && !UseSymVA)
1210 return Sym->DynsymIndex;
1211 return 0;
1212}
1213
1214template <class ELFT>
1215RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001216 : SyntheticSection(SHF_ALLOC, Config->isRela() ? SHT_RELA : SHT_REL,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001217 sizeof(uintX_t), Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001218 Sort(Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001219 this->Entsize = Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001220}
1221
1222template <class ELFT>
1223void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
1224 if (Reloc.Type == Target->RelativeRel)
1225 ++NumRelativeRelocs;
1226 Relocs.push_back(Reloc);
1227}
1228
1229template <class ELFT, class RelTy>
1230static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001231 bool AIsRel = A.getType(Config->isMips64EL()) == Target->RelativeRel;
1232 bool BIsRel = B.getType(Config->isMips64EL()) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001233 if (AIsRel != BIsRel)
1234 return AIsRel;
1235
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001236 return A.getSymbol(Config->isMips64EL()) < B.getSymbol(Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001237}
1238
1239template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1240 uint8_t *BufBegin = Buf;
1241 for (const DynamicReloc<ELFT> &Rel : Relocs) {
1242 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001243 Buf += Config->isRela() ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001244
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001245 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001246 P->r_addend = Rel.getAddend();
1247 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001248 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001249 // Dynamic relocation against MIPS GOT section make deal TLS entries
1250 // allocated in the end of the GOT. We need to adjust the offset to take
1251 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001252 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Rui Ueyamadf8eb172017-03-07 00:43:33 +00001253 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->isMips64EL());
Eugene Levianta96d9022016-11-16 10:02:27 +00001254 }
1255
1256 if (Sort) {
Rui Ueyamaaf6198d2017-03-07 00:43:53 +00001257 if (Config->isRela())
Eugene Levianta96d9022016-11-16 10:02:27 +00001258 std::stable_sort((Elf_Rela *)BufBegin,
1259 (Elf_Rela *)BufBegin + Relocs.size(),
1260 compRelocations<ELFT, Elf_Rela>);
1261 else
1262 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1263 compRelocations<ELFT, Elf_Rel>);
1264 }
1265}
1266
1267template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1268 return this->Entsize * Relocs.size();
1269}
1270
Rui Ueyama945055a2017-02-27 03:07:41 +00001271template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001272 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1273 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001274
1275 // Set required output section properties.
1276 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001277}
1278
Eugene Leviant9230db92016-11-17 09:16:34 +00001279template <class ELFT>
George Rimar49648002017-03-15 09:32:36 +00001280SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001281 : SyntheticSection(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1282 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1283 sizeof(uintX_t),
1284 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
Eugene Leviant9230db92016-11-17 09:16:34 +00001285 StrTabSec(StrTabSec) {
1286 this->Entsize = sizeof(Elf_Sym);
1287}
1288
1289// Orders symbols according to their positions in the GOT,
1290// in compliance with MIPS ABI rules.
1291// See "Global Offset Table" in Chapter 5 in the following document
1292// for detailed description:
1293// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001294static bool sortMipsSymbols(const SymbolTableEntry &L, const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001295 // Sort entries related to non-local preemptible symbols by GOT indexes.
1296 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001297 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1298 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001299 if (LIsInLocalGot || RIsInLocalGot)
1300 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001301 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001302}
1303
Rui Ueyamabb07d102017-02-27 03:31:19 +00001304// Finalize a symbol table. The ELF spec requires that all local
1305// symbols precede global symbols, so we sort symbol entries in this
1306// function. (For .dynsym, we don't do that because symbols for
1307// dynamic linking are inherently all globals.)
Rui Ueyama945055a2017-02-27 03:07:41 +00001308template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001309 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001310
Rui Ueyama6e967342017-02-28 03:29:12 +00001311 // If it is a .dynsym, there should be no local symbols, but we need
1312 // to do a few things for the dynamic linker.
1313 if (this->Type == SHT_DYNSYM) {
1314 // Section's Info field has the index of the first non-local symbol.
1315 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001316 this->OutSec->Info = 1;
1317
1318 if (In<ELFT>::GnuHashTab) {
1319 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1320 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1321 } else if (Config->EMachine == EM_MIPS) {
1322 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1323 }
1324
1325 size_t I = 0;
1326 for (const SymbolTableEntry &S : Symbols)
1327 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001328 return;
Peter Smith55865432017-02-20 11:12:33 +00001329 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001330}
Peter Smith55865432017-02-20 11:12:33 +00001331
Peter Smith1ec42d92017-03-08 14:06:24 +00001332template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1333 if (this->Type == SHT_DYNSYM)
1334 return;
1335 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001336 auto It = std::stable_partition(
1337 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1338 return S.Symbol->isLocal() ||
1339 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1340 });
1341 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001342 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001343}
1344
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001345template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1346 // Adding a local symbol to a .dynsym is a bug.
1347 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001348
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001349 bool HashIt = B->isLocal();
1350 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001351}
1352
1353template <class ELFT>
1354size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001355 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1356 if (E.Symbol == Body)
1357 return true;
1358 // This is used for -r, so we have to handle multiple section
1359 // symbols being combined.
1360 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001361 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1362 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001363 return false;
1364 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001365 if (I == Symbols.end())
1366 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001367 return I - Symbols.begin() + 1;
1368}
1369
Rui Ueyama1f032532017-02-28 01:56:36 +00001370// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001371template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001372 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001373 Buf += sizeof(Elf_Sym);
1374
Eugene Leviant9230db92016-11-17 09:16:34 +00001375 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001376
Rui Ueyama1f032532017-02-28 01:56:36 +00001377 for (SymbolTableEntry &Ent : Symbols) {
1378 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001379
Rui Ueyama1b003182017-02-28 19:22:09 +00001380 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001381 if (Body->isLocal()) {
1382 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1383 } else {
1384 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1385 ESym->setVisibility(Body->symbol()->Visibility);
1386 }
1387
1388 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001389 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001390
Rui Ueyama1b003182017-02-28 19:22:09 +00001391 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001392 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001393 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001394 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001395 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001396 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001397 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001398
1399 // st_value is usually an address of a symbol, but that has a
1400 // special meaining for uninstantiated common symbols (this can
1401 // occur if -r is given).
1402 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001403 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001404 else
1405 ESym->st_value = Body->getVA<ELFT>();
1406
Rui Ueyama1f032532017-02-28 01:56:36 +00001407 ++ESym;
1408 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001409
Rui Ueyama1f032532017-02-28 01:56:36 +00001410 // On MIPS we need to mark symbol which has a PLT entry and requires
1411 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1412 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1413 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1414 if (Config->EMachine == EM_MIPS) {
1415 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1416
1417 for (SymbolTableEntry &Ent : Symbols) {
1418 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001419 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001420 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001421
1422 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001423 if (auto *D = dyn_cast<DefinedRegular>(Body))
1424 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001425 ESym->st_other |= STO_MIPS_PIC;
1426 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001427 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001428 }
1429}
1430
Rui Ueyamae4120632017-02-28 22:05:13 +00001431// .hash and .gnu.hash sections contain on-disk hash tables that map
1432// symbol names to their dynamic symbol table indices. Their purpose
1433// is to help the dynamic linker resolve symbols quickly. If ELF files
1434// don't have them, the dynamic linker has to do linear search on all
1435// dynamic symbols, which makes programs slower. Therefore, a .hash
1436// section is added to a DSO by default. A .gnu.hash is added if you
1437// give the -hash-style=gnu or -hash-style=both option.
1438//
1439// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1440// Each ELF file has a list of DSOs that the ELF file depends on and a
1441// list of dynamic symbols that need to be resolved from any of the
1442// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1443// where m is the number of DSOs and n is the number of dynamic
1444// symbols. For modern large programs, both m and n are large. So
1445// making each step faster by using hash tables substiantially
1446// improves time to load programs.
1447//
1448// (Note that this is not the only way to design the shared library.
1449// For instance, the Windows DLL takes a different approach. On
1450// Windows, each dynamic symbol has a name of DLL from which the symbol
1451// has to be resolved. That makes the cost of symbol resolution O(n).
1452// This disables some hacky techniques you can use on Unix such as
1453// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1454//
1455// Due to historical reasons, we have two different hash tables, .hash
1456// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1457// and better version of .hash. .hash is just an on-disk hash table, but
1458// .gnu.hash has a bloom filter in addition to a hash table to skip
1459// DSOs very quickly. If you are sure that your dynamic linker knows
1460// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1461// safe bet is to specify -hash-style=both for backward compatibilty.
Eugene Leviant9230db92016-11-17 09:16:34 +00001462template <class ELFT>
Eugene Leviantbe809a72016-11-18 06:44:18 +00001463GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001464 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t), ".gnu.hash") {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001465 this->Entsize = ELFT::Is64Bits ? 0 : 4;
1466}
1467
Rui Ueyama945055a2017-02-27 03:07:41 +00001468template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001469 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001470
1471 // Computes bloom filter size in word size. We want to allocate 8
1472 // bits for each symbol. It must be a power of two.
1473 if (Symbols.empty())
1474 MaskWords = 1;
1475 else
1476 MaskWords = NextPowerOf2((Symbols.size() - 1) / sizeof(uintX_t));
1477
1478 Size = 16; // Header
1479 Size += sizeof(uintX_t) * MaskWords; // Bloom filter
1480 Size += NBuckets * 4; // Hash buckets
1481 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001482}
1483
1484template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001485 // Write a header.
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001486 const endianness E = ELFT::TargetEndianness;
1487 write32<E>(Buf, NBuckets);
1488 write32<E>(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size());
1489 write32<E>(Buf + 8, MaskWords);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001490 write32<E>(Buf + 12, getShift2());
1491 Buf += 16;
1492
Rui Ueyama7986b452017-03-01 18:09:09 +00001493 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001494 writeBloomFilter(Buf);
1495 Buf += sizeof(uintX_t) * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001496 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001497}
1498
Rui Ueyama7986b452017-03-01 18:09:09 +00001499// This function writes a 2-bit bloom filter. This bloom filter alone
1500// usually filters out 80% or more of all symbol lookups [1].
1501// The dynamic linker uses the hash table only when a symbol is not
1502// filtered out by a bloom filter.
1503//
1504// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1505// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
Eugene Leviantbe809a72016-11-18 06:44:18 +00001506template <class ELFT>
Rui Ueyamae13373b2017-03-01 02:51:42 +00001507void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001508 typedef typename ELFT::Off Elf_Off;
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001509 const unsigned C = sizeof(uintX_t) * 8;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001510
Rui Ueyamae13373b2017-03-01 02:51:42 +00001511 auto *Filter = reinterpret_cast<Elf_Off *>(Buf);
1512 for (const Entry &Sym : Symbols) {
1513 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1514 Filter[I] |= uintX_t(1) << (Sym.Hash % C);
1515 Filter[I] |= uintX_t(1) << ((Sym.Hash >> getShift2()) % C);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001516 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001517}
1518
1519template <class ELFT>
1520void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001521 // A 32-bit integer type in the target endianness.
1522 typedef typename ELFT::Word Elf_Word;
1523
Rui Ueyamae13373b2017-03-01 02:51:42 +00001524 // Group symbols by hash value.
1525 std::vector<std::vector<Entry>> Syms(NBuckets);
1526 for (const Entry &Ent : Symbols)
1527 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001528
Rui Ueyamae13373b2017-03-01 02:51:42 +00001529 // Write hash buckets. Hash buckets contain indices in the following
1530 // hash value table.
1531 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1532 for (size_t I = 0; I < NBuckets; ++I)
1533 if (!Syms[I].empty())
1534 Buckets[I] = Syms[I][0].Body->DynsymIndex;
1535
1536 // Write a hash value table. It represents a sequence of chains that
1537 // share the same hash modulo value. The last element of each chain
1538 // is terminated by LSB 1.
1539 Elf_Word *Values = Buckets + NBuckets;
1540 size_t I = 0;
1541 for (std::vector<Entry> &Vec : Syms) {
1542 if (Vec.empty())
1543 continue;
1544 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1545 Values[I++] = Ent.Hash & ~1;
1546 Values[I++] = Vec.back().Hash | 1;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001547 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001548}
1549
1550static uint32_t hashGnu(StringRef Name) {
1551 uint32_t H = 5381;
1552 for (uint8_t C : Name)
1553 H = (H << 5) + H + C;
1554 return H;
1555}
1556
Rui Ueyamae13373b2017-03-01 02:51:42 +00001557// Returns a number of hash buckets to accomodate given number of elements.
1558// We want to choose a moderate number that is not too small (which
1559// causes too many hash collisions) and not too large (which wastes
1560// disk space.)
1561//
1562// We return a prime number because it (is believed to) achieve good
1563// hash distribution.
1564static size_t getBucketSize(size_t NumSymbols) {
1565 // List of largest prime numbers that are not greater than 2^n + 1.
1566 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1567 251, 127, 61, 31, 13, 7, 3, 1})
1568 if (N <= NumSymbols)
1569 return N;
1570 return 0;
1571}
1572
Eugene Leviantbe809a72016-11-18 06:44:18 +00001573// Add symbols to this symbol hash table. Note that this function
1574// destructively sort a given vector -- which is needed because
1575// GNU-style hash table places some sorting requirements.
1576template <class ELFT>
1577void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001578 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1579 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001580 std::vector<SymbolTableEntry>::iterator Mid =
1581 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1582 return S.Symbol->isUndefined();
1583 });
1584 if (Mid == V.end())
1585 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001586
1587 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1588 SymbolBody *B = Ent.Symbol;
1589 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001590 }
1591
Rui Ueyamae13373b2017-03-01 02:51:42 +00001592 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001593 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001594 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001595 return L.Hash % NBuckets < R.Hash % NBuckets;
1596 });
1597
1598 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001599 for (const Entry &Ent : Symbols)
1600 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001601}
1602
Eugene Leviantb96e8092016-11-18 09:06:47 +00001603template <class ELFT>
1604HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001605 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1606 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001607}
1608
Rui Ueyama945055a2017-02-27 03:07:41 +00001609template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001610 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001611
1612 unsigned NumEntries = 2; // nbucket and nchain.
1613 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1614
1615 // Create as many buckets as there are symbols.
1616 // FIXME: This is simplistic. We can try to optimize it, but implementing
1617 // support for SHT_GNU_HASH is probably even more profitable.
1618 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001619 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001620}
1621
1622template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001623 // A 32-bit integer type in the target endianness.
1624 typedef typename ELFT::Word Elf_Word;
1625
Eugene Leviantb96e8092016-11-18 09:06:47 +00001626 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001627
Eugene Leviantb96e8092016-11-18 09:06:47 +00001628 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1629 *P++ = NumSymbols; // nbucket
1630 *P++ = NumSymbols; // nchain
1631
1632 Elf_Word *Buckets = P;
1633 Elf_Word *Chains = P + NumSymbols;
1634
1635 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1636 SymbolBody *Body = S.Symbol;
1637 StringRef Name = Body->getName();
1638 unsigned I = Body->DynsymIndex;
1639 uint32_t Hash = hashSysV(Name) % NumSymbols;
1640 Chains[I] = Buckets[Hash];
1641 Buckets[Hash] = I;
1642 }
1643}
1644
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001645template <class ELFT>
Peter Smithf09245a2017-02-09 10:56:15 +00001646PltSection<ELFT>::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001647 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001648 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001649
1650template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001651 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1652 // linker to resolve dynsyms at runtime. Write such code.
1653 if (HeaderSize != 0)
1654 Target->writePltHeader(Buf);
1655 size_t Off = HeaderSize;
1656 // The IPlt is immediately after the Plt, account for this in RelOff
1657 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001658
1659 for (auto &I : Entries) {
1660 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001661 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001662 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001663 uint64_t Plt = this->getVA() + Off;
1664 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1665 Off += Target->PltEntrySize;
1666 }
1667}
1668
1669template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
1670 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001671 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1672 if (HeaderSize == 0) {
1673 PltRelocSection = In<ELFT>::RelaIplt;
1674 Sym.IsInIplt = true;
1675 }
1676 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001677 Entries.push_back(std::make_pair(&Sym, RelOff));
1678}
1679
1680template <class ELFT> size_t PltSection<ELFT>::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001681 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001682}
1683
Peter Smith96943762017-01-25 10:31:16 +00001684// Some architectures such as additional symbols in the PLT section. For
1685// example ARM uses mapping symbols to aid disassembly
1686template <class ELFT> void PltSection<ELFT>::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001687 // The PLT may have symbols defined for the Header, the IPLT has no header
1688 if (HeaderSize != 0)
1689 Target->addPltHeaderSymbols(this);
1690 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001691 for (size_t I = 0; I < Entries.size(); ++I) {
1692 Target->addPltSymbols(this, Off);
1693 Off += Target->PltEntrySize;
1694 }
1695}
1696
Peter Smithf09245a2017-02-09 10:56:15 +00001697template <class ELFT> unsigned PltSection<ELFT>::getPltRelocOff() const {
1698 return (HeaderSize == 0) ? In<ELFT>::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001699}
1700
Peter Smithbaffdb82016-12-08 12:58:55 +00001701template <class ELFT>
Eugene Levianta113a412016-11-21 09:24:43 +00001702GdbIndexSection<ELFT>::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001703 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001704 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001705
George Rimarec02b8d2016-12-15 12:07:53 +00001706// Iterative hash function for symbol's name is described in .gdb_index format
1707// specification. Note that we use one for version 5 to 7 here, it is different
1708// for version 4.
1709static uint32_t hash(StringRef Str) {
1710 uint32_t R = 0;
1711 for (uint8_t C : Str)
1712 R = R * 67 + tolower(C) - 113;
1713 return R;
1714}
1715
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001716static std::vector<std::pair<uint64_t, uint64_t>>
1717readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1718 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1719 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1720 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1721 return Ret;
1722}
1723
1724template <class ELFT>
1725static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1726 uint64_t Offset) {
1727 for (InputSectionBase *S : Arr)
1728 if (S && S != &InputSection::Discarded)
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001729 if (Offset >= S->getOffsetInFile() &&
1730 Offset < S->getOffsetInFile() + S->getSize())
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001731 return S;
1732 return nullptr;
1733}
1734
1735template <class ELFT>
1736static std::vector<AddressEntry>
1737readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1738 std::vector<AddressEntry> Ret;
1739
1740 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1741 DWARFAddressRangesVector Ranges;
1742 CU->collectAddressRanges(Ranges);
1743
1744 ArrayRef<InputSectionBase *> Sections =
1745 Sec->template getFile<ELFT>()->getSections();
1746
1747 for (std::pair<uint64_t, uint64_t> &R : Ranges)
1748 if (InputSectionBase *S = findSection<ELFT>(Sections, R.first))
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001749 Ret.push_back({S, R.first - S->getOffsetInFile(),
1750 R.second - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001751 ++CurrentCU;
1752 }
1753 return Ret;
1754}
1755
1756static std::vector<std::pair<StringRef, uint8_t>>
1757readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1758 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1759 Dwarf.getGnuPubTypesSection()};
1760
1761 std::vector<std::pair<StringRef, uint8_t>> Ret;
1762 for (StringRef D : Data) {
1763 DWARFDebugPubTable PubTable(D, IsLE, true);
1764 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1765 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1766 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1767 }
1768 return Ret;
1769}
1770
1771class ObjInfoTy : public llvm::LoadedObjectInfo {
1772 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1773 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1774 if (S.getFlags() & ELF::SHF_ALLOC)
1775 return S.getOffset();
1776 return 0;
1777 }
1778
1779 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1780};
1781
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001782template <class ELFT> void GdbIndexSection<ELFT>::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001783 elf::ObjectFile<ELFT> *File = Sec->template getFile<ELFT>();
1784
1785 Expected<std::unique_ptr<object::ObjectFile>> Obj =
1786 object::ObjectFile::createObjectFile(File->MB);
1787 if (!Obj) {
1788 error(toString(File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001789 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001790 }
1791
1792 ObjInfoTy ObjInfo;
1793 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001794
1795 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001796 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1797 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001798
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001799 for (AddressEntry &Ent : readAddressArea<ELFT>(Dwarf, Sec, CuId))
1800 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001801
1802 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001803 readPubNamesAndTypes(Dwarf, ELFT::TargetEndianness == support::little);
George Rimarec02b8d2016-12-15 12:07:53 +00001804
1805 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1806 uint32_t Hash = hash(Pair.first);
1807 size_t Offset = StringPool.add(Pair.first);
1808
1809 bool IsNew;
1810 GdbSymbol *Sym;
1811 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1812 if (IsNew) {
1813 Sym->CuVectorIndex = CuVectors.size();
1814 CuVectors.push_back({{CuId, Pair.second}});
1815 continue;
1816 }
1817
Rui Ueyamaaab18c02017-03-01 22:24:46 +00001818 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
George Rimarec02b8d2016-12-15 12:07:53 +00001819 }
Eugene Levianta113a412016-11-21 09:24:43 +00001820}
1821
Rui Ueyama945055a2017-02-27 03:07:41 +00001822template <class ELFT> void GdbIndexSection<ELFT>::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001823 if (Finalized)
1824 return;
1825 Finalized = true;
1826
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001827 for (InputSectionBase *S : InputSections)
1828 if (InputSection *IS = dyn_cast<InputSection>(S))
1829 if (IS->OutSec && IS->Name == ".debug_info")
1830 readDwarf(IS);
1831
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001832 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001833
1834 // GdbIndex header consist from version fields
1835 // and 5 more fields with different kinds of offsets.
1836 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001837 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001838
1839 ConstantPoolOffset =
1840 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1841
1842 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1843 CuVectorsOffset.push_back(CuVectorsSize);
1844 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1845 }
1846 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1847
1848 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001849}
1850
1851template <class ELFT> size_t GdbIndexSection<ELFT>::getSize() const {
Rui Ueyama945055a2017-02-27 03:07:41 +00001852 const_cast<GdbIndexSection<ELFT> *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001853 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001854}
1855
1856template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001857 write32le(Buf, 7); // Write version.
1858 write32le(Buf + 4, CuListOffset); // CU list offset.
1859 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1860 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1861 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1862 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001863 Buf += 24;
1864
1865 // Write the CU list.
1866 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
1867 write64le(Buf, CU.first);
1868 write64le(Buf + 8, CU.second);
1869 Buf += 16;
1870 }
George Rimar8b547392016-12-15 09:08:13 +00001871
1872 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001873 for (AddressEntry &E : AddressArea) {
Rafael Espindolae1294092017-03-08 16:03:41 +00001874 uintX_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001875 write64le(Buf, BaseAddr + E.LowAddress);
1876 write64le(Buf + 8, BaseAddr + E.HighAddress);
1877 write32le(Buf + 16, E.CuIndex);
1878 Buf += 20;
1879 }
George Rimarec02b8d2016-12-15 12:07:53 +00001880
1881 // Write the symbol table.
1882 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1883 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1884 if (Sym) {
1885 size_t NameOffset =
1886 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1887 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1888 write32le(Buf, NameOffset);
1889 write32le(Buf + 4, CuVectorOffset);
1890 }
1891 Buf += 8;
1892 }
1893
1894 // Write the CU vectors into the constant pool.
1895 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1896 write32le(Buf, CuVec.size());
1897 Buf += 4;
1898 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1899 uint32_t Index = P.first;
1900 uint8_t Flags = P.second;
1901 Index |= Flags << 24;
1902 write32le(Buf, Index);
1903 Buf += 4;
1904 }
1905 }
1906
1907 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001908}
1909
George Rimar3fb5a6d2016-11-29 16:05:27 +00001910template <class ELFT> bool GdbIndexSection<ELFT>::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001911 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001912}
1913
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001914template <class ELFT>
1915EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001916 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001917
1918// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1919// Each entry of the search table consists of two values,
1920// the starting PC from where FDEs covers, and the FDE's address.
1921// It is sorted by PC.
1922template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1923 const endianness E = ELFT::TargetEndianness;
1924
1925 // Sort the FDE list by their PC and uniqueify. Usually there is only
1926 // one FDE for a PC (i.e. function), but if ICF merges two functions
1927 // into one, there can be more than one FDEs pointing to the address.
1928 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1929 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1930 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1931 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1932
1933 Buf[0] = 1;
1934 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1935 Buf[2] = DW_EH_PE_udata4;
1936 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001937 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001938 write32<E>(Buf + 8, Fdes.size());
1939 Buf += 12;
1940
1941 uintX_t VA = this->getVA();
1942 for (FdeData &Fde : Fdes) {
1943 write32<E>(Buf, Fde.Pc - VA);
1944 write32<E>(Buf + 4, Fde.FdeVA - VA);
1945 Buf += 8;
1946 }
1947}
1948
1949template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1950 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001951 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001952}
1953
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001954template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001955void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1956 Fdes.push_back({Pc, FdeVA});
1957}
1958
George Rimar11992c862016-11-25 08:05:41 +00001959template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001960 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001961}
1962
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001963template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001964VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001965 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1966 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001967
1968static StringRef getFileDefName() {
1969 if (!Config->SoName.empty())
1970 return Config->SoName;
1971 return Config->OutputFile;
1972}
1973
Rui Ueyama945055a2017-02-27 03:07:41 +00001974template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001975 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1976 for (VersionDefinition &V : Config->VersionDefinitions)
1977 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1978
Rui Ueyamac3726f82017-02-28 04:41:20 +00001979 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001980
1981 // sh_info should be set to the number of definitions. This fact is missed in
1982 // documentation, but confirmed by binutils community:
1983 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001984 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001985}
1986
1987template <class ELFT>
1988void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1989 StringRef Name, size_t NameOff) {
1990 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1991 Verdef->vd_version = 1;
1992 Verdef->vd_cnt = 1;
1993 Verdef->vd_aux = sizeof(Elf_Verdef);
1994 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1995 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1996 Verdef->vd_ndx = Index;
1997 Verdef->vd_hash = hashSysV(Name);
1998
1999 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2000 Verdaux->vda_name = NameOff;
2001 Verdaux->vda_next = 0;
2002}
2003
2004template <class ELFT>
2005void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2006 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2007
2008 for (VersionDefinition &V : Config->VersionDefinitions) {
2009 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2010 writeOne(Buf, V.Id, V.Name, V.NameOff);
2011 }
2012
2013 // Need to terminate the last version definition.
2014 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2015 Verdef->vd_next = 0;
2016}
2017
2018template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2019 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2020}
2021
2022template <class ELFT>
2023VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002024 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002025 ".gnu.version") {
2026 this->Entsize = sizeof(Elf_Versym);
2027}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002028
Rui Ueyama945055a2017-02-27 03:07:41 +00002029template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002030 // At the moment of june 2016 GNU docs does not mention that sh_link field
2031 // should be set, but Sun docs do. Also readelf relies on this field.
Rui Ueyamac3726f82017-02-28 04:41:20 +00002032 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002033}
2034
2035template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2036 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2037}
2038
2039template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2040 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2041 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2042 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2043 ++OutVersym;
2044 }
2045}
2046
George Rimar11992c862016-11-25 08:05:41 +00002047template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2048 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2049}
2050
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002051template <class ELFT>
2052VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002053 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2054 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002055 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2056 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2057 // First identifiers are reserved by verdef section if it exist.
2058 NextIndex = getVerDefNum() + 1;
2059}
2060
2061template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002062void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2063 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2064 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002065 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2066 return;
2067 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002068
2069 auto *File = cast<SharedFile<ELFT>>(SS->File);
2070
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002071 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2072 // to create one by adding it to our needed list and creating a dynstr entry
2073 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002074 if (File->VerdefMap.empty())
2075 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->getSoName())});
2076 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002077 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2078 // prepare to create one by allocating a version identifier and creating a
2079 // dynstr entry for the version name.
2080 if (NV.Index == 0) {
Rui Ueyama4076fa12017-02-26 23:35:34 +00002081 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2082 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002083 NV.Index = NextIndex++;
2084 }
2085 SS->symbol()->VersionId = NV.Index;
2086}
2087
2088template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2089 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2090 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2091 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2092
2093 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2094 // Create an Elf_Verneed for this DSO.
2095 Verneed->vn_version = 1;
2096 Verneed->vn_cnt = P.first->VerdefMap.size();
2097 Verneed->vn_file = P.second;
2098 Verneed->vn_aux =
2099 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2100 Verneed->vn_next = sizeof(Elf_Verneed);
2101 ++Verneed;
2102
2103 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2104 // VerdefMap, which will only contain references to needed version
2105 // definitions. Each Elf_Vernaux is based on the information contained in
2106 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2107 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2108 // data structures within a single input file.
2109 for (auto &NV : P.first->VerdefMap) {
2110 Vernaux->vna_hash = NV.first->vd_hash;
2111 Vernaux->vna_flags = 0;
2112 Vernaux->vna_other = NV.second.Index;
2113 Vernaux->vna_name = NV.second.StrTab;
2114 Vernaux->vna_next = sizeof(Elf_Vernaux);
2115 ++Vernaux;
2116 }
2117
2118 Vernaux[-1].vna_next = 0;
2119 }
2120 Verneed[-1].vn_next = 0;
2121}
2122
Rui Ueyama945055a2017-02-27 03:07:41 +00002123template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00002124 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2125 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002126}
2127
2128template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2129 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2130 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2131 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2132 return Size;
2133}
2134
George Rimar11992c862016-11-25 08:05:41 +00002135template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2136 return getNeedNum() == 0;
2137}
2138
Rafael Espindola6119b862017-03-06 20:23:56 +00002139MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002140 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002141 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002142 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002143
Rafael Espindola6119b862017-03-06 20:23:56 +00002144void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002145 assert(!Finalized);
2146 MS->MergeSec = this;
2147 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002148}
2149
Rafael Espindola6119b862017-03-06 20:23:56 +00002150void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002151
Rafael Espindola6119b862017-03-06 20:23:56 +00002152bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002153 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2154}
2155
Rafael Espindola6119b862017-03-06 20:23:56 +00002156void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002157 // Add all string pieces to the string table builder to create section
2158 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002159 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002160 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2161 if (Sec->Pieces[I].Live)
2162 Builder.add(Sec->getData(I));
2163
2164 // Fix the string table content. After this, the contents will never change.
2165 Builder.finalize();
2166
2167 // finalize() fixed tail-optimized strings, so we can now get
2168 // offsets of strings. Get an offset for each string and save it
2169 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002170 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002171 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2172 if (Sec->Pieces[I].Live)
2173 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2174}
2175
Rafael Espindola6119b862017-03-06 20:23:56 +00002176void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002177 // Add all string pieces to the string table builder to create section
2178 // contents. Because we are not tail-optimizing, offsets of strings are
2179 // fixed when they are added to the builder (string table builder contains
2180 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002181 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002182 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2183 if (Sec->Pieces[I].Live)
2184 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2185
2186 Builder.finalizeInOrder();
2187}
2188
Rafael Espindola6119b862017-03-06 20:23:56 +00002189void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002190 if (Finalized)
2191 return;
2192 Finalized = true;
2193 if (shouldTailMerge())
2194 finalizeTailMerge();
2195 else
2196 finalizeNoTailMerge();
2197}
2198
Rafael Espindola6119b862017-03-06 20:23:56 +00002199size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002200 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002201 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002202 return Builder.getSize();
2203}
2204
George Rimar42886c42017-03-15 12:02:31 +00002205MipsRldMapSection::MipsRldMapSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002206 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
George Rimar42886c42017-03-15 12:02:31 +00002207 Config->is64Bit() ? 8 : 4, ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002208
George Rimar42886c42017-03-15 12:02:31 +00002209void MipsRldMapSection::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00002210 // Apply filler from linker script.
George Rimar42886c42017-03-15 12:02:31 +00002211 uint64_t Filler = ScriptBase->getFiller(this->Name);
Eugene Leviant17b7a572016-11-22 17:49:14 +00002212 Filler = (Filler << 32) | Filler;
2213 memcpy(Buf, &Filler, getSize());
2214}
2215
Peter Smith719eb8e2016-11-24 11:43:55 +00002216template <class ELFT>
2217ARMExidxSentinelSection<ELFT>::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002218 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
2219 sizeof(typename ELFT::uint), ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002220
2221// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2222// This section will have been sorted last in the .ARM.exidx table.
2223// This table entry will have the form:
2224// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
George Rimar879a6572016-12-15 15:38:58 +00002225template <class ELFT>
2226void ARMExidxSentinelSection<ELFT>::writeTo(uint8_t *Buf) {
Peter Smith719eb8e2016-11-24 11:43:55 +00002227 // Get the InputSection before us, we are by definition last
Rafael Espindola24e6f362017-02-24 15:07:30 +00002228 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002229 InputSection *LE = *(++RI);
2230 InputSection *LC = cast<InputSection>(LE->template getLinkOrderDep<ELFT>());
Rafael Espindolae1294092017-03-08 16:03:41 +00002231 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
Peter Smith719eb8e2016-11-24 11:43:55 +00002232 uint64_t P = this->getVA();
2233 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2234 write32le(Buf + 4, 0x1);
2235}
2236
George Rimar7b827042017-03-16 10:40:50 +00002237ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002238 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
George Rimar7b827042017-03-16 10:40:50 +00002239 Config->is64Bit() ? 8 : 4, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002240 this->OutSec = OS;
2241 this->OutSecOff = Off;
2242}
2243
George Rimar7b827042017-03-16 10:40:50 +00002244void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002245 uint64_t Off = alignTo(Size, T->alignment);
2246 T->Offset = Off;
2247 Thunks.push_back(T);
2248 T->addSymbols(*this);
2249 Size = Off + T->size();
2250}
2251
George Rimar7b827042017-03-16 10:40:50 +00002252void ThunkSection::writeTo(uint8_t *Buf) {
2253 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002254 T->writeTo(Buf + T->Offset, *this);
2255}
2256
George Rimar7b827042017-03-16 10:40:50 +00002257InputSection *ThunkSection::getTargetInputSection() const {
2258 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002259 return T->getTargetInputSection();
2260}
2261
George Rimar9782ca52017-03-15 15:29:29 +00002262InputSection *InX::ARMAttributes;
George Rimar9782ca52017-03-15 15:29:29 +00002263InputSection *InX::Common;
2264StringTableSection *InX::DynStrTab;
2265InputSection *InX::Interp;
2266GotPltSection *InX::GotPlt;
2267IgotPltSection *InX::IgotPlt;
2268MipsRldMapSection *InX::MipsRldMap;
2269StringTableSection *InX::ShStrTab;
2270StringTableSection *InX::StrTab;
2271
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002272template InputSection *elf::createCommonSection<ELF32LE>();
2273template InputSection *elf::createCommonSection<ELF32BE>();
2274template InputSection *elf::createCommonSection<ELF64LE>();
2275template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002276
Rafael Espindola6119b862017-03-06 20:23:56 +00002277template MergeInputSection *elf::createCommentSection<ELF32LE>();
2278template MergeInputSection *elf::createCommentSection<ELF32BE>();
2279template MergeInputSection *elf::createCommentSection<ELF64LE>();
2280template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002281
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002282template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002283 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002284 InputSectionBase *);
2285template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002286 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002287 InputSectionBase *);
2288template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002289 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002290 InputSectionBase *);
2291template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002292 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002293 InputSectionBase *);
Peter Smith96943762017-01-25 10:31:16 +00002294
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002295template class elf::MipsAbiFlagsSection<ELF32LE>;
2296template class elf::MipsAbiFlagsSection<ELF32BE>;
2297template class elf::MipsAbiFlagsSection<ELF64LE>;
2298template class elf::MipsAbiFlagsSection<ELF64BE>;
2299
Simon Atanasyance02cf02016-11-09 21:36:56 +00002300template class elf::MipsOptionsSection<ELF32LE>;
2301template class elf::MipsOptionsSection<ELF32BE>;
2302template class elf::MipsOptionsSection<ELF64LE>;
2303template class elf::MipsOptionsSection<ELF64BE>;
2304
2305template class elf::MipsReginfoSection<ELF32LE>;
2306template class elf::MipsReginfoSection<ELF32BE>;
2307template class elf::MipsReginfoSection<ELF64LE>;
2308template class elf::MipsReginfoSection<ELF64BE>;
2309
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00002310template class elf::BuildIdSection<ELF32LE>;
2311template class elf::BuildIdSection<ELF32BE>;
2312template class elf::BuildIdSection<ELF64LE>;
2313template class elf::BuildIdSection<ELF64BE>;
2314
George Rimar47bed8c2017-03-16 08:44:53 +00002315template class elf::CopyRelSection<ELF32LE>;
2316template class elf::CopyRelSection<ELF32BE>;
2317template class elf::CopyRelSection<ELF64LE>;
2318template class elf::CopyRelSection<ELF64BE>;
2319
Eugene Leviantad4439e2016-11-11 11:33:32 +00002320template class elf::GotSection<ELF32LE>;
2321template class elf::GotSection<ELF32BE>;
2322template class elf::GotSection<ELF64LE>;
2323template class elf::GotSection<ELF64BE>;
2324
Simon Atanasyan725dc142016-11-16 21:01:02 +00002325template class elf::MipsGotSection<ELF32LE>;
2326template class elf::MipsGotSection<ELF32BE>;
2327template class elf::MipsGotSection<ELF64LE>;
2328template class elf::MipsGotSection<ELF64BE>;
2329
Eugene Leviant6380ce22016-11-15 12:26:55 +00002330template class elf::DynamicSection<ELF32LE>;
2331template class elf::DynamicSection<ELF32BE>;
2332template class elf::DynamicSection<ELF64LE>;
2333template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002334
2335template class elf::RelocationSection<ELF32LE>;
2336template class elf::RelocationSection<ELF32BE>;
2337template class elf::RelocationSection<ELF64LE>;
2338template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002339
2340template class elf::SymbolTableSection<ELF32LE>;
2341template class elf::SymbolTableSection<ELF32BE>;
2342template class elf::SymbolTableSection<ELF64LE>;
2343template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002344
2345template class elf::GnuHashTableSection<ELF32LE>;
2346template class elf::GnuHashTableSection<ELF32BE>;
2347template class elf::GnuHashTableSection<ELF64LE>;
2348template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002349
2350template class elf::HashTableSection<ELF32LE>;
2351template class elf::HashTableSection<ELF32BE>;
2352template class elf::HashTableSection<ELF64LE>;
2353template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002354
2355template class elf::PltSection<ELF32LE>;
2356template class elf::PltSection<ELF32BE>;
2357template class elf::PltSection<ELF64LE>;
2358template class elf::PltSection<ELF64BE>;
Eugene Levianta113a412016-11-21 09:24:43 +00002359
2360template class elf::GdbIndexSection<ELF32LE>;
2361template class elf::GdbIndexSection<ELF32BE>;
2362template class elf::GdbIndexSection<ELF64LE>;
2363template class elf::GdbIndexSection<ELF64BE>;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002364
2365template class elf::EhFrameHeader<ELF32LE>;
2366template class elf::EhFrameHeader<ELF32BE>;
2367template class elf::EhFrameHeader<ELF64LE>;
2368template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002369
2370template class elf::VersionTableSection<ELF32LE>;
2371template class elf::VersionTableSection<ELF32BE>;
2372template class elf::VersionTableSection<ELF64LE>;
2373template class elf::VersionTableSection<ELF64BE>;
2374
2375template class elf::VersionNeedSection<ELF32LE>;
2376template class elf::VersionNeedSection<ELF32BE>;
2377template class elf::VersionNeedSection<ELF64LE>;
2378template class elf::VersionNeedSection<ELF64BE>;
2379
2380template class elf::VersionDefinitionSection<ELF32LE>;
2381template class elf::VersionDefinitionSection<ELF32BE>;
2382template class elf::VersionDefinitionSection<ELF64LE>;
2383template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002384
Peter Smith719eb8e2016-11-24 11:43:55 +00002385template class elf::ARMExidxSentinelSection<ELF32LE>;
2386template class elf::ARMExidxSentinelSection<ELF32BE>;
2387template class elf::ARMExidxSentinelSection<ELF64LE>;
2388template class elf::ARMExidxSentinelSection<ELF64BE>;
Peter Smith3a52eb02017-02-01 10:26:03 +00002389
Rafael Espindola66b4e212017-02-23 22:06:28 +00002390template class elf::EhFrameSection<ELF32LE>;
2391template class elf::EhFrameSection<ELF32BE>;
2392template class elf::EhFrameSection<ELF64LE>;
2393template class elf::EhFrameSection<ELF64BE>;