blob: e137f59cdf0ea05e0c24a65236df2eacca27b527 [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
Rui Ueyama42fca6e2017-04-27 04:50:08 +0000100// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +0000101// 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 Ueyama6022b2b2017-03-29 00:49:50 +0000370size_t BssSection::reserveSpace(uint64_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;
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000374 this->Alignment = std::max(this->Alignment, Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000375 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;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000537 Off += alignTo(Cie->Piece->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000538
539 for (EhSectionPiece *Fde : Cie->FdePieces) {
540 Fde->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000541 Off += alignTo(Fde->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000542 }
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>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000567uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
568 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000569 // 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) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000606 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
607 uint64_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000608 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;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000638 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000639 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640 return true;
641}
642
Eugene Leviantad4439e2016-11-11 11:33:32 +0000643template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000644uint64_t GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
645 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000646}
647
648template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000649uint64_t GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
650 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000651}
652
Rui Ueyama945055a2017-02-27 03:07:41 +0000653template <class ELFT> void GotSection<ELFT>::finalizeContents() {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000654 Size = NumEntries * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000655}
656
George Rimar11992c862016-11-25 08:05:41 +0000657template <class ELFT> bool GotSection<ELFT>::empty() const {
658 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
659 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000660 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000661}
662
Simon Atanasyan725dc142016-11-16 21:01:02 +0000663template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000664 this->template relocate<ELFT>(Buf, Buf + Size);
Simon Atanasyan725dc142016-11-16 21:01:02 +0000665}
666
George Rimar14534eb2017-03-20 16:44:28 +0000667MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000668 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
669 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000670
George Rimar14534eb2017-03-20 16:44:28 +0000671void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000672 // For "true" local symbols which can be referenced from the same module
673 // only compiler creates two instructions for address loading:
674 //
675 // lw $8, 0($gp) # R_MIPS_GOT16
676 // addi $8, $8, 0 # R_MIPS_LO16
677 //
678 // The first instruction loads high 16 bits of the symbol address while
679 // the second adds an offset. That allows to reduce number of required
680 // GOT entries because only one global offset table entry is necessary
681 // for every 64 KBytes of local data. So for local symbols we need to
682 // allocate number of GOT entries to hold all required "page" addresses.
683 //
684 // All global symbols (hidden and regular) considered by compiler uniformly.
685 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
686 // to load address of the symbol. So for each such symbol we need to
687 // allocate dedicated GOT entry to store its address.
688 //
689 // If a symbol is preemptible we need help of dynamic linker to get its
690 // final address. The corresponding GOT entries are allocated in the
691 // "global" part of GOT. Entries for non preemptible global symbol allocated
692 // in the "local" part of GOT.
693 //
694 // See "Global Offset Table" in Chapter 5:
695 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
696 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
697 // At this point we do not know final symbol value so to reduce number
698 // of allocated GOT entries do the following trick. Save all output
699 // sections referenced by GOT relocations. Then later in the `finalize`
700 // method calculate number of "pages" required to cover all saved output
701 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000702 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000703 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000704 return;
705 }
706 if (Sym.isTls()) {
707 // GOT entries created for MIPS TLS relocations behave like
708 // almost GOT entries from other ABIs. They go to the end
709 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000710 Sym.GotIndex = TlsEntries.size();
711 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000712 return;
713 }
George Rimar14534eb2017-03-20 16:44:28 +0000714 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000715 if (S.isInGot() && !A)
716 return;
717 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000718 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000719 return;
720 Items.emplace_back(&S, A);
721 if (!A)
722 S.GotIndex = NewIndex;
723 };
724 if (Sym.isPreemptible()) {
725 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000726 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000727 Sym.IsInGlobalMipsGot = true;
728 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000729 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000730 Sym.Is32BitMipsGot = true;
731 } else {
732 // Hold local GOT entries accessed via a 16-bit index separately.
733 // That allows to write them in the beginning of the GOT and keep
734 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000735 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000736 }
737}
738
George Rimar14534eb2017-03-20 16:44:28 +0000739bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000740 if (Sym.GlobalDynIndex != -1U)
741 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000742 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000743 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000744 TlsEntries.push_back(nullptr);
745 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000746 return true;
747}
748
749// Reserves TLS entries for a TLS module ID and a TLS block offset.
750// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000751bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000752 if (TlsIndexOff != uint32_t(-1))
753 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000754 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000755 TlsEntries.push_back(nullptr);
756 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000757 return true;
758}
759
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000760static uint64_t getMipsPageAddr(uint64_t Addr) {
761 return (Addr + 0x8000) & ~0xffff;
762}
763
764static uint64_t getMipsPageCount(uint64_t Size) {
765 return (Size + 0xfffe) / 0xffff + 1;
766}
767
George Rimar14534eb2017-03-20 16:44:28 +0000768uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
769 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000770 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000771 cast<DefinedRegular>(&B)->Section->getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000772 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
773 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
774 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000775 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000776 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000777}
778
George Rimar14534eb2017-03-20 16:44:28 +0000779uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
780 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000781 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000782 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000784 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000785 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000786 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000787 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000788 Index += LocalEntries.size();
789 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000791 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000792 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000793 auto It = EntryIndexMap.find({&B, Addend});
794 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000795 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000796 }
George Rimar14534eb2017-03-20 16:44:28 +0000797 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000798}
799
George Rimar14534eb2017-03-20 16:44:28 +0000800uint64_t MipsGotSection::getTlsOffset() const {
801 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000802}
803
George Rimar14534eb2017-03-20 16:44:28 +0000804uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
805 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000806}
807
George Rimar14534eb2017-03-20 16:44:28 +0000808const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000809 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000810}
811
George Rimar14534eb2017-03-20 16:44:28 +0000812unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000813 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
814 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000815}
816
George Rimar14534eb2017-03-20 16:44:28 +0000817void MipsGotSection::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000818 updateAllocSize();
819}
820
George Rimar14534eb2017-03-20 16:44:28 +0000821void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000822 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000823 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000824 // For each output section referenced by GOT page relocations calculate
825 // and save into PageIndexMap an upper bound of MIPS GOT entries required
826 // to store page addresses of local symbols. We assume the worst case -
827 // each 64kb page of the output section has at least one GOT relocation
828 // against it. And take in account the case when the section intersects
829 // page boundaries.
830 P.second = PageEntriesNum;
831 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000832 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000833 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000834 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000835}
836
George Rimar14534eb2017-03-20 16:44:28 +0000837bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000838 // We add the .got section to the result for dynamic MIPS target because
839 // its address and properties are mentioned in the .dynamic section.
840 return Config->Relocatable;
841}
842
George Rimar14534eb2017-03-20 16:44:28 +0000843uint64_t MipsGotSection::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000844 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000845}
846
George Rimar5f73bc92017-03-29 15:23:28 +0000847static uint64_t readUint(uint8_t *Buf) {
848 if (Config->Is64)
849 return read64(Buf, Config->Endianness);
850 return read32(Buf, Config->Endianness);
851}
852
George Rimar14534eb2017-03-20 16:44:28 +0000853static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000854 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000855 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000856 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000857 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000858}
859
George Rimar14534eb2017-03-20 16:44:28 +0000860void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000861 // Set the MSB of the second GOT slot. This is not required by any
862 // MIPS ABI documentation, though.
863 //
864 // There is a comment in glibc saying that "The MSB of got[1] of a
865 // gnu object is set to identify gnu objects," and in GNU gold it
866 // says "the second entry will be used by some runtime loaders".
867 // But how this field is being used is unclear.
868 //
869 // We are not really willing to mimic other linkers behaviors
870 // without understanding why they do that, but because all files
871 // generated by GNU tools have this special GOT value, and because
872 // we've been doing this for years, it is probably a safe bet to
873 // keep doing this for now. We really need to revisit this to see
874 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000875 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
876 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000877 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000878 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000879 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000880 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000881 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000882 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
883 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000884 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000885 }
George Rimar14534eb2017-03-20 16:44:28 +0000886 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000887 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000888 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000889 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000890 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000891 uint64_t VA = Body->getVA(SA.second);
892 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000893 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000894 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
895 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
896 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000897 // Initialize TLS-related GOT entries. If the entry has a corresponding
898 // dynamic relocations, leave it initialized by zero. Write down adjusted
899 // TLS symbol's values otherwise. To calculate the adjustments use offsets
900 // for thread-local storage.
901 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000902 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000903 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000904 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000905 if (!B || B->isPreemptible())
906 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000907 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000908 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000909 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
910 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000911 }
912 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000913 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
914 writeUint(Entry, 1);
915 Entry += Config->Wordsize;
916 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000917 }
918 }
919}
920
George Rimar10f74fc2017-03-15 09:12:56 +0000921GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000922 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
923 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000924
George Rimar10f74fc2017-03-15 09:12:56 +0000925void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000926 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
927 Entries.push_back(&Sym);
928}
929
George Rimar10f74fc2017-03-15 09:12:56 +0000930size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000931 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
932 Target->GotPltEntrySize;
933}
934
George Rimar10f74fc2017-03-15 09:12:56 +0000935void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000936 Target->writeGotPltHeader(Buf);
937 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
938 for (const SymbolBody *B : Entries) {
939 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000940 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000941 }
942}
943
Peter Smithbaffdb82016-12-08 12:58:55 +0000944// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
945// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000946IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000947 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
948 Target->GotPltEntrySize,
949 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000950
George Rimar10f74fc2017-03-15 09:12:56 +0000951void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000952 Sym.IsInIgot = true;
953 Sym.GotPltIndex = Entries.size();
954 Entries.push_back(&Sym);
955}
956
George Rimar10f74fc2017-03-15 09:12:56 +0000957size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000958 return Entries.size() * Target->GotPltEntrySize;
959}
960
George Rimar10f74fc2017-03-15 09:12:56 +0000961void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000962 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000963 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000964 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000965 }
966}
967
George Rimar49648002017-03-15 09:32:36 +0000968StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
969 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000970 Dynamic(Dynamic) {
971 // ELF string tables start with a NUL byte.
972 addString("");
973}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000974
975// Adds a string to the string table. If HashIt is true we hash and check for
976// duplicates. It is optional because the name of global symbols are already
977// uniqued and hashing them again has a big cost for a small value: uniquing
978// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000979unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000980 if (HashIt) {
981 auto R = StringMap.insert(std::make_pair(S, this->Size));
982 if (!R.second)
983 return R.first->second;
984 }
985 unsigned Ret = this->Size;
986 this->Size = this->Size + S.size() + 1;
987 Strings.push_back(S);
988 return Ret;
989}
990
George Rimar49648002017-03-15 09:32:36 +0000991void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000992 for (StringRef S : Strings) {
993 memcpy(Buf, S.data(), S.size());
994 Buf += S.size() + 1;
995 }
996}
997
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000998// Returns the number of version definition entries. Because the first entry
999// is for the version definition itself, it is the number of versioned symbols
1000// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001001static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1002
1003template <class ELFT>
1004DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001005 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001006 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001007 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001008
Eugene Leviant6380ce22016-11-15 12:26:55 +00001009 // .dynamic section is not writable on MIPS.
1010 // See "Special Section" in Chapter 4 in the following document:
1011 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1012 if (Config->EMachine == EM_MIPS)
1013 this->Flags = SHF_ALLOC;
1014
1015 addEntries();
1016}
1017
1018// There are some dynamic entries that don't depend on other sections.
1019// Such entries can be set early.
1020template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1021 // Add strings to .dynstr early so that .dynstr's size will be
1022 // fixed early.
1023 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama729ac792016-11-17 04:10:09 +00001024 add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001025 if (!Config->RPath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001026 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001027 In<ELFT>::DynStrTab->addString(Config->RPath)});
1028 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1029 if (F->isNeeded())
Rafael Espindola3460cdd2017-04-24 21:44:20 +00001030 add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001031 if (!Config->SoName.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001032 add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001033
1034 // Set DT_FLAGS and DT_FLAGS_1.
1035 uint32_t DtFlags = 0;
1036 uint32_t DtFlags1 = 0;
1037 if (Config->Bsymbolic)
1038 DtFlags |= DF_SYMBOLIC;
1039 if (Config->ZNodelete)
1040 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001041 if (Config->ZNodlopen)
1042 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001043 if (Config->ZNow) {
1044 DtFlags |= DF_BIND_NOW;
1045 DtFlags1 |= DF_1_NOW;
1046 }
1047 if (Config->ZOrigin) {
1048 DtFlags |= DF_ORIGIN;
1049 DtFlags1 |= DF_1_ORIGIN;
1050 }
1051
1052 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001053 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001054 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001055 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001056
Petr Hosek668bebe2016-12-07 02:05:42 +00001057 if (!Config->Shared && !Config->Relocatable)
Rui Ueyama729ac792016-11-17 04:10:09 +00001058 add({DT_DEBUG, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001059}
1060
1061// Add remaining entries to complete .dynamic contents.
Rui Ueyama945055a2017-02-27 03:07:41 +00001062template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001063 if (this->Size)
1064 return; // Already finalized.
1065
1066 this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001067 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001068 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001069 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001070 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001071 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001072 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001073
1074 // MIPS dynamic loader does not support RELCOUNT tag.
1075 // The problem is in the tight relation between dynamic
1076 // relocations and GOT. So do not emit this tag on MIPS.
1077 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001078 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001079 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001080 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001081 }
1082 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001083 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001084 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001085 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001086 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant6380ce22016-11-15 12:26:55 +00001087 In<ELFT>::GotPlt});
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001088 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001089 }
1090
Eugene Leviant9230db92016-11-17 09:16:34 +00001091 add({DT_SYMTAB, In<ELFT>::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001092 add({DT_SYMENT, sizeof(Elf_Sym)});
1093 add({DT_STRTAB, In<ELFT>::DynStrTab});
1094 add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001095 if (!Config->ZText)
1096 add({DT_TEXTREL, (uint64_t)0});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001097 if (In<ELFT>::GnuHashTab)
1098 add({DT_GNU_HASH, In<ELFT>::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001099 if (In<ELFT>::HashTab)
1100 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001101
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001102 if (Out::PreinitArray) {
1103 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1104 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001105 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001106 if (Out::InitArray) {
1107 add({DT_INIT_ARRAY, Out::InitArray});
1108 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001109 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001110 if (Out::FiniArray) {
1111 add({DT_FINI_ARRAY, Out::FiniArray});
1112 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001113 }
1114
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001115 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001116 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001117 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001118 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001119
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001120 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1121 if (HasVerNeed || In<ELFT>::VerDef)
1122 add({DT_VERSYM, In<ELFT>::VerSym});
1123 if (In<ELFT>::VerDef) {
1124 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001125 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001126 }
1127 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001128 add({DT_VERNEED, In<ELFT>::VerNeed});
1129 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001130 }
1131
1132 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001133 add({DT_MIPS_RLD_VERSION, 1});
1134 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1135 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Eugene Leviant9230db92016-11-17 09:16:34 +00001136 add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()});
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001137 add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()});
1138 if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001139 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001140 else
Eugene Leviant9230db92016-11-17 09:16:34 +00001141 add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()});
Rui Ueyama729ac792016-11-17 04:10:09 +00001142 add({DT_PLTGOT, In<ELFT>::MipsGot});
Eugene Leviant17b7a572016-11-22 17:49:14 +00001143 if (In<ELFT>::MipsRldMap)
1144 add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001145 }
1146
Eugene Leviant6380ce22016-11-15 12:26:55 +00001147 this->OutSec->Link = this->Link;
1148
1149 // +1 for DT_NULL
1150 this->Size = (Entries.size() + 1) * this->Entsize;
1151}
1152
1153template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1154 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1155
1156 for (const Entry &E : Entries) {
1157 P->d_tag = E.Tag;
1158 switch (E.Kind) {
1159 case Entry::SecAddr:
1160 P->d_un.d_ptr = E.OutSec->Addr;
1161 break;
1162 case Entry::InSecAddr:
1163 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1164 break;
1165 case Entry::SecSize:
1166 P->d_un.d_val = E.OutSec->Size;
1167 break;
1168 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001169 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001170 break;
1171 case Entry::PlainInt:
1172 P->d_un.d_val = E.Val;
1173 break;
1174 }
1175 ++P;
1176 }
1177}
1178
George Rimar97def8c2017-03-17 12:07:44 +00001179uint64_t DynamicReloc::getOffset() const {
Rafael Espindolae1294092017-03-08 16:03:41 +00001180 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001181}
1182
George Rimar97def8c2017-03-17 12:07:44 +00001183int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001184 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001185 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001186 return Addend;
1187}
1188
George Rimar97def8c2017-03-17 12:07:44 +00001189uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001190 if (Sym && !UseSymVA)
1191 return Sym->DynsymIndex;
1192 return 0;
1193}
1194
1195template <class ELFT>
1196RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001197 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001198 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001199 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001200 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001201}
1202
1203template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001204void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001205 if (Reloc.Type == Target->RelativeRel)
1206 ++NumRelativeRelocs;
1207 Relocs.push_back(Reloc);
1208}
1209
1210template <class ELFT, class RelTy>
1211static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001212 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1213 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001214 if (AIsRel != BIsRel)
1215 return AIsRel;
1216
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001217 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001218}
1219
1220template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1221 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001222 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001223 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001224 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001225
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001226 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001227 P->r_addend = Rel.getAddend();
1228 P->r_offset = Rel.getOffset();
Simon Atanasyan725dc142016-11-16 21:01:02 +00001229 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001230 // Dynamic relocation against MIPS GOT section make deal TLS entries
1231 // allocated in the end of the GOT. We need to adjust the offset to take
1232 // in account 'local' and 'global' GOT entries.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +00001233 P->r_offset += In<ELFT>::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001234 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001235 }
1236
1237 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001238 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001239 std::stable_sort((Elf_Rela *)BufBegin,
1240 (Elf_Rela *)BufBegin + Relocs.size(),
1241 compRelocations<ELFT, Elf_Rela>);
1242 else
1243 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1244 compRelocations<ELFT, Elf_Rel>);
1245 }
1246}
1247
1248template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1249 return this->Entsize * Relocs.size();
1250}
1251
Rui Ueyama945055a2017-02-27 03:07:41 +00001252template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Eugene Leviant9230db92016-11-17 09:16:34 +00001253 this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex
1254 : In<ELFT>::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001255
1256 // Set required output section properties.
1257 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001258}
1259
Eugene Leviant9230db92016-11-17 09:16:34 +00001260template <class ELFT>
George Rimar49648002017-03-15 09:32:36 +00001261SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001262 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001263 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001264 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001265 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
Eugene Leviant9230db92016-11-17 09:16:34 +00001266 StrTabSec(StrTabSec) {
1267 this->Entsize = sizeof(Elf_Sym);
1268}
1269
1270// Orders symbols according to their positions in the GOT,
1271// in compliance with MIPS ABI rules.
1272// See "Global Offset Table" in Chapter 5 in the following document
1273// for detailed description:
1274// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001275static bool sortMipsSymbols(const SymbolTableEntry &L,
1276 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001277 // Sort entries related to non-local preemptible symbols by GOT indexes.
1278 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001279 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1280 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001281 if (LIsInLocalGot || RIsInLocalGot)
1282 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001283 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001284}
1285
Rui Ueyamabb07d102017-02-27 03:31:19 +00001286// Finalize a symbol table. The ELF spec requires that all local
1287// symbols precede global symbols, so we sort symbol entries in this
1288// function. (For .dynsym, we don't do that because symbols for
1289// dynamic linking are inherently all globals.)
Rui Ueyama945055a2017-02-27 03:07:41 +00001290template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001291 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001292
Rui Ueyama6e967342017-02-28 03:29:12 +00001293 // If it is a .dynsym, there should be no local symbols, but we need
1294 // to do a few things for the dynamic linker.
1295 if (this->Type == SHT_DYNSYM) {
1296 // Section's Info field has the index of the first non-local symbol.
1297 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001298 this->OutSec->Info = 1;
1299
1300 if (In<ELFT>::GnuHashTab) {
1301 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1302 In<ELFT>::GnuHashTab->addSymbols(Symbols);
1303 } else if (Config->EMachine == EM_MIPS) {
1304 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1305 }
1306
1307 size_t I = 0;
1308 for (const SymbolTableEntry &S : Symbols)
1309 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001310 return;
Peter Smith55865432017-02-20 11:12:33 +00001311 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001312}
Peter Smith55865432017-02-20 11:12:33 +00001313
Peter Smith1ec42d92017-03-08 14:06:24 +00001314template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() {
1315 if (this->Type == SHT_DYNSYM)
1316 return;
1317 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001318 auto It = std::stable_partition(
1319 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1320 return S.Symbol->isLocal() ||
1321 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1322 });
1323 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001324 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001325}
1326
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001327template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1328 // Adding a local symbol to a .dynsym is a bug.
1329 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001330
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001331 bool HashIt = B->isLocal();
1332 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001333}
1334
1335template <class ELFT>
1336size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001337 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1338 if (E.Symbol == Body)
1339 return true;
1340 // This is used for -r, so we have to handle multiple section
1341 // symbols being combined.
1342 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001343 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1344 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001345 return false;
1346 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001347 if (I == Symbols.end())
1348 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001349 return I - Symbols.begin() + 1;
1350}
1351
Rui Ueyama1f032532017-02-28 01:56:36 +00001352// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001353template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001354 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001355 Buf += sizeof(Elf_Sym);
1356
Eugene Leviant9230db92016-11-17 09:16:34 +00001357 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001358
Rui Ueyama1f032532017-02-28 01:56:36 +00001359 for (SymbolTableEntry &Ent : Symbols) {
1360 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001361
Rui Ueyama1b003182017-02-28 19:22:09 +00001362 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001363 if (Body->isLocal()) {
1364 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1365 } else {
1366 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1367 ESym->setVisibility(Body->symbol()->Visibility);
1368 }
1369
1370 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001371 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001372
Rui Ueyama1b003182017-02-28 19:22:09 +00001373 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001374 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001375 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001376 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001377 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001378 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001379 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001380
1381 // st_value is usually an address of a symbol, but that has a
1382 // special meaining for uninstantiated common symbols (this can
1383 // occur if -r is given).
1384 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001385 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001386 else
George Rimarf64618a2017-03-17 11:56:54 +00001387 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001388
Rui Ueyama1f032532017-02-28 01:56:36 +00001389 ++ESym;
1390 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001391
Rui Ueyama1f032532017-02-28 01:56:36 +00001392 // On MIPS we need to mark symbol which has a PLT entry and requires
1393 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1394 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1395 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1396 if (Config->EMachine == EM_MIPS) {
1397 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1398
1399 for (SymbolTableEntry &Ent : Symbols) {
1400 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001401 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001402 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001403
1404 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001405 if (auto *D = dyn_cast<DefinedRegular>(Body))
1406 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001407 ESym->st_other |= STO_MIPS_PIC;
1408 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001409 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001410 }
1411}
1412
Rui Ueyamae4120632017-02-28 22:05:13 +00001413// .hash and .gnu.hash sections contain on-disk hash tables that map
1414// symbol names to their dynamic symbol table indices. Their purpose
1415// is to help the dynamic linker resolve symbols quickly. If ELF files
1416// don't have them, the dynamic linker has to do linear search on all
1417// dynamic symbols, which makes programs slower. Therefore, a .hash
1418// section is added to a DSO by default. A .gnu.hash is added if you
1419// give the -hash-style=gnu or -hash-style=both option.
1420//
1421// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1422// Each ELF file has a list of DSOs that the ELF file depends on and a
1423// list of dynamic symbols that need to be resolved from any of the
1424// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1425// where m is the number of DSOs and n is the number of dynamic
1426// symbols. For modern large programs, both m and n are large. So
1427// making each step faster by using hash tables substiantially
1428// improves time to load programs.
1429//
1430// (Note that this is not the only way to design the shared library.
1431// For instance, the Windows DLL takes a different approach. On
1432// Windows, each dynamic symbol has a name of DLL from which the symbol
1433// has to be resolved. That makes the cost of symbol resolution O(n).
1434// This disables some hacky techniques you can use on Unix such as
1435// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1436//
1437// Due to historical reasons, we have two different hash tables, .hash
1438// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1439// and better version of .hash. .hash is just an on-disk hash table, but
1440// .gnu.hash has a bloom filter in addition to a hash table to skip
1441// DSOs very quickly. If you are sure that your dynamic linker knows
1442// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1443// safe bet is to specify -hash-style=both for backward compatibilty.
Eugene Leviant9230db92016-11-17 09:16:34 +00001444template <class ELFT>
Eugene Leviantbe809a72016-11-18 06:44:18 +00001445GnuHashTableSection<ELFT>::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001446 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1447}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001448
Rui Ueyama945055a2017-02-27 03:07:41 +00001449template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001450 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001451
1452 // Computes bloom filter size in word size. We want to allocate 8
1453 // bits for each symbol. It must be a power of two.
1454 if (Symbols.empty())
1455 MaskWords = 1;
1456 else
George Rimar5f73bc92017-03-29 15:23:28 +00001457 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001458
George Rimar5f73bc92017-03-29 15:23:28 +00001459 Size = 16; // Header
1460 Size += Config->Wordsize * MaskWords; // Bloom filter
1461 Size += NBuckets * 4; // Hash buckets
1462 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001463}
1464
George Rimar5f73bc92017-03-29 15:23:28 +00001465template <class ELFT>
1466void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001467 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001468 write32(Buf, NBuckets, Config->Endianness);
1469 write32(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size(),
1470 Config->Endianness);
1471 write32(Buf + 8, MaskWords, Config->Endianness);
1472 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001473 Buf += 16;
1474
Rui Ueyama7986b452017-03-01 18:09:09 +00001475 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001476 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001477 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001478 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001479}
1480
Rui Ueyama7986b452017-03-01 18:09:09 +00001481// This function writes a 2-bit bloom filter. This bloom filter alone
1482// usually filters out 80% or more of all symbol lookups [1].
1483// The dynamic linker uses the hash table only when a symbol is not
1484// filtered out by a bloom filter.
1485//
1486// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1487// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
Eugene Leviantbe809a72016-11-18 06:44:18 +00001488template <class ELFT>
Rui Ueyamae13373b2017-03-01 02:51:42 +00001489void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001490 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001491 for (const Entry &Sym : Symbols) {
1492 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001493 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1494 Val |= uint64_t(1) << (Sym.Hash % C);
1495 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1496 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001497 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001498}
1499
1500template <class ELFT>
1501void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001502 // Group symbols by hash value.
1503 std::vector<std::vector<Entry>> Syms(NBuckets);
1504 for (const Entry &Ent : Symbols)
1505 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001506
Rui Ueyamae13373b2017-03-01 02:51:42 +00001507 // Write hash buckets. Hash buckets contain indices in the following
1508 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001509 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001510 for (size_t I = 0; I < NBuckets; ++I)
1511 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001512 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001513
1514 // Write a hash value table. It represents a sequence of chains that
1515 // share the same hash modulo value. The last element of each chain
1516 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001517 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001518 size_t I = 0;
1519 for (std::vector<Entry> &Vec : Syms) {
1520 if (Vec.empty())
1521 continue;
1522 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001523 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1524 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001525 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001526}
1527
1528static uint32_t hashGnu(StringRef Name) {
1529 uint32_t H = 5381;
1530 for (uint8_t C : Name)
1531 H = (H << 5) + H + C;
1532 return H;
1533}
1534
Rui Ueyamae13373b2017-03-01 02:51:42 +00001535// Returns a number of hash buckets to accomodate given number of elements.
1536// We want to choose a moderate number that is not too small (which
1537// causes too many hash collisions) and not too large (which wastes
1538// disk space.)
1539//
1540// We return a prime number because it (is believed to) achieve good
1541// hash distribution.
1542static size_t getBucketSize(size_t NumSymbols) {
1543 // List of largest prime numbers that are not greater than 2^n + 1.
1544 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1545 251, 127, 61, 31, 13, 7, 3, 1})
1546 if (N <= NumSymbols)
1547 return N;
1548 return 0;
1549}
1550
Eugene Leviantbe809a72016-11-18 06:44:18 +00001551// Add symbols to this symbol hash table. Note that this function
1552// destructively sort a given vector -- which is needed because
1553// GNU-style hash table places some sorting requirements.
1554template <class ELFT>
1555void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001556 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1557 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001558 std::vector<SymbolTableEntry>::iterator Mid =
1559 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1560 return S.Symbol->isUndefined();
1561 });
1562 if (Mid == V.end())
1563 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001564
1565 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1566 SymbolBody *B = Ent.Symbol;
1567 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001568 }
1569
Rui Ueyamae13373b2017-03-01 02:51:42 +00001570 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001571 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001572 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001573 return L.Hash % NBuckets < R.Hash % NBuckets;
1574 });
1575
1576 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001577 for (const Entry &Ent : Symbols)
1578 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001579}
1580
Eugene Leviantb96e8092016-11-18 09:06:47 +00001581template <class ELFT>
1582HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001583 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1584 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001585}
1586
Rui Ueyama945055a2017-02-27 03:07:41 +00001587template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00001588 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001589
1590 unsigned NumEntries = 2; // nbucket and nchain.
1591 NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
1592
1593 // Create as many buckets as there are symbols.
1594 // FIXME: This is simplistic. We can try to optimize it, but implementing
1595 // support for SHT_GNU_HASH is probably even more profitable.
1596 NumEntries += In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001597 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001598}
1599
1600template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001601 // A 32-bit integer type in the target endianness.
1602 typedef typename ELFT::Word Elf_Word;
1603
Eugene Leviantb96e8092016-11-18 09:06:47 +00001604 unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001605
Eugene Leviantb96e8092016-11-18 09:06:47 +00001606 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1607 *P++ = NumSymbols; // nbucket
1608 *P++ = NumSymbols; // nchain
1609
1610 Elf_Word *Buckets = P;
1611 Elf_Word *Chains = P + NumSymbols;
1612
1613 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
1614 SymbolBody *Body = S.Symbol;
1615 StringRef Name = Body->getName();
1616 unsigned I = Body->DynsymIndex;
1617 uint32_t Hash = hashSysV(Name) % NumSymbols;
1618 Chains[I] = Buckets[Hash];
1619 Buckets[Hash] = I;
1620 }
1621}
1622
George Rimardfc020e2017-03-17 11:01:57 +00001623PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001624 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001625 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001626
George Rimardfc020e2017-03-17 11:01:57 +00001627void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001628 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1629 // linker to resolve dynsyms at runtime. Write such code.
1630 if (HeaderSize != 0)
1631 Target->writePltHeader(Buf);
1632 size_t Off = HeaderSize;
1633 // The IPlt is immediately after the Plt, account for this in RelOff
1634 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001635
1636 for (auto &I : Entries) {
1637 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001638 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001639 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001640 uint64_t Plt = this->getVA() + Off;
1641 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1642 Off += Target->PltEntrySize;
1643 }
1644}
1645
George Rimardfc020e2017-03-17 11:01:57 +00001646template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001647 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001648 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1649 if (HeaderSize == 0) {
1650 PltRelocSection = In<ELFT>::RelaIplt;
1651 Sym.IsInIplt = true;
1652 }
1653 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001654 Entries.push_back(std::make_pair(&Sym, RelOff));
1655}
1656
George Rimardfc020e2017-03-17 11:01:57 +00001657size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001658 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001659}
1660
Peter Smith96943762017-01-25 10:31:16 +00001661// Some architectures such as additional symbols in the PLT section. For
1662// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001663void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001664 // The PLT may have symbols defined for the Header, the IPLT has no header
1665 if (HeaderSize != 0)
1666 Target->addPltHeaderSymbols(this);
1667 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001668 for (size_t I = 0; I < Entries.size(); ++I) {
1669 Target->addPltSymbols(this, Off);
1670 Off += Target->PltEntrySize;
1671 }
1672}
1673
George Rimardfc020e2017-03-17 11:01:57 +00001674unsigned PltSection::getPltRelocOff() const {
1675 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001676}
1677
George Rimar35e846e2017-03-21 08:19:34 +00001678GdbIndexSection::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001679 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001680 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001681
George Rimarec02b8d2016-12-15 12:07:53 +00001682// Iterative hash function for symbol's name is described in .gdb_index format
1683// specification. Note that we use one for version 5 to 7 here, it is different
1684// for version 4.
1685static uint32_t hash(StringRef Str) {
1686 uint32_t R = 0;
1687 for (uint8_t C : Str)
1688 R = R * 67 + tolower(C) - 113;
1689 return R;
1690}
1691
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001692static std::vector<std::pair<uint64_t, uint64_t>>
1693readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1694 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1695 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1696 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1697 return Ret;
1698}
1699
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001700static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr,
1701 uint64_t Offset) {
1702 for (InputSectionBase *S : Arr)
1703 if (S && S != &InputSection::Discarded)
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001704 if (Offset >= S->getOffsetInFile() &&
1705 Offset < S->getOffsetInFile() + S->getSize())
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001706 return S;
1707 return nullptr;
1708}
1709
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001710static std::vector<AddressEntry>
1711readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1712 std::vector<AddressEntry> Ret;
1713
1714 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1715 DWARFAddressRangesVector Ranges;
1716 CU->collectAddressRanges(Ranges);
1717
George Rimar35e846e2017-03-21 08:19:34 +00001718 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001719 for (std::pair<uint64_t, uint64_t> &R : Ranges)
George Rimar8fe7aea2017-03-17 13:43:24 +00001720 if (InputSectionBase *S = findSection(Sections, R.first))
Rafael Espindola35ae65e2017-03-08 15:57:17 +00001721 Ret.push_back({S, R.first - S->getOffsetInFile(),
1722 R.second - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001723 ++CurrentCU;
1724 }
1725 return Ret;
1726}
1727
1728static std::vector<std::pair<StringRef, uint8_t>>
1729readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1730 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1731 Dwarf.getGnuPubTypesSection()};
1732
1733 std::vector<std::pair<StringRef, uint8_t>> Ret;
1734 for (StringRef D : Data) {
1735 DWARFDebugPubTable PubTable(D, IsLE, true);
1736 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1737 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1738 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1739 }
1740 return Ret;
1741}
1742
1743class ObjInfoTy : public llvm::LoadedObjectInfo {
1744 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1745 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1746 if (S.getFlags() & ELF::SHF_ALLOC)
1747 return S.getOffset();
1748 return 0;
1749 }
1750
1751 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1752};
1753
George Rimar35e846e2017-03-21 08:19:34 +00001754void GdbIndexSection::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001755 Expected<std::unique_ptr<object::ObjectFile>> Obj =
George Rimar05423482017-03-20 10:47:00 +00001756 object::ObjectFile::createObjectFile(Sec->File->MB);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001757 if (!Obj) {
George Rimar05423482017-03-20 10:47:00 +00001758 error(toString(Sec->File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001759 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001760 }
1761
1762 ObjInfoTy ObjInfo;
1763 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001764
1765 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001766 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1767 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001768
George Rimar35e846e2017-03-21 08:19:34 +00001769 for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001770 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001771
1772 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
George Rimar35e846e2017-03-21 08:19:34 +00001773 readPubNamesAndTypes(Dwarf, Config->IsLE);
George Rimarec02b8d2016-12-15 12:07:53 +00001774
1775 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1776 uint32_t Hash = hash(Pair.first);
1777 size_t Offset = StringPool.add(Pair.first);
1778
1779 bool IsNew;
1780 GdbSymbol *Sym;
1781 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1782 if (IsNew) {
1783 Sym->CuVectorIndex = CuVectors.size();
1784 CuVectors.push_back({{CuId, Pair.second}});
1785 continue;
1786 }
1787
Rui Ueyamaaab18c02017-03-01 22:24:46 +00001788 CuVectors[Sym->CuVectorIndex].push_back({CuId, Pair.second});
George Rimarec02b8d2016-12-15 12:07:53 +00001789 }
Eugene Levianta113a412016-11-21 09:24:43 +00001790}
1791
George Rimar35e846e2017-03-21 08:19:34 +00001792void GdbIndexSection::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001793 if (Finalized)
1794 return;
1795 Finalized = true;
1796
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001797 for (InputSectionBase *S : InputSections)
1798 if (InputSection *IS = dyn_cast<InputSection>(S))
1799 if (IS->OutSec && IS->Name == ".debug_info")
1800 readDwarf(IS);
1801
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001802 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001803
1804 // GdbIndex header consist from version fields
1805 // and 5 more fields with different kinds of offsets.
1806 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001807 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001808
1809 ConstantPoolOffset =
1810 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1811
1812 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1813 CuVectorsOffset.push_back(CuVectorsSize);
1814 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1815 }
1816 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1817
1818 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001819}
1820
George Rimar35e846e2017-03-21 08:19:34 +00001821size_t GdbIndexSection::getSize() const {
1822 const_cast<GdbIndexSection *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001823 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001824}
1825
George Rimar35e846e2017-03-21 08:19:34 +00001826void GdbIndexSection::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001827 write32le(Buf, 7); // Write version.
1828 write32le(Buf + 4, CuListOffset); // CU list offset.
1829 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1830 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1831 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1832 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001833 Buf += 24;
1834
1835 // Write the CU list.
George Rimarf6abfd72017-03-20 10:40:40 +00001836 for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
Eugene Levianta113a412016-11-21 09:24:43 +00001837 write64le(Buf, CU.first);
1838 write64le(Buf + 8, CU.second);
1839 Buf += 16;
1840 }
George Rimar8b547392016-12-15 09:08:13 +00001841
1842 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001843 for (AddressEntry &E : AddressArea) {
George Rimarf6abfd72017-03-20 10:40:40 +00001844 uint64_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001845 write64le(Buf, BaseAddr + E.LowAddress);
1846 write64le(Buf + 8, BaseAddr + E.HighAddress);
1847 write32le(Buf + 16, E.CuIndex);
1848 Buf += 20;
1849 }
George Rimarec02b8d2016-12-15 12:07:53 +00001850
1851 // Write the symbol table.
1852 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1853 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1854 if (Sym) {
1855 size_t NameOffset =
1856 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1857 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1858 write32le(Buf, NameOffset);
1859 write32le(Buf + 4, CuVectorOffset);
1860 }
1861 Buf += 8;
1862 }
1863
1864 // Write the CU vectors into the constant pool.
1865 for (std::vector<std::pair<uint32_t, uint8_t>> &CuVec : CuVectors) {
1866 write32le(Buf, CuVec.size());
1867 Buf += 4;
1868 for (std::pair<uint32_t, uint8_t> &P : CuVec) {
1869 uint32_t Index = P.first;
1870 uint8_t Flags = P.second;
1871 Index |= Flags << 24;
1872 write32le(Buf, Index);
1873 Buf += 4;
1874 }
1875 }
1876
1877 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001878}
1879
George Rimar35e846e2017-03-21 08:19:34 +00001880bool GdbIndexSection::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001881 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001882}
1883
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001884template <class ELFT>
1885EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001886 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001887
1888// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1889// Each entry of the search table consists of two values,
1890// the starting PC from where FDEs covers, and the FDE's address.
1891// It is sorted by PC.
1892template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1893 const endianness E = ELFT::TargetEndianness;
1894
1895 // Sort the FDE list by their PC and uniqueify. Usually there is only
1896 // one FDE for a PC (i.e. function), but if ICF merges two functions
1897 // into one, there can be more than one FDEs pointing to the address.
1898 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1899 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1900 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1901 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1902
1903 Buf[0] = 1;
1904 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1905 Buf[2] = DW_EH_PE_udata4;
1906 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001907 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001908 write32<E>(Buf + 8, Fdes.size());
1909 Buf += 12;
1910
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001911 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001912 for (FdeData &Fde : Fdes) {
1913 write32<E>(Buf, Fde.Pc - VA);
1914 write32<E>(Buf + 4, Fde.FdeVA - VA);
1915 Buf += 8;
1916 }
1917}
1918
1919template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1920 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001921 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001922}
1923
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001924template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001925void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1926 Fdes.push_back({Pc, FdeVA});
1927}
1928
George Rimar11992c862016-11-25 08:05:41 +00001929template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001930 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001931}
1932
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001933template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001934VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001935 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1936 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001937
1938static StringRef getFileDefName() {
1939 if (!Config->SoName.empty())
1940 return Config->SoName;
1941 return Config->OutputFile;
1942}
1943
Rui Ueyama945055a2017-02-27 03:07:41 +00001944template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001945 FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName());
1946 for (VersionDefinition &V : Config->VersionDefinitions)
1947 V.NameOff = In<ELFT>::DynStrTab->addString(V.Name);
1948
Rui Ueyamac3726f82017-02-28 04:41:20 +00001949 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001950
1951 // sh_info should be set to the number of definitions. This fact is missed in
1952 // documentation, but confirmed by binutils community:
1953 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001954 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001955}
1956
1957template <class ELFT>
1958void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1959 StringRef Name, size_t NameOff) {
1960 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1961 Verdef->vd_version = 1;
1962 Verdef->vd_cnt = 1;
1963 Verdef->vd_aux = sizeof(Elf_Verdef);
1964 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1965 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1966 Verdef->vd_ndx = Index;
1967 Verdef->vd_hash = hashSysV(Name);
1968
1969 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1970 Verdaux->vda_name = NameOff;
1971 Verdaux->vda_next = 0;
1972}
1973
1974template <class ELFT>
1975void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1976 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1977
1978 for (VersionDefinition &V : Config->VersionDefinitions) {
1979 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1980 writeOne(Buf, V.Id, V.Name, V.NameOff);
1981 }
1982
1983 // Need to terminate the last version definition.
1984 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1985 Verdef->vd_next = 0;
1986}
1987
1988template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1989 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1990}
1991
1992template <class ELFT>
1993VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001994 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00001995 ".gnu.version") {
1996 this->Entsize = sizeof(Elf_Versym);
1997}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001998
Rui Ueyama945055a2017-02-27 03:07:41 +00001999template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002000 // At the moment of june 2016 GNU docs does not mention that sh_link field
2001 // should be set, but Sun docs do. Also readelf relies on this field.
Rui Ueyamac3726f82017-02-28 04:41:20 +00002002 this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002003}
2004
2005template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
2006 return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1);
2007}
2008
2009template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2010 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
2011 for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) {
2012 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2013 ++OutVersym;
2014 }
2015}
2016
George Rimar11992c862016-11-25 08:05:41 +00002017template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2018 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2019}
2020
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002021template <class ELFT>
2022VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002023 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2024 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002025 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2026 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2027 // First identifiers are reserved by verdef section if it exist.
2028 NextIndex = getVerDefNum() + 1;
2029}
2030
2031template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002032void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2033 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2034 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002035 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2036 return;
2037 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002038
2039 auto *File = cast<SharedFile<ELFT>>(SS->File);
2040
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002041 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2042 // to create one by adding it to our needed list and creating a dynstr entry
2043 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002044 if (File->VerdefMap.empty())
Rafael Espindola3460cdd2017-04-24 21:44:20 +00002045 Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002046 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002047 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2048 // prepare to create one by allocating a version identifier and creating a
2049 // dynstr entry for the version name.
2050 if (NV.Index == 0) {
Rui Ueyama4076fa12017-02-26 23:35:34 +00002051 NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() +
2052 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002053 NV.Index = NextIndex++;
2054 }
2055 SS->symbol()->VersionId = NV.Index;
2056}
2057
2058template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2059 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2060 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2061 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2062
2063 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2064 // Create an Elf_Verneed for this DSO.
2065 Verneed->vn_version = 1;
2066 Verneed->vn_cnt = P.first->VerdefMap.size();
2067 Verneed->vn_file = P.second;
2068 Verneed->vn_aux =
2069 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2070 Verneed->vn_next = sizeof(Elf_Verneed);
2071 ++Verneed;
2072
2073 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2074 // VerdefMap, which will only contain references to needed version
2075 // definitions. Each Elf_Vernaux is based on the information contained in
2076 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2077 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2078 // data structures within a single input file.
2079 for (auto &NV : P.first->VerdefMap) {
2080 Vernaux->vna_hash = NV.first->vd_hash;
2081 Vernaux->vna_flags = 0;
2082 Vernaux->vna_other = NV.second.Index;
2083 Vernaux->vna_name = NV.second.StrTab;
2084 Vernaux->vna_next = sizeof(Elf_Vernaux);
2085 ++Vernaux;
2086 }
2087
2088 Vernaux[-1].vna_next = 0;
2089 }
2090 Verneed[-1].vn_next = 0;
2091}
2092
Rui Ueyama945055a2017-02-27 03:07:41 +00002093template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rui Ueyamac3726f82017-02-28 04:41:20 +00002094 this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex;
2095 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002096}
2097
2098template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2099 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2100 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2101 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2102 return Size;
2103}
2104
George Rimar11992c862016-11-25 08:05:41 +00002105template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2106 return getNeedNum() == 0;
2107}
2108
Rafael Espindola6119b862017-03-06 20:23:56 +00002109MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002110 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002111 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002112 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002113
Rafael Espindola6119b862017-03-06 20:23:56 +00002114void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002115 assert(!Finalized);
2116 MS->MergeSec = this;
2117 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002118}
2119
Rafael Espindola6119b862017-03-06 20:23:56 +00002120void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002121
Rafael Espindola6119b862017-03-06 20:23:56 +00002122bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002123 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2124}
2125
Rafael Espindola6119b862017-03-06 20:23:56 +00002126void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002127 // Add all string pieces to the string table builder to create section
2128 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002129 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002130 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2131 if (Sec->Pieces[I].Live)
2132 Builder.add(Sec->getData(I));
2133
2134 // Fix the string table content. After this, the contents will never change.
2135 Builder.finalize();
2136
2137 // finalize() fixed tail-optimized strings, so we can now get
2138 // offsets of strings. Get an offset for each string and save it
2139 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002140 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002141 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2142 if (Sec->Pieces[I].Live)
2143 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2144}
2145
Rafael Espindola6119b862017-03-06 20:23:56 +00002146void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002147 // Add all string pieces to the string table builder to create section
2148 // contents. Because we are not tail-optimizing, offsets of strings are
2149 // fixed when they are added to the builder (string table builder contains
2150 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002151 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002152 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2153 if (Sec->Pieces[I].Live)
2154 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2155
2156 Builder.finalizeInOrder();
2157}
2158
Rafael Espindola6119b862017-03-06 20:23:56 +00002159void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002160 if (Finalized)
2161 return;
2162 Finalized = true;
2163 if (shouldTailMerge())
2164 finalizeTailMerge();
2165 else
2166 finalizeNoTailMerge();
2167}
2168
Rafael Espindola6119b862017-03-06 20:23:56 +00002169size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002170 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002171 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002172 return Builder.getSize();
2173}
2174
George Rimar42886c42017-03-15 12:02:31 +00002175MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002176 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2177 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002178
George Rimar42886c42017-03-15 12:02:31 +00002179void MipsRldMapSection::writeTo(uint8_t *Buf) {
Eugene Leviant17b7a572016-11-22 17:49:14 +00002180 // Apply filler from linker script.
James Henderson9d9a6632017-04-07 10:36:42 +00002181 Optional<uint32_t> Fill = Script->getFiller(this->Name);
2182 if (!Fill || *Fill == 0)
2183 return;
2184
2185 uint64_t Filler = *Fill;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002186 Filler = (Filler << 32) | Filler;
2187 memcpy(Buf, &Filler, getSize());
2188}
2189
George Rimar90a528b2017-03-21 09:01:39 +00002190ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002191 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002192 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002193
2194// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2195// This section will have been sorted last in the .ARM.exidx table.
2196// This table entry will have the form:
2197// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
George Rimar90a528b2017-03-21 09:01:39 +00002198void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smith719eb8e2016-11-24 11:43:55 +00002199 // Get the InputSection before us, we are by definition last
Rafael Espindola24e6f362017-02-24 15:07:30 +00002200 auto RI = cast<OutputSection>(this->OutSec)->Sections.rbegin();
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002201 InputSection *LE = *(++RI);
George Rimar9353e2d2017-03-21 08:29:48 +00002202 InputSection *LC = cast<InputSection>(LE->getLinkOrderDep());
Rafael Espindolae1294092017-03-08 16:03:41 +00002203 uint64_t S = LC->OutSec->Addr + LC->getOffset(LC->getSize());
Peter Smith719eb8e2016-11-24 11:43:55 +00002204 uint64_t P = this->getVA();
2205 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2206 write32le(Buf + 4, 0x1);
2207}
2208
George Rimar7b827042017-03-16 10:40:50 +00002209ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002210 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002211 Config->Wordsize, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002212 this->OutSec = OS;
2213 this->OutSecOff = Off;
2214}
2215
George Rimar7b827042017-03-16 10:40:50 +00002216void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002217 uint64_t Off = alignTo(Size, T->alignment);
2218 T->Offset = Off;
2219 Thunks.push_back(T);
2220 T->addSymbols(*this);
2221 Size = Off + T->size();
2222}
2223
George Rimar7b827042017-03-16 10:40:50 +00002224void ThunkSection::writeTo(uint8_t *Buf) {
2225 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002226 T->writeTo(Buf + T->Offset, *this);
2227}
2228
George Rimar7b827042017-03-16 10:40:50 +00002229InputSection *ThunkSection::getTargetInputSection() const {
2230 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002231 return T->getTargetInputSection();
2232}
2233
George Rimar9782ca52017-03-15 15:29:29 +00002234InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002235BssSection *InX::Bss;
2236BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002237BuildIdSection *InX::BuildId;
George Rimar9782ca52017-03-15 15:29:29 +00002238InputSection *InX::Common;
2239StringTableSection *InX::DynStrTab;
2240InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002241GdbIndexSection *InX::GdbIndex;
George Rimar9782ca52017-03-15 15:29:29 +00002242GotPltSection *InX::GotPlt;
2243IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002244MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002245MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002246PltSection *InX::Plt;
2247PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002248StringTableSection *InX::ShStrTab;
2249StringTableSection *InX::StrTab;
2250
George Rimara9189572017-03-17 16:50:07 +00002251template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2252template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2253template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2254template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2255
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002256template InputSection *elf::createCommonSection<ELF32LE>();
2257template InputSection *elf::createCommonSection<ELF32BE>();
2258template InputSection *elf::createCommonSection<ELF64LE>();
2259template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002260
Rafael Espindola6119b862017-03-06 20:23:56 +00002261template MergeInputSection *elf::createCommentSection<ELF32LE>();
2262template MergeInputSection *elf::createCommentSection<ELF32BE>();
2263template MergeInputSection *elf::createCommentSection<ELF64LE>();
2264template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002265
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002266template SymbolBody *elf::addSyntheticLocal<ELF32LE>(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<ELF32BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002270 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002271 InputSectionBase *);
2272template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002273 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002274 InputSectionBase *);
2275template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t,
Rui Ueyama65316d72017-02-23 03:15:57 +00002276 uint64_t, uint64_t,
Rafael Espindolab4c9b812017-02-23 02:28:28 +00002277 InputSectionBase *);
Peter Smith96943762017-01-25 10:31:16 +00002278
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002279template class elf::MipsAbiFlagsSection<ELF32LE>;
2280template class elf::MipsAbiFlagsSection<ELF32BE>;
2281template class elf::MipsAbiFlagsSection<ELF64LE>;
2282template class elf::MipsAbiFlagsSection<ELF64BE>;
2283
Simon Atanasyance02cf02016-11-09 21:36:56 +00002284template class elf::MipsOptionsSection<ELF32LE>;
2285template class elf::MipsOptionsSection<ELF32BE>;
2286template class elf::MipsOptionsSection<ELF64LE>;
2287template class elf::MipsOptionsSection<ELF64BE>;
2288
2289template class elf::MipsReginfoSection<ELF32LE>;
2290template class elf::MipsReginfoSection<ELF32BE>;
2291template class elf::MipsReginfoSection<ELF64LE>;
2292template class elf::MipsReginfoSection<ELF64BE>;
2293
Eugene Leviantad4439e2016-11-11 11:33:32 +00002294template class elf::GotSection<ELF32LE>;
2295template class elf::GotSection<ELF32BE>;
2296template class elf::GotSection<ELF64LE>;
2297template class elf::GotSection<ELF64BE>;
2298
Eugene Leviant6380ce22016-11-15 12:26:55 +00002299template class elf::DynamicSection<ELF32LE>;
2300template class elf::DynamicSection<ELF32BE>;
2301template class elf::DynamicSection<ELF64LE>;
2302template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002303
2304template class elf::RelocationSection<ELF32LE>;
2305template class elf::RelocationSection<ELF32BE>;
2306template class elf::RelocationSection<ELF64LE>;
2307template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002308
2309template class elf::SymbolTableSection<ELF32LE>;
2310template class elf::SymbolTableSection<ELF32BE>;
2311template class elf::SymbolTableSection<ELF64LE>;
2312template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002313
2314template class elf::GnuHashTableSection<ELF32LE>;
2315template class elf::GnuHashTableSection<ELF32BE>;
2316template class elf::GnuHashTableSection<ELF64LE>;
2317template class elf::GnuHashTableSection<ELF64BE>;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002318
2319template class elf::HashTableSection<ELF32LE>;
2320template class elf::HashTableSection<ELF32BE>;
2321template class elf::HashTableSection<ELF64LE>;
2322template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002323
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002324template class elf::EhFrameHeader<ELF32LE>;
2325template class elf::EhFrameHeader<ELF32BE>;
2326template class elf::EhFrameHeader<ELF64LE>;
2327template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002328
2329template class elf::VersionTableSection<ELF32LE>;
2330template class elf::VersionTableSection<ELF32BE>;
2331template class elf::VersionTableSection<ELF64LE>;
2332template class elf::VersionTableSection<ELF64BE>;
2333
2334template class elf::VersionNeedSection<ELF32LE>;
2335template class elf::VersionNeedSection<ELF32BE>;
2336template class elf::VersionNeedSection<ELF64LE>;
2337template class elf::VersionNeedSection<ELF64BE>;
2338
2339template class elf::VersionDefinitionSection<ELF32LE>;
2340template class elf::VersionDefinitionSection<ELF32BE>;
2341template class elf::VersionDefinitionSection<ELF64LE>;
2342template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002343
Rafael Espindola66b4e212017-02-23 22:06:28 +00002344template class elf::EhFrameSection<ELF32LE>;
2345template class elf::EhFrameSection<ELF32BE>;
2346template class elf::EhFrameSection<ELF64LE>;
2347template class elf::EhFrameSection<ELF64BE>;