blob: a804de6a01ae112d37a989fd910bf3f1d6311fad [file] [log] [blame]
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00001//===- SyntheticSections.cpp ----------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains linker-synthesized sections. Currently,
11// synthetic sections are created either output sections or input sections,
12// but we are rewriting code so that all synthetic sections are created as
13// input sections.
14//
15//===----------------------------------------------------------------------===//
16
17#include "SyntheticSections.h"
18#include "Config.h"
19#include "Error.h"
20#include "InputFiles.h"
Eugene Leviant17b7a572016-11-22 17:49:14 +000021#include "LinkerScript.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000022#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000023#include "OutputSections.h"
24#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000025#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000026#include "Target.h"
Rui Ueyama244a4352016-12-03 21:24:51 +000027#include "Threads.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000028#include "Writer.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000029#include "lld/Config/Version.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000030#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
31#include "llvm/Object/ELFObjectFile.h"
Eugene Leviant952eb4d2016-11-21 15:52:10 +000032#include "llvm/Support/Dwarf.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000033#include "llvm/Support/Endian.h"
34#include "llvm/Support/MD5.h"
35#include "llvm/Support/RandomNumberGenerator.h"
36#include "llvm/Support/SHA1.h"
37#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000038#include <cstdlib>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000039
40using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000041using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000042using namespace llvm::ELF;
43using namespace llvm::object;
44using namespace llvm::support;
45using namespace llvm::support::endian;
46
47using namespace lld;
48using namespace lld::elf;
49
Rui Ueyama9320cb02017-02-27 02:56:02 +000050uint64_t SyntheticSection::getVA() const {
51 if (this->OutSec)
52 return this->OutSec->Addr + this->OutSecOff;
53 return 0;
54}
55
Rui Ueyamae8a61022016-11-05 23:05:47 +000056template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
57 std::vector<DefinedCommon *> V;
58 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
59 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
60 V.push_back(B);
61 return V;
62}
63
64// Find all common symbols and allocate space for them.
Rafael Espindola774ea7d2017-02-23 16:49:07 +000065template <class ELFT> InputSection *elf::createCommonSection() {
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000066 if (!Config->DefineCommon)
George Rimar176d6062017-03-17 13:31:07 +000067 return nullptr;
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000068
Rui Ueyamae8a61022016-11-05 23:05:47 +000069 // Sort the common symbols by alignment as an heuristic to pack them better.
70 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
George Rimar176d6062017-03-17 13:31:07 +000071 if (Syms.empty())
72 return nullptr;
73
Rui Ueyamae8a61022016-11-05 23:05:47 +000074 std::stable_sort(Syms.begin(), Syms.end(),
75 [](const DefinedCommon *A, const DefinedCommon *B) {
76 return A->Alignment > B->Alignment;
77 });
78
Rui Ueyamac95671b2017-03-29 00:49:29 +000079 BssSection *Sec = make<BssSection>("COMMON");
80 for (DefinedCommon *Sym : Syms)
81 Sym->Offset = Sec->reserveSpace(Sym->Size, Sym->Alignment);
82 return Sec;
Rui Ueyamae8a61022016-11-05 23:05:47 +000083}
84
Rui Ueyama3da3f062016-11-10 20:20:37 +000085// Returns an LLD version string.
86static ArrayRef<uint8_t> getVersion() {
87 // Check LLD_VERSION first for ease of testing.
88 // You can get consitent output by using the environment variable.
89 // This is only for testing.
90 StringRef S = getenv("LLD_VERSION");
91 if (S.empty())
92 S = Saver.save(Twine("Linker: ") + getLLDVersion());
93
94 // +1 to include the terminating '\0'.
95 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000096}
Rui Ueyama3da3f062016-11-10 20:20:37 +000097
98// Creates a .comment section containing LLD version info.
99// With this feature, you can identify LLD-generated binaries easily
100// by "objdump -s -j .comment <file>".
101// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000102template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000103 typename ELFT::Shdr Hdr = {};
104 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
105 Hdr.sh_type = SHT_PROGBITS;
106 Hdr.sh_entsize = 1;
107 Hdr.sh_addralign = 1;
108
Rafael Espindola6119b862017-03-06 20:23:56 +0000109 auto *Ret =
110 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000111 Ret->Data = getVersion();
112 Ret->splitIntoPieces();
113 return Ret;
114}
115
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000116// .MIPS.abiflags section.
117template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000118MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000119 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000120 Flags(Flags) {
121 this->Entsize = sizeof(Elf_Mips_ABIFlags);
122}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000123
124template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
125 memcpy(Buf, &Flags, sizeof(Flags));
126}
127
128template <class ELFT>
129MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
130 Elf_Mips_ABIFlags Flags = {};
131 bool Create = false;
132
Rui Ueyama536a2672017-02-27 02:32:08 +0000133 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000134 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000135 continue;
136 Sec->Live = false;
137 Create = true;
138
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000139 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000140 const size_t Size = Sec->Data.size();
141 // Older version of BFD (such as the default FreeBSD linker) concatenate
142 // .MIPS.abiflags instead of merging. To allow for this case (or potential
143 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
144 if (Size < sizeof(Elf_Mips_ABIFlags)) {
145 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
146 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000147 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000148 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000149 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000150 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000151 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000152 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000153 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000154 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000155
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000156 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
157 // select the highest number of ISA/Rev/Ext.
158 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
159 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
160 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
161 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
162 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
163 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
164 Flags.ases |= S->ases;
165 Flags.flags1 |= S->flags1;
166 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000167 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000168 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000169
Rui Ueyama12f2da82016-11-22 03:57:06 +0000170 if (Create)
171 return make<MipsAbiFlagsSection<ELFT>>(Flags);
172 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000173}
174
Simon Atanasyance02cf02016-11-09 21:36:56 +0000175// .MIPS.options section.
176template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000177MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000178 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000179 Reginfo(Reginfo) {
180 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
181}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000182
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000183template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
184 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
185 Options->kind = ODK_REGINFO;
186 Options->size = getSize();
187
188 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000189 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000190 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000191}
192
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000193template <class ELFT>
194MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
195 // N64 ABI only.
196 if (!ELFT::Is64Bits)
197 return nullptr;
198
199 Elf_Mips_RegInfo Reginfo = {};
200 bool Create = false;
201
Rui Ueyama536a2672017-02-27 02:32:08 +0000202 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000203 if (Sec->Type != SHT_MIPS_OPTIONS)
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000204 continue;
205 Sec->Live = false;
206 Create = true;
207
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000208 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000209 ArrayRef<uint8_t> D = Sec->Data;
210
211 while (!D.empty()) {
212 if (D.size() < sizeof(Elf_Mips_Options)) {
213 error(Filename + ": invalid size of .MIPS.options section");
214 break;
215 }
216
217 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
218 if (Opt->kind == ODK_REGINFO) {
219 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
220 error(Filename + ": unsupported non-zero ri_gp_value");
221 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000222 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000223 break;
224 }
225
226 if (!Opt->size)
227 fatal(Filename + ": zero option descriptor size");
228 D = D.slice(Opt->size);
229 }
230 };
231
232 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000233 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000234 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000235}
236
237// MIPS .reginfo section.
238template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000239MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000240 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000241 Reginfo(Reginfo) {
242 this->Entsize = sizeof(Elf_Mips_RegInfo);
243}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000244
Rui Ueyamab71cae92016-11-22 03:57:08 +0000245template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000246 if (!Config->Relocatable)
Simon Atanasyan8469b882016-11-23 22:22:16 +0000247 Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000248 memcpy(Buf, &Reginfo, sizeof(Reginfo));
249}
250
251template <class ELFT>
252MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
253 // Section should be alive for O32 and N32 ABIs only.
254 if (ELFT::Is64Bits)
255 return nullptr;
256
257 Elf_Mips_RegInfo Reginfo = {};
258 bool Create = false;
259
Rui Ueyama536a2672017-02-27 02:32:08 +0000260 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000261 if (Sec->Type != SHT_MIPS_REGINFO)
Rui Ueyamab71cae92016-11-22 03:57:08 +0000262 continue;
263 Sec->Live = false;
264 Create = true;
265
266 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000267 error(toString(Sec->getFile<ELFT>()) +
268 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000269 return nullptr;
270 }
271 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
272 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000273 error(toString(Sec->getFile<ELFT>()) +
274 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000275
276 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000277 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000278 };
279
280 if (Create)
281 return make<MipsReginfoSection<ELFT>>(Reginfo);
282 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000283}
284
Rui Ueyama3255a522017-02-27 02:32:49 +0000285InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000286 // StringSaver guarantees that the returned string ends with '\0'.
287 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000288 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
289
290 auto *Sec =
291 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
292 Sec->Live = true;
293 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000294}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000295
Peter Smith96943762017-01-25 10:31:16 +0000296template <class ELFT>
Rui Ueyama65316d72017-02-23 03:15:57 +0000297SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
298 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000299 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
300 Value, Size, Section, nullptr);
Peter Smith96943762017-01-25 10:31:16 +0000301 if (In<ELFT>::SymTab)
Rui Ueyamab8dcdb52017-02-28 04:20:16 +0000302 In<ELFT>::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000303 return S;
304}
305
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000306static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000307 switch (Config->BuildId) {
308 case BuildIdKind::Fast:
309 return 8;
310 case BuildIdKind::Md5:
311 case BuildIdKind::Uuid:
312 return 16;
313 case BuildIdKind::Sha1:
314 return 20;
315 case BuildIdKind::Hexstring:
316 return Config->BuildIdVector.size();
317 default:
318 llvm_unreachable("unknown BuildIdKind");
319 }
320}
321
George Rimar6c2949d2017-03-20 16:40:21 +0000322BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000323 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000324 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000325
George Rimar6c2949d2017-03-20 16:40:21 +0000326void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000327 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000328 write32(Buf, 4, E); // Name size
329 write32(Buf + 4, HashSize, E); // Content size
330 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000331 memcpy(Buf + 12, "GNU", 4); // Name string
332 HashBuf = Buf + 16;
333}
334
Rui Ueyama35e00752016-11-10 00:12:28 +0000335// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000336static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
337 size_t ChunkSize) {
338 std::vector<ArrayRef<uint8_t>> Ret;
339 while (Arr.size() > ChunkSize) {
340 Ret.push_back(Arr.take_front(ChunkSize));
341 Arr = Arr.drop_front(ChunkSize);
342 }
343 if (!Arr.empty())
344 Ret.push_back(Arr);
345 return Ret;
346}
347
Rui Ueyama35e00752016-11-10 00:12:28 +0000348// Computes a hash value of Data using a given hash function.
349// In order to utilize multiple cores, we first split data into 1MB
350// chunks, compute a hash for each chunk, and then compute a hash value
351// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000352void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000353 llvm::ArrayRef<uint8_t> Data,
354 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000355 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000356 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000357
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000358 // Compute hash values.
Rui Ueyama4995afd2017-03-22 23:03:35 +0000359 parallelFor(0, Chunks.size(), [&](size_t I) {
360 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
361 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000362
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000363 // Write to the final output buffer.
364 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000365}
366
George Rimar1ab9cf42017-03-17 10:14:53 +0000367BssSection::BssSection(StringRef Name)
368 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
369
Rui Ueyamac95671b2017-03-29 00:49:29 +0000370size_t BssSection::reserveSpace(size_t Size, uint32_t Alignment) {
George Rimar176d6062017-03-17 13:31:07 +0000371 if (OutSec)
372 OutSec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000373 this->Size = alignTo(this->Size, Alignment) + Size;
374 this->Alignment = std::max<uint32_t>(this->Alignment, Alignment);
375 return this->Size - Size;
376}
Peter Smithebfe9942017-02-09 10:27:57 +0000377
George Rimar6c2949d2017-03-20 16:40:21 +0000378void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000379 switch (Config->BuildId) {
380 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000381 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000382 write64le(Dest, xxHash64(toStringRef(Arr)));
383 });
384 break;
385 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000386 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000387 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000388 });
389 break;
390 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000391 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000392 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000393 });
394 break;
395 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000396 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000397 error("entropy source failure");
398 break;
399 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000400 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000401 break;
402 default:
403 llvm_unreachable("unknown BuildIdKind");
404 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000405}
406
Eugene Leviant41ca3272016-11-10 09:48:29 +0000407template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000408EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000409 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000410
411// Search for an existing CIE record or create a new one.
412// CIE records from input object files are uniquified by their contents
413// and where their relocations point to.
414template <class ELFT>
415template <class RelTy>
416CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
417 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000418 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000419 const endianness E = ELFT::TargetEndianness;
420 if (read32<E>(Piece.data().data() + 4) != 0)
421 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
422
423 SymbolBody *Personality = nullptr;
424 unsigned FirstRelI = Piece.FirstRelocation;
425 if (FirstRelI != (unsigned)-1)
426 Personality =
427 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
428
429 // Search for an existing CIE by CIE contents/relocation target pair.
430 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
431
432 // If not found, create a new one.
433 if (Cie->Piece == nullptr) {
434 Cie->Piece = &Piece;
435 Cies.push_back(Cie);
436 }
437 return Cie;
438}
439
440// There is one FDE per function. Returns true if a given FDE
441// points to a live function.
442template <class ELFT>
443template <class RelTy>
444bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
445 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000446 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000447 unsigned FirstRelI = Piece.FirstRelocation;
448 if (FirstRelI == (unsigned)-1)
449 return false;
450 const RelTy &Rel = Rels[FirstRelI];
451 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000452 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000453 if (!D || !D->Section)
454 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000455 auto *Target =
456 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000457 return Target && Target->Live;
458}
459
460// .eh_frame is a sequence of CIE or FDE records. In general, there
461// is one CIE record per input object file which is followed by
462// a list of FDEs. This function searches an existing CIE or create a new
463// one and associates FDEs to the CIE.
464template <class ELFT>
465template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000466void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000467 ArrayRef<RelTy> Rels) {
468 const endianness E = ELFT::TargetEndianness;
469
470 DenseMap<size_t, CieRecord *> OffsetToCie;
471 for (EhSectionPiece &Piece : Sec->Pieces) {
472 // The empty record is the end marker.
473 if (Piece.size() == 4)
474 return;
475
476 size_t Offset = Piece.InputOff;
477 uint32_t ID = read32<E>(Piece.data().data() + 4);
478 if (ID == 0) {
479 OffsetToCie[Offset] = addCie(Piece, Rels);
480 continue;
481 }
482
483 uint32_t CieOffset = Offset + 4 - ID;
484 CieRecord *Cie = OffsetToCie[CieOffset];
485 if (!Cie)
486 fatal(toString(Sec) + ": invalid CIE reference");
487
488 if (!isFdeLive(Piece, Rels))
489 continue;
490 Cie->FdePieces.push_back(&Piece);
491 NumFdes++;
492 }
493}
494
495template <class ELFT>
496void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000497 auto *Sec = cast<EhInputSection>(C);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000498 Sec->EHSec = this;
499 updateAlignment(Sec->Alignment);
500 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000501 for (auto *DS : Sec->DependentSections)
502 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000503
504 // .eh_frame is a sequence of CIE or FDE records. This function
505 // splits it into pieces so that we can call
506 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000507 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000508 if (Sec->Pieces.empty())
509 return;
510
511 if (Sec->NumRelocations) {
512 if (Sec->AreRelocsRela)
513 addSectionAux(Sec, Sec->template relas<ELFT>());
514 else
515 addSectionAux(Sec, Sec->template rels<ELFT>());
516 return;
517 }
518 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
519}
520
521template <class ELFT>
522static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
523 memcpy(Buf, D.data(), D.size());
524
525 // Fix the size field. -4 since size does not include the size field itself.
526 const endianness E = ELFT::TargetEndianness;
527 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
528}
529
Rui Ueyama945055a2017-02-27 03:07:41 +0000530template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000531 if (this->Size)
532 return; // Already finalized.
533
534 size_t Off = 0;
535 for (CieRecord *Cie : Cies) {
536 Cie->Piece->OutputOff = Off;
537 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
538
539 for (EhSectionPiece *Fde : Cie->FdePieces) {
540 Fde->OutputOff = Off;
541 Off += alignTo(Fde->size(), sizeof(uintX_t));
542 }
543 }
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000544 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000545}
546
547template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
548 const endianness E = ELFT::TargetEndianness;
549 switch (Size) {
550 case DW_EH_PE_udata2:
551 return read16<E>(Buf);
552 case DW_EH_PE_udata4:
553 return read32<E>(Buf);
554 case DW_EH_PE_udata8:
555 return read64<E>(Buf);
556 case DW_EH_PE_absptr:
557 if (ELFT::Is64Bits)
558 return read64<E>(Buf);
559 return read32<E>(Buf);
560 }
561 fatal("unknown FDE size encoding");
562}
563
564// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
565// We need it to create .eh_frame_hdr section.
566template <class ELFT>
567typename ELFT::uint EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
568 uint8_t Enc) {
569 // The starting address to which this FDE applies is
570 // stored at FDE + 8 byte.
571 size_t Off = FdeOff + 8;
572 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
573 if ((Enc & 0x70) == DW_EH_PE_absptr)
574 return Addr;
575 if ((Enc & 0x70) == DW_EH_PE_pcrel)
576 return Addr + this->OutSec->Addr + Off;
577 fatal("unknown FDE size relative encoding");
578}
579
580template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
581 const endianness E = ELFT::TargetEndianness;
582 for (CieRecord *Cie : Cies) {
583 size_t CieOffset = Cie->Piece->OutputOff;
584 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
585
586 for (EhSectionPiece *Fde : Cie->FdePieces) {
587 size_t Off = Fde->OutputOff;
588 writeCieFde<ELFT>(Buf + Off, Fde->data());
589
590 // FDE's second word should have the offset to an associated CIE.
591 // Write it.
592 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
593 }
594 }
595
Rafael Espindola5c02b742017-03-06 21:17:18 +0000596 for (EhInputSection *S : Sections)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000597 S->template relocate<ELFT>(Buf, nullptr);
598
599 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
600 // to get a FDE from an address to which FDE is applied. So here
601 // we obtain two addresses and pass them to EhFrameHdr object.
602 if (In<ELFT>::EhFrameHdr) {
603 for (CieRecord *Cie : Cies) {
604 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
605 for (SectionPiece *Fde : Cie->FdePieces) {
606 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
607 uintX_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
608 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
609 }
610 }
611 }
612}
613
614template <class ELFT>
Eugene Leviantad4439e2016-11-11 11:33:32 +0000615GotSection<ELFT>::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000616 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
617 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000618
619template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000620 Sym.GotIndex = NumEntries;
621 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000622}
623
Simon Atanasyan725dc142016-11-16 21:01:02 +0000624template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
625 if (Sym.GlobalDynIndex != -1U)
626 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000627 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000628 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000629 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000630 return true;
631}
632
633// Reserves TLS entries for a TLS module ID and a TLS block offset.
634// In total it takes two GOT slots.
635template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
636 if (TlsIndexOff != uint32_t(-1))
637 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000638 TlsIndexOff = NumEntries * sizeof(uintX_t);
639 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640 return true;
641}
642
Eugene Leviantad4439e2016-11-11 11:33:32 +0000643template <class ELFT>
Simon Atanasyan725dc142016-11-16 21:01:02 +0000644typename GotSection<ELFT>::uintX_t
645GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
646 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
647}
648
649template <class ELFT>
650typename GotSection<ELFT>::uintX_t
651GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
652 return B.GlobalDynIndex * sizeof(uintX_t);
653}
654
Rui Ueyama945055a2017-02-27 03:07:41 +0000655template <class ELFT> void GotSection<ELFT>::finalizeContents() {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000656 Size = NumEntries * sizeof(uintX_t);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000657}
658
George Rimar11992c862016-11-25 08:05:41 +0000659template <class ELFT> bool GotSection<ELFT>::empty() const {
660 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
661 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000662 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000663}
664
Simon Atanasyan725dc142016-11-16 21:01:02 +0000665template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000666 this->template relocate<ELFT>(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000667}
668
George Rimar14534eb2017-03-20 16:44:28 +0000669MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000670 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
671 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000672
George Rimar14534eb2017-03-20 16:44:28 +0000673void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000674 // For "true" local symbols which can be referenced from the same module
675 // only compiler creates two instructions for address loading:
676 //
677 // lw $8, 0($gp) # R_MIPS_GOT16
678 // addi $8, $8, 0 # R_MIPS_LO16
679 //
680 // The first instruction loads high 16 bits of the symbol address while
681 // the second adds an offset. That allows to reduce number of required
682 // GOT entries because only one global offset table entry is necessary
683 // for every 64 KBytes of local data. So for local symbols we need to
684 // allocate number of GOT entries to hold all required "page" addresses.
685 //
686 // All global symbols (hidden and regular) considered by compiler uniformly.
687 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
688 // to load address of the symbol. So for each such symbol we need to
689 // allocate dedicated GOT entry to store its address.
690 //
691 // If a symbol is preemptible we need help of dynamic linker to get its
692 // final address. The corresponding GOT entries are allocated in the
693 // "global" part of GOT. Entries for non preemptible global symbol allocated
694 // in the "local" part of GOT.
695 //
696 // See "Global Offset Table" in Chapter 5:
697 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
698 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
699 // At this point we do not know final symbol value so to reduce number
700 // of allocated GOT entries do the following trick. Save all output
701 // sections referenced by GOT relocations. Then later in the `finalize`
702 // method calculate number of "pages" required to cover all saved output
703 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000704 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000705 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000706 return;
707 }
708 if (Sym.isTls()) {
709 // GOT entries created for MIPS TLS relocations behave like
710 // almost GOT entries from other ABIs. They go to the end
711 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000712 Sym.GotIndex = TlsEntries.size();
713 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000714 return;
715 }
George Rimar14534eb2017-03-20 16:44:28 +0000716 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000717 if (S.isInGot() && !A)
718 return;
719 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000720 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000721 return;
722 Items.emplace_back(&S, A);
723 if (!A)
724 S.GotIndex = NewIndex;
725 };
726 if (Sym.isPreemptible()) {
727 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000728 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 Sym.IsInGlobalMipsGot = true;
730 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000731 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000732 Sym.Is32BitMipsGot = true;
733 } else {
734 // Hold local GOT entries accessed via a 16-bit index separately.
735 // That allows to write them in the beginning of the GOT and keep
736 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000737 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000738 }
739}
740
George Rimar14534eb2017-03-20 16:44:28 +0000741bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000742 if (Sym.GlobalDynIndex != -1U)
743 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000744 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000745 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000746 TlsEntries.push_back(nullptr);
747 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000748 return true;
749}
750
751// Reserves TLS entries for a TLS module ID and a TLS block offset.
752// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000753bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000754 if (TlsIndexOff != uint32_t(-1))
755 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000756 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000757 TlsEntries.push_back(nullptr);
758 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000759 return true;
760}
761
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000762static uint64_t getMipsPageAddr(uint64_t Addr) {
763 return (Addr + 0x8000) & ~0xffff;
764}
765
766static uint64_t getMipsPageCount(uint64_t Size) {
767 return (Size + 0xfffe) / 0xffff + 1;
768}
769
George Rimar14534eb2017-03-20 16:44:28 +0000770uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
771 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000772 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000773 cast<DefinedRegular>(&B)->Section->getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000774 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
775 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
776 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000777 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000778 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000779}
780
George Rimar14534eb2017-03-20 16:44:28 +0000781uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
782 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000784 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000785 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000786 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000787 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000788 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000789 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000790 Index += LocalEntries.size();
791 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000792 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000795 auto It = EntryIndexMap.find({&B, Addend});
796 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000797 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000798 }
George Rimar14534eb2017-03-20 16:44:28 +0000799 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000800}
801
George Rimar14534eb2017-03-20 16:44:28 +0000802uint64_t MipsGotSection::getTlsOffset() const {
803 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804}
805
George Rimar14534eb2017-03-20 16:44:28 +0000806uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
807 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000808}
809
George Rimar14534eb2017-03-20 16:44:28 +0000810const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000811 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000812}
813
George Rimar14534eb2017-03-20 16:44:28 +0000814unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000815 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
816 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000817}
818
George Rimar14534eb2017-03-20 16:44:28 +0000819void MipsGotSection::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000820 updateAllocSize();
821}
822
George Rimar14534eb2017-03-20 16:44:28 +0000823void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000824 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000825 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000826 // For each output section referenced by GOT page relocations calculate
827 // and save into PageIndexMap an upper bound of MIPS GOT entries required
828 // to store page addresses of local symbols. We assume the worst case -
829 // each 64kb page of the output section has at least one GOT relocation
830 // against it. And take in account the case when the section intersects
831 // page boundaries.
832 P.second = PageEntriesNum;
833 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000834 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000835 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000836 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000837}
838
George Rimar14534eb2017-03-20 16:44:28 +0000839bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000840 // We add the .got section to the result for dynamic MIPS target because
841 // its address and properties are mentioned in the .dynamic section.
842 return Config->Relocatable;
843}
844
George Rimar14534eb2017-03-20 16:44:28 +0000845uint64_t MipsGotSection::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000846 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000847}
848
George Rimar14534eb2017-03-20 16:44:28 +0000849static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000850 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000851 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000852 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000853 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000854}
855
George Rimar14534eb2017-03-20 16:44:28 +0000856void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000857 // Set the MSB of the second GOT slot. This is not required by any
858 // MIPS ABI documentation, though.
859 //
860 // There is a comment in glibc saying that "The MSB of got[1] of a
861 // gnu object is set to identify gnu objects," and in GNU gold it
862 // says "the second entry will be used by some runtime loaders".
863 // But how this field is being used is unclear.
864 //
865 // We are not really willing to mimic other linkers behaviors
866 // without understanding why they do that, but because all files
867 // generated by GNU tools have this special GOT value, and because
868 // we've been doing this for years, it is probably a safe bet to
869 // keep doing this for now. We really need to revisit this to see
870 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000871 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
872 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000873 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000874 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000875 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000876 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000877 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000878 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
879 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000880 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000881 }
George Rimar14534eb2017-03-20 16:44:28 +0000882 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000883 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000884 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000885 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000886 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000887 uint64_t VA = Body->getVA(SA.second);
888 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000889 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000890 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
891 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
892 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000893 // Initialize TLS-related GOT entries. If the entry has a corresponding
894 // dynamic relocations, leave it initialized by zero. Write down adjusted
895 // TLS symbol's values otherwise. To calculate the adjustments use offsets
896 // for thread-local storage.
897 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000898 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000899 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000900 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000901 if (!B || B->isPreemptible())
902 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000903 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000904 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000905 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
906 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000907 }
908 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000909 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
910 writeUint(Entry, 1);
911 Entry += Config->Wordsize;
912 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000913 }
914 }
915}
916
George Rimar10f74fc2017-03-15 09:12:56 +0000917GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000918 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
919 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000920
George Rimar10f74fc2017-03-15 09:12:56 +0000921void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000922 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
923 Entries.push_back(&Sym);
924}
925
George Rimar10f74fc2017-03-15 09:12:56 +0000926size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000927 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
928 Target->GotPltEntrySize;
929}
930
George Rimar10f74fc2017-03-15 09:12:56 +0000931void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000932 Target->writeGotPltHeader(Buf);
933 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
934 for (const SymbolBody *B : Entries) {
935 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000936 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000937 }
938}
939
Peter Smithbaffdb82016-12-08 12:58:55 +0000940// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
941// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000942IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000943 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
944 Target->GotPltEntrySize,
945 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000946
George Rimar10f74fc2017-03-15 09:12:56 +0000947void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000948 Sym.IsInIgot = true;
949 Sym.GotPltIndex = Entries.size();
950 Entries.push_back(&Sym);
951}
952
George Rimar10f74fc2017-03-15 09:12:56 +0000953size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000954 return Entries.size() * Target->GotPltEntrySize;
955}
956
George Rimar10f74fc2017-03-15 09:12:56 +0000957void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000958 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000959 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000960 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000961 }
962}
963
George Rimar49648002017-03-15 09:32:36 +0000964StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
965 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000966 Dynamic(Dynamic) {
967 // ELF string tables start with a NUL byte.
968 addString("");
969}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000970
971// Adds a string to the string table. If HashIt is true we hash and check for
972// duplicates. It is optional because the name of global symbols are already
973// uniqued and hashing them again has a big cost for a small value: uniquing
974// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000975unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000976 if (HashIt) {
977 auto R = StringMap.insert(std::make_pair(S, this->Size));
978 if (!R.second)
979 return R.first->second;
980 }
981 unsigned Ret = this->Size;
982 this->Size = this->Size + S.size() + 1;
983 Strings.push_back(S);
984 return Ret;
985}
986
George Rimar49648002017-03-15 09:32:36 +0000987void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000988 for (StringRef S : Strings) {
989 memcpy(Buf, S.data(), S.size());
990 Buf += S.size() + 1;
991 }
992}
993
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000994// Returns the number of version definition entries. Because the first entry
995// is for the version definition itself, it is the number of versioned symbols
996// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000997static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
998
999template <class ELFT>
1000DynamicSection<ELFT>::DynamicSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001001 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, sizeof(uintX_t),
1002 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001003 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001004
Eugene Leviant6380ce22016-11-15 12:26:55 +00001005 // .dynamic section is not writable on MIPS.
1006 // See "Special Section" in Chapter 4 in the following document:
1007 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1008 if (Config->EMachine == EM_MIPS)
1009 this->Flags = SHF_ALLOC;
1010
1011 addEntries();
1012}
1013
1014// There are some dynamic entries that don't depend on other sections.
1015// Such entries can be set early.
1016template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1017 // Add strings to .dynstr early so that .dynstr's size will be
1018 // fixed early.
1019 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +00001020 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001021 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001022 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001023 In<ELFT>::DynStrTab->addString(Config->RPath)});
1024 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1025 if (F->isNeeded())
Rui Ueyama729ac792016-11-17 04:10:09 +00001026 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->getSoName())});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001027 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001028 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001029
1030 // Set DT_FLAGS and DT_FLAGS_1.
1031 uint32_t DtFlags = 0;
1032 uint32_t DtFlags1 = 0;
1033 if (Config->Bsymbolic)
1034 DtFlags |= DF_SYMBOLIC;
1035 if (Config->ZNodelete)
1036 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001037 if (Config->ZNodlopen)
1038 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001039 if (Config->ZNow) {
1040 DtFlags |= DF_BIND_NOW;
1041 DtFlags1 |= DF_1_NOW;
1042 }
1043 if (Config->ZOrigin) {
1044 DtFlags |= DF_ORIGIN;
1045 DtFlags1 |= DF_1_ORIGIN;
1046 }
1047
1048 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001049 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001050 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001051 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001052
Petr Hosek668bebe2016-12-07 02:05:42 +00001053 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +00001054 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001055}
1056
1057// Add remaining entries to complete .dynamic contents.
Rui Ueyama945055a2017-02-27 03:07:41 +00001058template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001059 if (this->Size)
1060 return; // Already finalized.
1061
1062 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001063 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001064 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001065 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001066 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001067 add({IsRela ? DT_RELAENT : DT_RELENT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001068 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
1069
1070 // MIPS dynamic loader does not support RELCOUNT tag.
1071 // The problem is in the tight relation between dynamic
1072 // relocations and GOT. So do not emit this tag on MIPS.
1073 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001074 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001075 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001076 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001077 }
1078 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001079 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001080 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001081 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001082 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001083 In<ELFT>::GotPlt});
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001084 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001085 }
1086
Eugene Leviant9230db92016-11-17 09:16:34 +00001087 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001088 add({DT_SYMENT, sizeof(Elf_Sym)});
1089 add({DT_STRTAB, In<ELFT>::DynStrTab});
1090 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001091 if (!Config->ZText)
1092 add({DT_TEXTREL, (uint64_t)0});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001093 if (In<ELFT>::GnuHashTab)
1094 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001095 if (In<ELFT>::HashTab)
1096 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001097
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001098 if (Out::PreinitArray) {
1099 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1100 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001101 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001102 if (Out::InitArray) {
1103 add({DT_INIT_ARRAY, Out::InitArray});
1104 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001105 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001106 if (Out::FiniArray) {
1107 add({DT_FINI_ARRAY, Out::FiniArray});
1108 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001109 }
1110
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001111 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001112 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001113 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001114 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001115
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001116 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1117 if (HasVerNeed || In<ELFT>::VerDef)
1118 add({DT_VERSYM, In<ELFT>::VerSym});
1119 if (In<ELFT>::VerDef) {
1120 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001121 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001122 }
1123 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001124 add({DT_VERNEED, In<ELFT>::VerNeed});
1125 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001126 }
1127
1128 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001129 add({DT_MIPS_RLD_VERSION, 1});
1130 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1131 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +00001132 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001133 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1134 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001135 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001136 else
Eugene Leviant9230db92016-11-17 09:16:34 +00001137 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +00001138 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +00001139 if (In<ELFT>::MipsRldMap)
1140 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001141 }
1142
Eugene Leviant6380ce22016-11-15 12:26:55 +00001143 this->OutSec->Link = this->Link;
1144
1145 // +1 for DT_NULL
1146 this->Size = (Entries.size() + 1) * this->Entsize;
1147}
1148
1149template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1150 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1151
1152 for (const Entry &E : Entries) {
1153 P->d_tag = E.Tag;
1154 switch (E.Kind) {
1155 case Entry::SecAddr:
1156 P->d_un.d_ptr = E.OutSec->Addr;
1157 break;
1158 case Entry::InSecAddr:
1159 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1160 break;
1161 case Entry::SecSize:
1162 P->d_un.d_val = E.OutSec->Size;
1163 break;
1164 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001165 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001166 break;
1167 case Entry::PlainInt:
1168 P->d_un.d_val = E.Val;
1169 break;
1170 }
1171 ++P;
1172 }
1173}
1174
George Rimar97def8c2017-03-17 12:07:44 +00001175uint64_t DynamicReloc::getOffset() const {
Rafael Espindolae1294092017-03-08 16:03:41 +00001176 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001177}
1178
George Rimar97def8c2017-03-17 12:07:44 +00001179int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001180 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001181 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001182 return Addend;
1183}
1184
George Rimar97def8c2017-03-17 12:07:44 +00001185uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001186 if (Sym && !UseSymVA)
1187 return Sym->DynsymIndex;
1188 return 0;
1189}
1190
1191template <class ELFT>
1192RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001193 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001194 sizeof(uintX_t), Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001195 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001196 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001197}
1198
1199template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001200void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001201 if (Reloc.Type == Target->RelativeRel)
1202 ++NumRelativeRelocs;
1203 Relocs.push_back(Reloc);
1204}
1205
1206template <class ELFT, class RelTy>
1207static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001208 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1209 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001210 if (AIsRel != BIsRel)
1211 return AIsRel;
1212
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001213 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001214}
1215
1216template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1217 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001218 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001219 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001220 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001221
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001222 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001223 P->r_addend = Rel.getAddend();
1224 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001225 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001226 // Dynamic relocation against MIPS GOT section make deal TLS entries
1227 // allocated in the end of the GOT. We need to adjust the offset to take
1228 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001229 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001230 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001231 }
1232
1233 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001234 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001235 std::stable_sort((Elf_Rela *)BufBegin,
1236 (Elf_Rela *)BufBegin + Relocs.size(),
1237 compRelocations<ELFT, Elf_Rela>);
1238 else
1239 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1240 compRelocations<ELFT, Elf_Rel>);
1241 }
1242}
1243
1244template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1245 return this->Entsize * Relocs.size();
1246}
1247
Rui Ueyama945055a2017-02-27 03:07:41 +00001248template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001249 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1250 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001251
1252 // Set required output section properties.
1253 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001254}
1255
Eugene Leviant9230db92016-11-17 09:16:34 +00001256template <class ELFT>
George Rimar49648002017-03-15 09:32:36 +00001257SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001258 : SyntheticSection(StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0,
1259 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1260 sizeof(uintX_t),
1261 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
Eugene Leviant9230db92016-11-17 09:16:34 +00001262 StrTabSec(StrTabSec) {
1263 this->Entsize = sizeof(Elf_Sym);
1264}
1265
1266// Orders symbols according to their positions in the GOT,
1267// in compliance with MIPS ABI rules.
1268// See "Global Offset Table" in Chapter 5 in the following document
1269// for detailed description:
1270// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001271static bool sortMipsSymbols(const SymbolTableEntry &L,
1272 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001273 // Sort entries related to non-local preemptible symbols by GOT indexes.
1274 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001275 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1276 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001277 if (LIsInLocalGot || RIsInLocalGot)
1278 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001279 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001280}
1281
Rui Ueyamabb07d102017-02-27 03:31:19 +00001282// Finalize a symbol table. The ELF spec requires that all local
1283// symbols precede global symbols, so we sort symbol entries in this
1284// function. (For .dynsym, we don't do that because symbols for
1285// dynamic linking are inherently all globals.)
Rui Ueyama945055a2017-02-27 03:07:41 +00001286template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001287 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001288
Rui Ueyama6e967342017-02-28 03:29:12 +00001289 // If it is a .dynsym, there should be no local symbols, but we need
1290 // to do a few things for the dynamic linker.
1291 if (this->Type == SHT_DYNSYM) {
1292 // Section's Info field has the index of the first non-local symbol.
1293 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001294 this->OutSec->Info = 1;
1295
1296 if (In<ELFT>::GnuHashTab) {
1297 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1298 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1299 } else if (Config->EMachine == EM_MIPS) {
1300 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1301 }
1302
1303 size_t I = 0;
1304 for (const SymbolTableEntry &S : Symbols)
1305 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001306 return;
Peter Smith55865432017-02-20 11:12:33 +00001307 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001308}
Peter Smith55865432017-02-20 11:12:33 +00001309
Peter Smith1ec42d92017-03-08 14:06:24 +00001310template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1311 if (this->Type == SHT_DYNSYM)
1312 return;
1313 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001314 auto It = std::stable_partition(
1315 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1316 return S.Symbol->isLocal() ||
1317 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1318 });
1319 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001320 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001321}
1322
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001323template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1324 // Adding a local symbol to a .dynsym is a bug.
1325 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001326
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001327 bool HashIt = B->isLocal();
1328 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001329}
1330
1331template <class ELFT>
1332size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001333 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1334 if (E.Symbol == Body)
1335 return true;
1336 // This is used for -r, so we have to handle multiple section
1337 // symbols being combined.
1338 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001339 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1340 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001341 return false;
1342 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001343 if (I == Symbols.end())
1344 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001345 return I - Symbols.begin() + 1;
1346}
1347
Rui Ueyama1f032532017-02-28 01:56:36 +00001348// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001349template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001350 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001351 Buf += sizeof(Elf_Sym);
1352
Eugene Leviant9230db92016-11-17 09:16:34 +00001353 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001354
Rui Ueyama1f032532017-02-28 01:56:36 +00001355 for (SymbolTableEntry &Ent : Symbols) {
1356 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001357
Rui Ueyama1b003182017-02-28 19:22:09 +00001358 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001359 if (Body->isLocal()) {
1360 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1361 } else {
1362 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1363 ESym->setVisibility(Body->symbol()->Visibility);
1364 }
1365
1366 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001367 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001368
Rui Ueyama1b003182017-02-28 19:22:09 +00001369 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001370 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001371 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001372 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001373 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001374 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001375 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001376
1377 // st_value is usually an address of a symbol, but that has a
1378 // special meaining for uninstantiated common symbols (this can
1379 // occur if -r is given).
1380 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001381 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001382 else
George Rimarf64618a2017-03-17 11:56:54 +00001383 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001384
Rui Ueyama1f032532017-02-28 01:56:36 +00001385 ++ESym;
1386 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001387
Rui Ueyama1f032532017-02-28 01:56:36 +00001388 // On MIPS we need to mark symbol which has a PLT entry and requires
1389 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1390 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1391 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1392 if (Config->EMachine == EM_MIPS) {
1393 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1394
1395 for (SymbolTableEntry &Ent : Symbols) {
1396 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001397 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001398 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001399
1400 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001401 if (auto *D = dyn_cast<DefinedRegular>(Body))
1402 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001403 ESym->st_other |= STO_MIPS_PIC;
1404 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001405 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001406 }
1407}
1408
Rui Ueyamae4120632017-02-28 22:05:13 +00001409// .hash and .gnu.hash sections contain on-disk hash tables that map
1410// symbol names to their dynamic symbol table indices. Their purpose
1411// is to help the dynamic linker resolve symbols quickly. If ELF files
1412// don't have them, the dynamic linker has to do linear search on all
1413// dynamic symbols, which makes programs slower. Therefore, a .hash
1414// section is added to a DSO by default. A .gnu.hash is added if you
1415// give the -hash-style=gnu or -hash-style=both option.
1416//
1417// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1418// Each ELF file has a list of DSOs that the ELF file depends on and a
1419// list of dynamic symbols that need to be resolved from any of the
1420// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1421// where m is the number of DSOs and n is the number of dynamic
1422// symbols. For modern large programs, both m and n are large. So
1423// making each step faster by using hash tables substiantially
1424// improves time to load programs.
1425//
1426// (Note that this is not the only way to design the shared library.
1427// For instance, the Windows DLL takes a different approach. On
1428// Windows, each dynamic symbol has a name of DLL from which the symbol
1429// has to be resolved. That makes the cost of symbol resolution O(n).
1430// This disables some hacky techniques you can use on Unix such as
1431// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1432//
1433// Due to historical reasons, we have two different hash tables, .hash
1434// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1435// and better version of .hash. .hash is just an on-disk hash table, but
1436// .gnu.hash has a bloom filter in addition to a hash table to skip
1437// DSOs very quickly. If you are sure that your dynamic linker knows
1438// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1439// safe bet is to specify -hash-style=both for backward compatibilty.
Eugene Leviant9230db92016-11-17 09:16:34 +00001440template <class ELFT>
Eugene Leviantbe809a72016-11-18 06:44:18 +00001441GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyama486369f2017-03-28 18:11:52 +00001442 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, sizeof(uintX_t), ".gnu.hash") {}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001443
Rui Ueyama945055a2017-02-27 03:07:41 +00001444template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001445 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001446
1447 // Computes bloom filter size in word size. We want to allocate 8
1448 // bits for each symbol. It must be a power of two.
1449 if (Symbols.empty())
1450 MaskWords = 1;
1451 else
1452 MaskWords = NextPowerOf2((Symbols.size() - 1) / sizeof(uintX_t));
1453
1454 Size = 16; // Header
1455 Size += sizeof(uintX_t) * MaskWords; // Bloom filter
1456 Size += NBuckets * 4; // Hash buckets
1457 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001458}
1459
1460template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001461 // Write a header.
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001462 const endianness E = ELFT::TargetEndianness;
1463 write32<E>(Buf, NBuckets);
1464 write32<E>(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size());
1465 write32<E>(Buf + 8, MaskWords);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001466 write32<E>(Buf + 12, getShift2());
1467 Buf += 16;
1468
Rui Ueyama7986b452017-03-01 18:09:09 +00001469 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001470 writeBloomFilter(Buf);
1471 Buf += sizeof(uintX_t) * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001472 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001473}
1474
Rui Ueyama7986b452017-03-01 18:09:09 +00001475// This function writes a 2-bit bloom filter. This bloom filter alone
1476// usually filters out 80% or more of all symbol lookups [1].
1477// The dynamic linker uses the hash table only when a symbol is not
1478// filtered out by a bloom filter.
1479//
1480// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1481// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
Eugene Leviantbe809a72016-11-18 06:44:18 +00001482template <class ELFT>
Rui Ueyamae13373b2017-03-01 02:51:42 +00001483void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001484 typedef typename ELFT::Off Elf_Off;
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001485 const unsigned C = sizeof(uintX_t) * 8;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001486
Rui Ueyamae13373b2017-03-01 02:51:42 +00001487 auto *Filter = reinterpret_cast<Elf_Off *>(Buf);
1488 for (const Entry &Sym : Symbols) {
1489 size_t I = (Sym.Hash / C) & (MaskWords - 1);
1490 Filter[I] |= uintX_t(1) << (Sym.Hash % C);
1491 Filter[I] |= uintX_t(1) << ((Sym.Hash >> getShift2()) % C);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001492 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001493}
1494
1495template <class ELFT>
1496void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001497 // A 32-bit integer type in the target endianness.
1498 typedef typename ELFT::Word Elf_Word;
1499
Rui Ueyamae13373b2017-03-01 02:51:42 +00001500 // Group symbols by hash value.
1501 std::vector<std::vector<Entry>> Syms(NBuckets);
1502 for (const Entry &Ent : Symbols)
1503 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001504
Rui Ueyamae13373b2017-03-01 02:51:42 +00001505 // Write hash buckets. Hash buckets contain indices in the following
1506 // hash value table.
1507 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
1508 for (size_t I = 0; I < NBuckets; ++I)
1509 if (!Syms[I].empty())
1510 Buckets[I] = Syms[I][0].Body->DynsymIndex;
1511
1512 // Write a hash value table. It represents a sequence of chains that
1513 // share the same hash modulo value. The last element of each chain
1514 // is terminated by LSB 1.
1515 Elf_Word *Values = Buckets + NBuckets;
1516 size_t I = 0;
1517 for (std::vector<Entry> &Vec : Syms) {
1518 if (Vec.empty())
1519 continue;
1520 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
1521 Values[I++] = Ent.Hash & ~1;
1522 Values[I++] = Vec.back().Hash | 1;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001523 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001524}
1525
1526static uint32_t hashGnu(StringRef Name) {
1527 uint32_t H = 5381;
1528 for (uint8_t C : Name)
1529 H = (H << 5) + H + C;
1530 return H;
1531}
1532
Rui Ueyamae13373b2017-03-01 02:51:42 +00001533// Returns a number of hash buckets to accomodate given number of elements.
1534// We want to choose a moderate number that is not too small (which
1535// causes too many hash collisions) and not too large (which wastes
1536// disk space.)
1537//
1538// We return a prime number because it (is believed to) achieve good
1539// hash distribution.
1540static size_t getBucketSize(size_t NumSymbols) {
1541 // List of largest prime numbers that are not greater than 2^n + 1.
1542 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1543 251, 127, 61, 31, 13, 7, 3, 1})
1544 if (N <= NumSymbols)
1545 return N;
1546 return 0;
1547}
1548
Eugene Leviantbe809a72016-11-18 06:44:18 +00001549// Add symbols to this symbol hash table. Note that this function
1550// destructively sort a given vector -- which is needed because
1551// GNU-style hash table places some sorting requirements.
1552template <class ELFT>
1553void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001554 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1555 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001556 std::vector<SymbolTableEntry>::iterator Mid =
1557 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1558 return S.Symbol->isUndefined();
1559 });
1560 if (Mid == V.end())
1561 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001562
1563 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1564 SymbolBody *B = Ent.Symbol;
1565 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001566 }
1567
Rui Ueyamae13373b2017-03-01 02:51:42 +00001568 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001569 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001570 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001571 return L.Hash % NBuckets < R.Hash % NBuckets;
1572 });
1573
1574 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001575 for (const Entry &Ent : Symbols)
1576 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001577}
1578
Eugene Leviantb96e8092016-11-18 09:06:47 +00001579template <class ELFT>
1580HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001581 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1582 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001583}
1584
Rui Ueyama945055a2017-02-27 03:07:41 +00001585template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001586 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001587
1588 unsigned NumEntries = 2; // nbucket and nchain.
1589 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1590
1591 // Create as many buckets as there are symbols.
1592 // FIXME: This is simplistic. We can try to optimize it, but implementing
1593 // support for SHT_GNU_HASH is probably even more profitable.
1594 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001595 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001596}
1597
1598template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001599 // A 32-bit integer type in the target endianness.
1600 typedef typename ELFT::Word Elf_Word;
1601
Eugene Leviantb96e8092016-11-18 09:06:47 +00001602 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001603
Eugene Leviantb96e8092016-11-18 09:06:47 +00001604 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1605 *P++ = NumSymbols; // nbucket
1606 *P++ = NumSymbols; // nchain
1607
1608 Elf_Word *Buckets = P;
1609 Elf_Word *Chains = P + NumSymbols;
1610
1611 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1612 SymbolBody *Body = S.Symbol;
1613 StringRef Name = Body->getName();
1614 unsigned I = Body->DynsymIndex;
1615 uint32_t Hash = hashSysV(Name) % NumSymbols;
1616 Chains[I] = Buckets[Hash];
1617 Buckets[Hash] = I;
1618 }
1619}
1620
George Rimardfc020e2017-03-17 11:01:57 +00001621PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001622 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001623 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001624
George Rimardfc020e2017-03-17 11:01:57 +00001625void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001626 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1627 // linker to resolve dynsyms at runtime. Write such code.
1628 if (HeaderSize != 0)
1629 Target->writePltHeader(Buf);
1630 size_t Off = HeaderSize;
1631 // The IPlt is immediately after the Plt, account for this in RelOff
1632 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001633
1634 for (auto &I : Entries) {
1635 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001636 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001637 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001638 uint64_t Plt = this->getVA() + Off;
1639 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1640 Off += Target->PltEntrySize;
1641 }
1642}
1643
George Rimardfc020e2017-03-17 11:01:57 +00001644template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001645 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001646 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1647 if (HeaderSize == 0) {
1648 PltRelocSection = In<ELFT>::RelaIplt;
1649 Sym.IsInIplt = true;
1650 }
1651 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001652 Entries.push_back(std::make_pair(&Sym, RelOff));
1653}
1654
George Rimardfc020e2017-03-17 11:01:57 +00001655size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001656 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001657}
1658
Peter Smith96943762017-01-25 10:31:16 +00001659// Some architectures such as additional symbols in the PLT section. For
1660// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001661void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001662 // The PLT may have symbols defined for the Header, the IPLT has no header
1663 if (HeaderSize != 0)
1664 Target->addPltHeaderSymbols(this);
1665 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001666 for (size_t I = 0; I < Entries.size(); ++I) {
1667 Target->addPltSymbols(this, Off);
1668 Off += Target->PltEntrySize;
1669 }
1670}
1671
George Rimardfc020e2017-03-17 11:01:57 +00001672unsigned PltSection::getPltRelocOff() const {
1673 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001674}
1675
George Rimar35e846e2017-03-21 08:19:34 +00001676GdbIndexSection::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001677 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001678 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001679
George Rimarec02b8d2016-12-15 12:07:53 +00001680// Iterative hash function for symbol's name is described in .gdb_index format
1681// specification. Note that we use one for version 5 to 7 here, it is different
1682// for version 4.
1683static uint32_t hash(StringRef Str) {
1684 uint32_t R = 0;
1685 for (uint8_t C : Str)
1686 R = R * 67 + tolower(C) - 113;
1687 return R;
1688}
1689
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001690static std::vector<std::pair<uint64_t, uint64_t>>
1691readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1692 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1693 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1694 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1695 return Ret;
1696}
1697
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001698static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1699 uint64_t Offset) {
1700 for (InputSectionBase *S : Arr)
1701 if (S && S != &InputSection::Discarded)
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001702 if (Offset >= S->getOffsetInFile() &&
1703 Offset < S->getOffsetInFile() + S->getSize())
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001704 return S;
1705 return nullptr;
1706}
1707
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001708static std::vector<AddressEntry>
1709readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1710 std::vector<AddressEntry> Ret;
1711
1712 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1713 DWARFAddressRangesVector Ranges;
1714 CU->collectAddressRanges(Ranges);
1715
George Rimar35e846e2017-03-21 08:19:34 +00001716 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001717 for (std::pair<uint64_t, uint64_t> &R : Ranges)
George Rimar8fe7aea2017-03-17 13:43:24 +00001718 if (InputSectionBase *S = findSection(Sections, R.first))
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001719 Ret.push_back({S, R.first - S->getOffsetInFile(),
1720 R.second - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001721 ++CurrentCU;
1722 }
1723 return Ret;
1724}
1725
1726static std::vector<std::pair<StringRef, uint8_t>>
1727readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1728 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1729 Dwarf.getGnuPubTypesSection()};
1730
1731 std::vector<std::pair<StringRef, uint8_t>> Ret;
1732 for (StringRef D : Data) {
1733 DWARFDebugPubTable PubTable(D, IsLE, true);
1734 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1735 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1736 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1737 }
1738 return Ret;
1739}
1740
1741class ObjInfoTy : public llvm::LoadedObjectInfo {
1742 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1743 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1744 if (S.getFlags() & ELF::SHF_ALLOC)
1745 return S.getOffset();
1746 return 0;
1747 }
1748
1749 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1750};
1751
George Rimar35e846e2017-03-21 08:19:34 +00001752void GdbIndexSection::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001753 Expected<std::unique_ptr<object::ObjectFile>> Obj =
George Rimar05423482017-03-20 10:47:00 +00001754 object::ObjectFile::createObjectFile(Sec->File->MB);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001755 if (!Obj) {
George Rimar05423482017-03-20 10:47:00 +00001756 error(toString(Sec->File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001757 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001758 }
1759
1760 ObjInfoTy ObjInfo;
1761 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001762
1763 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001764 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1765 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001766
George Rimar35e846e2017-03-21 08:19:34 +00001767 for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001768 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001769
1770 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
George Rimar35e846e2017-03-21 08:19:34 +00001771 readPubNamesAndTypes(Dwarf, Config->IsLE);
George Rimarec02b8d2016-12-15 12:07:53 +00001772
1773 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1774 uint32_t Hash = hash(Pair.first);
1775 size_t Offset = StringPool.add(Pair.first);
1776
1777 bool IsNew;
1778 GdbSymbol *Sym;
1779 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1780 if (IsNew) {
1781 Sym->CuVectorIndex = CuVectors.size();
1782 CuVectors.push_back({{CuId, Pair.second}});
1783 continue;
1784 }
1785
Rui Ueyamaaab18c02017-03-01 22:24:46 +00001786 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
George Rimarec02b8d2016-12-15 12:07:53 +00001787 }
Eugene Levianta113a412016-11-21 09:24:43 +00001788}
1789
George Rimar35e846e2017-03-21 08:19:34 +00001790void GdbIndexSection::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001791 if (Finalized)
1792 return;
1793 Finalized = true;
1794
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001795 for (InputSectionBase *S : InputSections)
1796 if (InputSection *IS = dyn_cast<InputSection>(S))
1797 if (IS->OutSec && IS->Name == ".debug_info")
1798 readDwarf(IS);
1799
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001800 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001801
1802 // GdbIndex header consist from version fields
1803 // and 5 more fields with different kinds of offsets.
1804 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001805 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001806
1807 ConstantPoolOffset =
1808 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1809
1810 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1811 CuVectorsOffset.push_back(CuVectorsSize);
1812 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1813 }
1814 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1815
1816 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001817}
1818
George Rimar35e846e2017-03-21 08:19:34 +00001819size_t GdbIndexSection::getSize() const {
1820 const_cast<GdbIndexSection *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001821 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001822}
1823
George Rimar35e846e2017-03-21 08:19:34 +00001824void GdbIndexSection::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001825 write32le(Buf, 7); // Write version.
1826 write32le(Buf + 4, CuListOffset); // CU list offset.
1827 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1828 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1829 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1830 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001831 Buf += 24;
1832
1833 // Write the CU list.
George Rimarf6abfd72017-03-20 10:40:40 +00001834 for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
Eugene Levianta113a412016-11-21 09:24:43 +00001835 write64le(Buf, CU.first);
1836 write64le(Buf + 8, CU.second);
1837 Buf += 16;
1838 }
George Rimar8b547392016-12-15 09:08:13 +00001839
1840 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001841 for (AddressEntry &E : AddressArea) {
George Rimarf6abfd72017-03-20 10:40:40 +00001842 uint64_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001843 write64le(Buf, BaseAddr + E.LowAddress);
1844 write64le(Buf + 8, BaseAddr + E.HighAddress);
1845 write32le(Buf + 16, E.CuIndex);
1846 Buf += 20;
1847 }
George Rimarec02b8d2016-12-15 12:07:53 +00001848
1849 // Write the symbol table.
1850 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1851 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1852 if (Sym) {
1853 size_t NameOffset =
1854 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1855 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1856 write32le(Buf, NameOffset);
1857 write32le(Buf + 4, CuVectorOffset);
1858 }
1859 Buf += 8;
1860 }
1861
1862 // Write the CU vectors into the constant pool.
1863 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1864 write32le(Buf, CuVec.size());
1865 Buf += 4;
1866 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1867 uint32_t Index = P.first;
1868 uint8_t Flags = P.second;
1869 Index |= Flags << 24;
1870 write32le(Buf, Index);
1871 Buf += 4;
1872 }
1873 }
1874
1875 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001876}
1877
George Rimar35e846e2017-03-21 08:19:34 +00001878bool GdbIndexSection::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001879 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001880}
1881
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001882template <class ELFT>
1883EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001884 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001885
1886// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1887// Each entry of the search table consists of two values,
1888// the starting PC from where FDEs covers, and the FDE's address.
1889// It is sorted by PC.
1890template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1891 const endianness E = ELFT::TargetEndianness;
1892
1893 // Sort the FDE list by their PC and uniqueify. Usually there is only
1894 // one FDE for a PC (i.e. function), but if ICF merges two functions
1895 // into one, there can be more than one FDEs pointing to the address.
1896 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1897 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1898 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1899 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1900
1901 Buf[0] = 1;
1902 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1903 Buf[2] = DW_EH_PE_udata4;
1904 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001905 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001906 write32<E>(Buf + 8, Fdes.size());
1907 Buf += 12;
1908
1909 uintX_t VA = this->getVA();
1910 for (FdeData &Fde : Fdes) {
1911 write32<E>(Buf, Fde.Pc - VA);
1912 write32<E>(Buf + 4, Fde.FdeVA - VA);
1913 Buf += 8;
1914 }
1915}
1916
1917template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1918 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001919 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001920}
1921
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001922template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001923void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1924 Fdes.push_back({Pc, FdeVA});
1925}
1926
George Rimar11992c862016-11-25 08:05:41 +00001927template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001928 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001929}
1930
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001931template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001932VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001933 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1934 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001935
1936static StringRef getFileDefName() {
1937 if (!Config->SoName.empty())
1938 return Config->SoName;
1939 return Config->OutputFile;
1940}
1941
Rui Ueyama945055a2017-02-27 03:07:41 +00001942template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001943 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1944 for (VersionDefinition &V : Config->VersionDefinitions)
1945 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1946
Rui Ueyamac3726f82017-02-28 04:41:20 +00001947 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001948
1949 // sh_info should be set to the number of definitions. This fact is missed in
1950 // documentation, but confirmed by binutils community:
1951 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001952 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001953}
1954
1955template <class ELFT>
1956void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1957 StringRef Name, size_t NameOff) {
1958 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1959 Verdef->vd_version = 1;
1960 Verdef->vd_cnt = 1;
1961 Verdef->vd_aux = sizeof(Elf_Verdef);
1962 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1963 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1964 Verdef->vd_ndx = Index;
1965 Verdef->vd_hash = hashSysV(Name);
1966
1967 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1968 Verdaux->vda_name = NameOff;
1969 Verdaux->vda_next = 0;
1970}
1971
1972template <class ELFT>
1973void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1974 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1975
1976 for (VersionDefinition &V : Config->VersionDefinitions) {
1977 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1978 writeOne(Buf, V.Id, V.Name, V.NameOff);
1979 }
1980
1981 // Need to terminate the last version definition.
1982 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1983 Verdef->vd_next = 0;
1984}
1985
1986template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1987 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1988}
1989
1990template <class ELFT>
1991VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001992 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00001993 ".gnu.version") {
1994 this->Entsize = sizeof(Elf_Versym);
1995}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001996
Rui Ueyama945055a2017-02-27 03:07:41 +00001997template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001998 // At the moment of june 2016 GNU docs does not mention that sh_link field
1999 // should be set, but Sun docs do. Also readelf relies on this field.
Rui Ueyamac3726f82017-02-28 04:41:20 +00002000 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002001}
2002
2003template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2004 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2005}
2006
2007template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2008 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2009 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2010 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2011 ++OutVersym;
2012 }
2013}
2014
George Rimar11992c862016-11-25 08:05:41 +00002015template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2016 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2017}
2018
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002019template <class ELFT>
2020VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002021 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2022 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002023 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2024 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2025 // First identifiers are reserved by verdef section if it exist.
2026 NextIndex = getVerDefNum() + 1;
2027}
2028
2029template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002030void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2031 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2032 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002033 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2034 return;
2035 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002036
2037 auto *File = cast<SharedFile<ELFT>>(SS->File);
2038
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002039 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2040 // to create one by adding it to our needed list and creating a dynstr entry
2041 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002042 if (File->VerdefMap.empty())
2043 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->getSoName())});
2044 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002045 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2046 // prepare to create one by allocating a version identifier and creating a
2047 // dynstr entry for the version name.
2048 if (NV.Index == 0) {
Rui Ueyama4076fa12017-02-26 23:35:34 +00002049 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2050 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002051 NV.Index = NextIndex++;
2052 }
2053 SS->symbol()->VersionId = NV.Index;
2054}
2055
2056template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2057 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2058 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2059 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2060
2061 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2062 // Create an Elf_Verneed for this DSO.
2063 Verneed->vn_version = 1;
2064 Verneed->vn_cnt = P.first->VerdefMap.size();
2065 Verneed->vn_file = P.second;
2066 Verneed->vn_aux =
2067 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2068 Verneed->vn_next = sizeof(Elf_Verneed);
2069 ++Verneed;
2070
2071 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2072 // VerdefMap, which will only contain references to needed version
2073 // definitions. Each Elf_Vernaux is based on the information contained in
2074 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2075 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2076 // data structures within a single input file.
2077 for (auto &NV : P.first->VerdefMap) {
2078 Vernaux->vna_hash = NV.first->vd_hash;
2079 Vernaux->vna_flags = 0;
2080 Vernaux->vna_other = NV.second.Index;
2081 Vernaux->vna_name = NV.second.StrTab;
2082 Vernaux->vna_next = sizeof(Elf_Vernaux);
2083 ++Vernaux;
2084 }
2085
2086 Vernaux[-1].vna_next = 0;
2087 }
2088 Verneed[-1].vn_next = 0;
2089}
2090
Rui Ueyama945055a2017-02-27 03:07:41 +00002091template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00002092 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2093 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002094}
2095
2096template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2097 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2098 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2099 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2100 return Size;
2101}
2102
George Rimar11992c862016-11-25 08:05:41 +00002103template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2104 return getNeedNum() == 0;
2105}
2106
Rafael Espindola6119b862017-03-06 20:23:56 +00002107MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002108 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002109 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002110 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002111
Rafael Espindola6119b862017-03-06 20:23:56 +00002112void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002113 assert(!Finalized);
2114 MS->MergeSec = this;
2115 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002116}
2117
Rafael Espindola6119b862017-03-06 20:23:56 +00002118void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002119
Rafael Espindola6119b862017-03-06 20:23:56 +00002120bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002121 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2122}
2123
Rafael Espindola6119b862017-03-06 20:23:56 +00002124void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002125 // Add all string pieces to the string table builder to create section
2126 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002127 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002128 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2129 if (Sec->Pieces[I].Live)
2130 Builder.add(Sec->getData(I));
2131
2132 // Fix the string table content. After this, the contents will never change.
2133 Builder.finalize();
2134
2135 // finalize() fixed tail-optimized strings, so we can now get
2136 // offsets of strings. Get an offset for each string and save it
2137 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002138 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002139 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2140 if (Sec->Pieces[I].Live)
2141 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2142}
2143
Rafael Espindola6119b862017-03-06 20:23:56 +00002144void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002145 // Add all string pieces to the string table builder to create section
2146 // contents. Because we are not tail-optimizing, offsets of strings are
2147 // fixed when they are added to the builder (string table builder contains
2148 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002149 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002150 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2151 if (Sec->Pieces[I].Live)
2152 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2153
2154 Builder.finalizeInOrder();
2155}
2156
Rafael Espindola6119b862017-03-06 20:23:56 +00002157void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002158 if (Finalized)
2159 return;
2160 Finalized = true;
2161 if (shouldTailMerge())
2162 finalizeTailMerge();
2163 else
2164 finalizeNoTailMerge();
2165}
2166
Rafael Espindola6119b862017-03-06 20:23:56 +00002167size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002168 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002169 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002170 return Builder.getSize();
2171}
2172
George Rimar42886c42017-03-15 12:02:31 +00002173MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002174 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2175 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002176
George Rimar42886c42017-03-15 12:02:31 +00002177void MipsRldMapSection::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00002178 // Apply filler from linker script.
George Rimara8dba482017-03-20 10:09:58 +00002179 uint64_t Filler = Script->getFiller(this->Name);
Eugene Leviant17b7a572016-11-22 17:49:14 +00002180 Filler = (Filler << 32) | Filler;
2181 memcpy(Buf, &Filler, getSize());
2182}
2183
George Rimar90a528b2017-03-21 09:01:39 +00002184ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002185 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002186 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002187
2188// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2189// This section will have been sorted last in the .ARM.exidx table.
2190// This table entry will have the form:
2191// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
George Rimar90a528b2017-03-21 09:01:39 +00002192void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smith719eb8e2016-11-24 11:43:55 +00002193 // Get the InputSection before us, we are by definition last
Rafael Espindola24e6f362017-02-24 15:07:30 +00002194 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002195 InputSection *LE = *(++RI);
George Rimar9353e2d2017-03-21 08:29:48 +00002196 InputSection *LC = cast<InputSection>(LE->getLinkOrderDep());
Rafael Espindolae1294092017-03-08 16:03:41 +00002197 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
Peter Smith719eb8e2016-11-24 11:43:55 +00002198 uint64_t P = this->getVA();
2199 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2200 write32le(Buf + 4, 0x1);
2201}
2202
George Rimar7b827042017-03-16 10:40:50 +00002203ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002204 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002205 Config->Wordsize, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002206 this->OutSec = OS;
2207 this->OutSecOff = Off;
2208}
2209
George Rimar7b827042017-03-16 10:40:50 +00002210void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002211 uint64_t Off = alignTo(Size, T->alignment);
2212 T->Offset = Off;
2213 Thunks.push_back(T);
2214 T->addSymbols(*this);
2215 Size = Off + T->size();
2216}
2217
George Rimar7b827042017-03-16 10:40:50 +00002218void ThunkSection::writeTo(uint8_t *Buf) {
2219 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002220 T->writeTo(Buf + T->Offset, *this);
2221}
2222
George Rimar7b827042017-03-16 10:40:50 +00002223InputSection *ThunkSection::getTargetInputSection() const {
2224 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002225 return T->getTargetInputSection();
2226}
2227
George Rimar9782ca52017-03-15 15:29:29 +00002228InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002229BssSection *InX::Bss;
2230BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002231BuildIdSection *InX::BuildId;
George Rimar9782ca52017-03-15 15:29:29 +00002232InputSection *InX::Common;
2233StringTableSection *InX::DynStrTab;
2234InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002235GdbIndexSection *InX::GdbIndex;
George Rimar9782ca52017-03-15 15:29:29 +00002236GotPltSection *InX::GotPlt;
2237IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002238MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002239MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002240PltSection *InX::Plt;
2241PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002242StringTableSection *InX::ShStrTab;
2243StringTableSection *InX::StrTab;
2244
George Rimara9189572017-03-17 16:50:07 +00002245template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2246template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2247template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2248template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2249
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002250template InputSection *elf::createCommonSection<ELF32LE>();
2251template InputSection *elf::createCommonSection<ELF32BE>();
2252template InputSection *elf::createCommonSection<ELF64LE>();
2253template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002254
Rafael Espindola6119b862017-03-06 20:23:56 +00002255template MergeInputSection *elf::createCommentSection<ELF32LE>();
2256template MergeInputSection *elf::createCommentSection<ELF32BE>();
2257template MergeInputSection *elf::createCommentSection<ELF64LE>();
2258template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002259
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002260template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002261 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002262 InputSectionBase *);
2263template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002264 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002265 InputSectionBase *);
2266template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002267 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002268 InputSectionBase *);
2269template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002270 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002271 InputSectionBase *);
Peter Smith96943762017-01-25 10:31:16 +00002272
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002273template class elf::MipsAbiFlagsSection<ELF32LE>;
2274template class elf::MipsAbiFlagsSection<ELF32BE>;
2275template class elf::MipsAbiFlagsSection<ELF64LE>;
2276template class elf::MipsAbiFlagsSection<ELF64BE>;
2277
Simon Atanasyance02cf02016-11-09 21:36:56 +00002278template class elf::MipsOptionsSection<ELF32LE>;
2279template class elf::MipsOptionsSection<ELF32BE>;
2280template class elf::MipsOptionsSection<ELF64LE>;
2281template class elf::MipsOptionsSection<ELF64BE>;
2282
2283template class elf::MipsReginfoSection<ELF32LE>;
2284template class elf::MipsReginfoSection<ELF32BE>;
2285template class elf::MipsReginfoSection<ELF64LE>;
2286template class elf::MipsReginfoSection<ELF64BE>;
2287
Eugene Leviantad4439e2016-11-11 11:33:32 +00002288template class elf::GotSection<ELF32LE>;
2289template class elf::GotSection<ELF32BE>;
2290template class elf::GotSection<ELF64LE>;
2291template class elf::GotSection<ELF64BE>;
2292
Eugene Leviant6380ce22016-11-15 12:26:55 +00002293template class elf::DynamicSection<ELF32LE>;
2294template class elf::DynamicSection<ELF32BE>;
2295template class elf::DynamicSection<ELF64LE>;
2296template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002297
2298template class elf::RelocationSection<ELF32LE>;
2299template class elf::RelocationSection<ELF32BE>;
2300template class elf::RelocationSection<ELF64LE>;
2301template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002302
2303template class elf::SymbolTableSection<ELF32LE>;
2304template class elf::SymbolTableSection<ELF32BE>;
2305template class elf::SymbolTableSection<ELF64LE>;
2306template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002307
2308template class elf::GnuHashTableSection<ELF32LE>;
2309template class elf::GnuHashTableSection<ELF32BE>;
2310template class elf::GnuHashTableSection<ELF64LE>;
2311template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002312
2313template class elf::HashTableSection<ELF32LE>;
2314template class elf::HashTableSection<ELF32BE>;
2315template class elf::HashTableSection<ELF64LE>;
2316template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002317
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002318template class elf::EhFrameHeader<ELF32LE>;
2319template class elf::EhFrameHeader<ELF32BE>;
2320template class elf::EhFrameHeader<ELF64LE>;
2321template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002322
2323template class elf::VersionTableSection<ELF32LE>;
2324template class elf::VersionTableSection<ELF32BE>;
2325template class elf::VersionTableSection<ELF64LE>;
2326template class elf::VersionTableSection<ELF64BE>;
2327
2328template class elf::VersionNeedSection<ELF32LE>;
2329template class elf::VersionNeedSection<ELF32BE>;
2330template class elf::VersionNeedSection<ELF64LE>;
2331template class elf::VersionNeedSection<ELF64BE>;
2332
2333template class elf::VersionDefinitionSection<ELF32LE>;
2334template class elf::VersionDefinitionSection<ELF32BE>;
2335template class elf::VersionDefinitionSection<ELF64LE>;
2336template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002337
Rafael Espindola66b4e212017-02-23 22:06:28 +00002338template class elf::EhFrameSection<ELF32LE>;
2339template class elf::EhFrameSection<ELF32BE>;
2340template class elf::EhFrameSection<ELF64LE>;
2341template class elf::EhFrameSection<ELF64BE>;