blob: 797401008b139e10e91ceeccded41ef36dc07dd6 [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)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000189 Reginfo.ri_gp_value = InX::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)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000247 Reginfo.ri_gp_value = InX::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
Rui Ueyama65316d72017-02-23 03:15:57 +0000296SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
297 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000298 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
299 Value, Size, Section, nullptr);
George Rimar69b17c32017-05-16 10:04:42 +0000300 if (InX::SymTab)
301 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000302 return S;
303}
304
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000305static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000306 switch (Config->BuildId) {
307 case BuildIdKind::Fast:
308 return 8;
309 case BuildIdKind::Md5:
310 case BuildIdKind::Uuid:
311 return 16;
312 case BuildIdKind::Sha1:
313 return 20;
314 case BuildIdKind::Hexstring:
315 return Config->BuildIdVector.size();
316 default:
317 llvm_unreachable("unknown BuildIdKind");
318 }
319}
320
George Rimar6c2949d2017-03-20 16:40:21 +0000321BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000322 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000323 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000324
George Rimar6c2949d2017-03-20 16:40:21 +0000325void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000326 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000327 write32(Buf, 4, E); // Name size
328 write32(Buf + 4, HashSize, E); // Content size
329 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000330 memcpy(Buf + 12, "GNU", 4); // Name string
331 HashBuf = Buf + 16;
332}
333
Rui Ueyama35e00752016-11-10 00:12:28 +0000334// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000335static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
336 size_t ChunkSize) {
337 std::vector<ArrayRef<uint8_t>> Ret;
338 while (Arr.size() > ChunkSize) {
339 Ret.push_back(Arr.take_front(ChunkSize));
340 Arr = Arr.drop_front(ChunkSize);
341 }
342 if (!Arr.empty())
343 Ret.push_back(Arr);
344 return Ret;
345}
346
Rui Ueyama35e00752016-11-10 00:12:28 +0000347// Computes a hash value of Data using a given hash function.
348// In order to utilize multiple cores, we first split data into 1MB
349// chunks, compute a hash for each chunk, and then compute a hash value
350// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000351void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000352 llvm::ArrayRef<uint8_t> Data,
353 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000354 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000355 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000356
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000357 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000358 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000359 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
360 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000361
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000362 // Write to the final output buffer.
363 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000364}
365
George Rimar1ab9cf42017-03-17 10:14:53 +0000366BssSection::BssSection(StringRef Name)
367 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
368
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000369size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) {
George Rimar176d6062017-03-17 13:31:07 +0000370 if (OutSec)
371 OutSec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000372 this->Size = alignTo(this->Size, Alignment) + Size;
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000373 this->Alignment = std::max(this->Alignment, Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000374 return this->Size - Size;
375}
Peter Smithebfe9942017-02-09 10:27:57 +0000376
George Rimar6c2949d2017-03-20 16:40:21 +0000377void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000378 switch (Config->BuildId) {
379 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000380 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000381 write64le(Dest, xxHash64(toStringRef(Arr)));
382 });
383 break;
384 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000385 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000386 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000387 });
388 break;
389 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000390 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000391 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000392 });
393 break;
394 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000395 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000396 error("entropy source failure");
397 break;
398 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000399 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000400 break;
401 default:
402 llvm_unreachable("unknown BuildIdKind");
403 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000404}
405
Eugene Leviant41ca3272016-11-10 09:48:29 +0000406template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000407EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000408 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000409
410// Search for an existing CIE record or create a new one.
411// CIE records from input object files are uniquified by their contents
412// and where their relocations point to.
413template <class ELFT>
414template <class RelTy>
415CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
416 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000417 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000418 const endianness E = ELFT::TargetEndianness;
419 if (read32<E>(Piece.data().data() + 4) != 0)
420 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
421
422 SymbolBody *Personality = nullptr;
423 unsigned FirstRelI = Piece.FirstRelocation;
424 if (FirstRelI != (unsigned)-1)
425 Personality =
426 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
427
428 // Search for an existing CIE by CIE contents/relocation target pair.
429 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
430
431 // If not found, create a new one.
432 if (Cie->Piece == nullptr) {
433 Cie->Piece = &Piece;
434 Cies.push_back(Cie);
435 }
436 return Cie;
437}
438
439// There is one FDE per function. Returns true if a given FDE
440// points to a live function.
441template <class ELFT>
442template <class RelTy>
443bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
444 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000445 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000446 unsigned FirstRelI = Piece.FirstRelocation;
447 if (FirstRelI == (unsigned)-1)
448 return false;
449 const RelTy &Rel = Rels[FirstRelI];
450 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000451 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000452 if (!D || !D->Section)
453 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000454 auto *Target =
455 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000456 return Target && Target->Live;
457}
458
459// .eh_frame is a sequence of CIE or FDE records. In general, there
460// is one CIE record per input object file which is followed by
461// a list of FDEs. This function searches an existing CIE or create a new
462// one and associates FDEs to the CIE.
463template <class ELFT>
464template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000465void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000466 ArrayRef<RelTy> Rels) {
467 const endianness E = ELFT::TargetEndianness;
468
469 DenseMap<size_t, CieRecord *> OffsetToCie;
470 for (EhSectionPiece &Piece : Sec->Pieces) {
471 // The empty record is the end marker.
472 if (Piece.size() == 4)
473 return;
474
475 size_t Offset = Piece.InputOff;
476 uint32_t ID = read32<E>(Piece.data().data() + 4);
477 if (ID == 0) {
478 OffsetToCie[Offset] = addCie(Piece, Rels);
479 continue;
480 }
481
482 uint32_t CieOffset = Offset + 4 - ID;
483 CieRecord *Cie = OffsetToCie[CieOffset];
484 if (!Cie)
485 fatal(toString(Sec) + ": invalid CIE reference");
486
487 if (!isFdeLive(Piece, Rels))
488 continue;
489 Cie->FdePieces.push_back(&Piece);
490 NumFdes++;
491 }
492}
493
494template <class ELFT>
495void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000496 auto *Sec = cast<EhInputSection>(C);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000497 Sec->EHSec = this;
498 updateAlignment(Sec->Alignment);
499 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000500 for (auto *DS : Sec->DependentSections)
501 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000502
503 // .eh_frame is a sequence of CIE or FDE records. This function
504 // splits it into pieces so that we can call
505 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000506 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000507 if (Sec->Pieces.empty())
508 return;
509
510 if (Sec->NumRelocations) {
511 if (Sec->AreRelocsRela)
512 addSectionAux(Sec, Sec->template relas<ELFT>());
513 else
514 addSectionAux(Sec, Sec->template rels<ELFT>());
515 return;
516 }
517 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
518}
519
520template <class ELFT>
521static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
522 memcpy(Buf, D.data(), D.size());
523
524 // Fix the size field. -4 since size does not include the size field itself.
525 const endianness E = ELFT::TargetEndianness;
526 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
527}
528
Rui Ueyama945055a2017-02-27 03:07:41 +0000529template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000530 if (this->Size)
531 return; // Already finalized.
532
533 size_t Off = 0;
534 for (CieRecord *Cie : Cies) {
535 Cie->Piece->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000536 Off += alignTo(Cie->Piece->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000537
538 for (EhSectionPiece *Fde : Cie->FdePieces) {
539 Fde->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000540 Off += alignTo(Fde->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000541 }
542 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000543
544 // The LSB standard does not allow a .eh_frame section with zero
545 // Call Frame Information records. Therefore add a CIE record length
546 // 0 as a terminator if this .eh_frame section is empty.
547 if (Off == 0)
548 Off = 4;
549
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000550 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000551}
552
553template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
554 const endianness E = ELFT::TargetEndianness;
555 switch (Size) {
556 case DW_EH_PE_udata2:
557 return read16<E>(Buf);
558 case DW_EH_PE_udata4:
559 return read32<E>(Buf);
560 case DW_EH_PE_udata8:
561 return read64<E>(Buf);
562 case DW_EH_PE_absptr:
563 if (ELFT::Is64Bits)
564 return read64<E>(Buf);
565 return read32<E>(Buf);
566 }
567 fatal("unknown FDE size encoding");
568}
569
570// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
571// We need it to create .eh_frame_hdr section.
572template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000573uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
574 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000575 // The starting address to which this FDE applies is
576 // stored at FDE + 8 byte.
577 size_t Off = FdeOff + 8;
578 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
579 if ((Enc & 0x70) == DW_EH_PE_absptr)
580 return Addr;
581 if ((Enc & 0x70) == DW_EH_PE_pcrel)
582 return Addr + this->OutSec->Addr + Off;
583 fatal("unknown FDE size relative encoding");
584}
585
586template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
587 const endianness E = ELFT::TargetEndianness;
588 for (CieRecord *Cie : Cies) {
589 size_t CieOffset = Cie->Piece->OutputOff;
590 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
591
592 for (EhSectionPiece *Fde : Cie->FdePieces) {
593 size_t Off = Fde->OutputOff;
594 writeCieFde<ELFT>(Buf + Off, Fde->data());
595
596 // FDE's second word should have the offset to an associated CIE.
597 // Write it.
598 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
599 }
600 }
601
Rafael Espindola5c02b742017-03-06 21:17:18 +0000602 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000603 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000604
605 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
606 // to get a FDE from an address to which FDE is applied. So here
607 // we obtain two addresses and pass them to EhFrameHdr object.
608 if (In<ELFT>::EhFrameHdr) {
609 for (CieRecord *Cie : Cies) {
610 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
611 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000612 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
613 uint64_t FdeVA = this->OutSec->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000614 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
615 }
616 }
617 }
618}
619
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000620GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000621 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
622 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000623
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000624void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000625 Sym.GotIndex = NumEntries;
626 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000627}
628
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000629bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000630 if (Sym.GlobalDynIndex != -1U)
631 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000632 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000633 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000634 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000635 return true;
636}
637
638// Reserves TLS entries for a TLS module ID and a TLS block offset.
639// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000640bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000641 if (TlsIndexOff != uint32_t(-1))
642 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000643 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000644 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000645 return true;
646}
647
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000648uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000649 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000650}
651
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000652uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000653 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000654}
655
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000656void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000657
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000658bool GotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000659 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
660 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000661 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000662}
663
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000664void GotSection::writeTo(uint8_t *Buf) { relocateAlloc(Buf, Buf + Size); }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000665
George Rimar14534eb2017-03-20 16:44:28 +0000666MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000667 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
668 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000669
George Rimar14534eb2017-03-20 16:44:28 +0000670void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000671 // For "true" local symbols which can be referenced from the same module
672 // only compiler creates two instructions for address loading:
673 //
674 // lw $8, 0($gp) # R_MIPS_GOT16
675 // addi $8, $8, 0 # R_MIPS_LO16
676 //
677 // The first instruction loads high 16 bits of the symbol address while
678 // the second adds an offset. That allows to reduce number of required
679 // GOT entries because only one global offset table entry is necessary
680 // for every 64 KBytes of local data. So for local symbols we need to
681 // allocate number of GOT entries to hold all required "page" addresses.
682 //
683 // All global symbols (hidden and regular) considered by compiler uniformly.
684 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
685 // to load address of the symbol. So for each such symbol we need to
686 // allocate dedicated GOT entry to store its address.
687 //
688 // If a symbol is preemptible we need help of dynamic linker to get its
689 // final address. The corresponding GOT entries are allocated in the
690 // "global" part of GOT. Entries for non preemptible global symbol allocated
691 // in the "local" part of GOT.
692 //
693 // See "Global Offset Table" in Chapter 5:
694 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
695 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
696 // At this point we do not know final symbol value so to reduce number
697 // of allocated GOT entries do the following trick. Save all output
698 // sections referenced by GOT relocations. Then later in the `finalize`
699 // method calculate number of "pages" required to cover all saved output
700 // section and allocate appropriate number of GOT entries.
Rui Ueyama80474a22017-02-28 19:29:55 +0000701 auto *DefSym = cast<DefinedRegular>(&Sym);
Rafael Espindola5e434b32017-03-08 16:08:36 +0000702 PageIndexMap.insert({DefSym->Section->getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000703 return;
704 }
705 if (Sym.isTls()) {
706 // GOT entries created for MIPS TLS relocations behave like
707 // almost GOT entries from other ABIs. They go to the end
708 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000709 Sym.GotIndex = TlsEntries.size();
710 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000711 return;
712 }
George Rimar14534eb2017-03-20 16:44:28 +0000713 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000714 if (S.isInGot() && !A)
715 return;
716 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000717 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 return;
719 Items.emplace_back(&S, A);
720 if (!A)
721 S.GotIndex = NewIndex;
722 };
723 if (Sym.isPreemptible()) {
724 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000725 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 Sym.IsInGlobalMipsGot = true;
727 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000728 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 Sym.Is32BitMipsGot = true;
730 } else {
731 // Hold local GOT entries accessed via a 16-bit index separately.
732 // That allows to write them in the beginning of the GOT and keep
733 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000734 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000735 }
736}
737
George Rimar14534eb2017-03-20 16:44:28 +0000738bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000739 if (Sym.GlobalDynIndex != -1U)
740 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000741 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000742 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000743 TlsEntries.push_back(nullptr);
744 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000745 return true;
746}
747
748// Reserves TLS entries for a TLS module ID and a TLS block offset.
749// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000750bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000751 if (TlsIndexOff != uint32_t(-1))
752 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000753 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000754 TlsEntries.push_back(nullptr);
755 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000756 return true;
757}
758
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000759static uint64_t getMipsPageAddr(uint64_t Addr) {
760 return (Addr + 0x8000) & ~0xffff;
761}
762
763static uint64_t getMipsPageCount(uint64_t Size) {
764 return (Size + 0xfffe) / 0xffff + 1;
765}
766
George Rimar14534eb2017-03-20 16:44:28 +0000767uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
768 int64_t Addend) const {
Rafael Espindola24e6f362017-02-24 15:07:30 +0000769 const OutputSection *OutSec =
Rafael Espindola5e434b32017-03-08 16:08:36 +0000770 cast<DefinedRegular>(&B)->Section->getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000771 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
772 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
773 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000774 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000775 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000776}
777
George Rimar14534eb2017-03-20 16:44:28 +0000778uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
779 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000780 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000781 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000782 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000783 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000784 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000785 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000786 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000787 Index += LocalEntries.size();
788 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000789 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000790 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000791 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000792 auto It = EntryIndexMap.find({&B, Addend});
793 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000794 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000795 }
George Rimar14534eb2017-03-20 16:44:28 +0000796 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000797}
798
George Rimar14534eb2017-03-20 16:44:28 +0000799uint64_t MipsGotSection::getTlsOffset() const {
800 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000801}
802
George Rimar14534eb2017-03-20 16:44:28 +0000803uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
804 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000805}
806
George Rimar14534eb2017-03-20 16:44:28 +0000807const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000808 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000809}
810
George Rimar14534eb2017-03-20 16:44:28 +0000811unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000812 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
813 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000814}
815
George Rimar14534eb2017-03-20 16:44:28 +0000816void MipsGotSection::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000817 updateAllocSize();
818}
819
George Rimar14534eb2017-03-20 16:44:28 +0000820void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000821 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000822 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000823 // For each output section referenced by GOT page relocations calculate
824 // and save into PageIndexMap an upper bound of MIPS GOT entries required
825 // to store page addresses of local symbols. We assume the worst case -
826 // each 64kb page of the output section has at least one GOT relocation
827 // against it. And take in account the case when the section intersects
828 // page boundaries.
829 P.second = PageEntriesNum;
830 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000831 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000832 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000833 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000834}
835
George Rimar14534eb2017-03-20 16:44:28 +0000836bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000837 // We add the .got section to the result for dynamic MIPS target because
838 // its address and properties are mentioned in the .dynamic section.
839 return Config->Relocatable;
840}
841
George Rimar14534eb2017-03-20 16:44:28 +0000842uint64_t MipsGotSection::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000843 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000844}
845
George Rimar5f73bc92017-03-29 15:23:28 +0000846static uint64_t readUint(uint8_t *Buf) {
847 if (Config->Is64)
848 return read64(Buf, Config->Endianness);
849 return read32(Buf, Config->Endianness);
850}
851
George Rimar14534eb2017-03-20 16:44:28 +0000852static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000853 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000854 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000855 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000856 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000857}
858
George Rimar14534eb2017-03-20 16:44:28 +0000859void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000860 // Set the MSB of the second GOT slot. This is not required by any
861 // MIPS ABI documentation, though.
862 //
863 // There is a comment in glibc saying that "The MSB of got[1] of a
864 // gnu object is set to identify gnu objects," and in GNU gold it
865 // says "the second entry will be used by some runtime loaders".
866 // But how this field is being used is unclear.
867 //
868 // We are not really willing to mimic other linkers behaviors
869 // without understanding why they do that, but because all files
870 // generated by GNU tools have this special GOT value, and because
871 // we've been doing this for years, it is probably a safe bet to
872 // keep doing this for now. We really need to revisit this to see
873 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000874 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
875 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000876 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000877 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000878 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000879 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000880 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000881 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
882 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000883 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000884 }
George Rimar14534eb2017-03-20 16:44:28 +0000885 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000886 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000887 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000888 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000889 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000890 uint64_t VA = Body->getVA(SA.second);
891 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000892 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000893 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
894 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
895 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000896 // Initialize TLS-related GOT entries. If the entry has a corresponding
897 // dynamic relocations, leave it initialized by zero. Write down adjusted
898 // TLS symbol's values otherwise. To calculate the adjustments use offsets
899 // for thread-local storage.
900 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000901 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000902 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000903 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000904 if (!B || B->isPreemptible())
905 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000906 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000907 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000908 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
909 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000910 }
911 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000912 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
913 writeUint(Entry, 1);
914 Entry += Config->Wordsize;
915 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000916 }
917 }
918}
919
George Rimar10f74fc2017-03-15 09:12:56 +0000920GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000921 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
922 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000923
George Rimar10f74fc2017-03-15 09:12:56 +0000924void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000925 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
926 Entries.push_back(&Sym);
927}
928
George Rimar10f74fc2017-03-15 09:12:56 +0000929size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000930 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
931 Target->GotPltEntrySize;
932}
933
George Rimar10f74fc2017-03-15 09:12:56 +0000934void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000935 Target->writeGotPltHeader(Buf);
936 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
937 for (const SymbolBody *B : Entries) {
938 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000939 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000940 }
941}
942
Peter Smithbaffdb82016-12-08 12:58:55 +0000943// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
944// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000945IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000946 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
947 Target->GotPltEntrySize,
948 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000949
George Rimar10f74fc2017-03-15 09:12:56 +0000950void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000951 Sym.IsInIgot = true;
952 Sym.GotPltIndex = Entries.size();
953 Entries.push_back(&Sym);
954}
955
George Rimar10f74fc2017-03-15 09:12:56 +0000956size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000957 return Entries.size() * Target->GotPltEntrySize;
958}
959
George Rimar10f74fc2017-03-15 09:12:56 +0000960void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000961 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000962 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000963 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000964 }
965}
966
George Rimar49648002017-03-15 09:32:36 +0000967StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
968 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000969 Dynamic(Dynamic) {
970 // ELF string tables start with a NUL byte.
971 addString("");
972}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000973
974// Adds a string to the string table. If HashIt is true we hash and check for
975// duplicates. It is optional because the name of global symbols are already
976// uniqued and hashing them again has a big cost for a small value: uniquing
977// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000978unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000979 if (HashIt) {
980 auto R = StringMap.insert(std::make_pair(S, this->Size));
981 if (!R.second)
982 return R.first->second;
983 }
984 unsigned Ret = this->Size;
985 this->Size = this->Size + S.size() + 1;
986 Strings.push_back(S);
987 return Ret;
988}
989
George Rimar49648002017-03-15 09:32:36 +0000990void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000991 for (StringRef S : Strings) {
992 memcpy(Buf, S.data(), S.size());
993 Buf += S.size() + 1;
994 }
995}
996
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000997// Returns the number of version definition entries. Because the first entry
998// is for the version definition itself, it is the number of versioned symbols
999// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001000static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1001
1002template <class ELFT>
1003DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001004 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001005 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001006 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001007
Petr Hosekffa786f2017-05-26 19:12:38 +00001008 // .dynamic section is not writable on MIPS and on Fuchsia OS
1009 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001010 // See "Special Section" in Chapter 4 in the following document:
1011 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001012 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001013 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)
Rafael Espindola895aea62017-05-11 22:02:41 +00001024 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001025 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001026 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001027 InX::DynStrTab->addString(Config->Rpath)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001028 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1029 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001030 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001031 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001032 add({DT_SONAME, InX::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 Hosekffa786f2017-05-26 19:12:38 +00001057 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1058 // need it for each process, so we don't write it for DSOs. The loader writes
1059 // the pointer into this entry.
1060 //
1061 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1062 // systems (currently only Fuchsia OS) provide other means to give the
1063 // debugger this information. Such systems may choose make .dynamic read-only.
1064 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1065 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001066 add({DT_DEBUG, (uint64_t)0});
1067}
1068
1069// Add remaining entries to complete .dynamic contents.
1070template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1071 if (this->Size)
1072 return; // Already finalized.
1073
Rafael Espindola895aea62017-05-11 22:02:41 +00001074 this->Link = InX::DynStrTab->OutSec->SectionIndex;
Peter Smithbaffdb82016-12-08 12:58:55 +00001075 if (In<ELFT>::RelaDyn->OutSec->Size > 0) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001076 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001077 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Peter Smithbaffdb82016-12-08 12:58:55 +00001078 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001079 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001080 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001081
1082 // MIPS dynamic loader does not support RELCOUNT tag.
1083 // The problem is in the tight relation between dynamic
1084 // relocations and GOT. So do not emit this tag on MIPS.
1085 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001086 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001087 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001088 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001089 }
1090 }
Peter Smithbaffdb82016-12-08 12:58:55 +00001091 if (In<ELFT>::RelaPlt->OutSec->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001092 add({DT_JMPREL, In<ELFT>::RelaPlt});
Peter Smithbaffdb82016-12-08 12:58:55 +00001093 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001094 add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Rafael Espindola4b1c3692017-05-11 21:23:38 +00001095 InX::GotPlt});
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001096 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001097 }
1098
George Rimar69b17c32017-05-16 10:04:42 +00001099 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001100 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001101 add({DT_STRTAB, InX::DynStrTab});
1102 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001103 if (!Config->ZText)
1104 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001105 if (InX::GnuHashTab)
1106 add({DT_GNU_HASH, InX::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001107 if (In<ELFT>::HashTab)
1108 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001109
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001110 if (Out::PreinitArray) {
1111 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1112 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001113 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001114 if (Out::InitArray) {
1115 add({DT_INIT_ARRAY, Out::InitArray});
1116 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001117 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001118 if (Out::FiniArray) {
1119 add({DT_FINI_ARRAY, Out::FiniArray});
1120 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001121 }
1122
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001123 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001124 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001125 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001126 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001127
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001128 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1129 if (HasVerNeed || In<ELFT>::VerDef)
1130 add({DT_VERSYM, In<ELFT>::VerSym});
1131 if (In<ELFT>::VerDef) {
1132 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001133 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001134 }
1135 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001136 add({DT_VERNEED, In<ELFT>::VerNeed});
1137 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001138 }
1139
1140 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001141 add({DT_MIPS_RLD_VERSION, 1});
1142 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1143 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
George Rimar69b17c32017-05-16 10:04:42 +00001144 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001145 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1146 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001147 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001148 else
George Rimar69b17c32017-05-16 10:04:42 +00001149 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001150 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001151 if (InX::MipsRldMap)
1152 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001153 }
1154
Eugene Leviant6380ce22016-11-15 12:26:55 +00001155 this->OutSec->Link = this->Link;
1156
1157 // +1 for DT_NULL
1158 this->Size = (Entries.size() + 1) * this->Entsize;
1159}
1160
1161template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1162 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1163
1164 for (const Entry &E : Entries) {
1165 P->d_tag = E.Tag;
1166 switch (E.Kind) {
1167 case Entry::SecAddr:
1168 P->d_un.d_ptr = E.OutSec->Addr;
1169 break;
1170 case Entry::InSecAddr:
1171 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
1172 break;
1173 case Entry::SecSize:
1174 P->d_un.d_val = E.OutSec->Size;
1175 break;
1176 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001177 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001178 break;
1179 case Entry::PlainInt:
1180 P->d_un.d_val = E.Val;
1181 break;
1182 }
1183 ++P;
1184 }
1185}
1186
George Rimar97def8c2017-03-17 12:07:44 +00001187uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001188 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001189}
1190
George Rimar97def8c2017-03-17 12:07:44 +00001191int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001192 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001193 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001194 return Addend;
1195}
1196
George Rimar97def8c2017-03-17 12:07:44 +00001197uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001198 if (Sym && !UseSymVA)
1199 return Sym->DynsymIndex;
1200 return 0;
1201}
1202
1203template <class ELFT>
1204RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001205 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001206 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001207 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001208 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001209}
1210
1211template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001212void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001213 if (Reloc.Type == Target->RelativeRel)
1214 ++NumRelativeRelocs;
1215 Relocs.push_back(Reloc);
1216}
1217
1218template <class ELFT, class RelTy>
1219static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001220 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1221 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001222 if (AIsRel != BIsRel)
1223 return AIsRel;
1224
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001225 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001226}
1227
1228template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1229 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001230 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001231 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001232 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001233
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001234 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001235 P->r_addend = Rel.getAddend();
1236 P->r_offset = Rel.getOffset();
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001237 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001238 // Dynamic relocation against MIPS GOT section make deal TLS entries
1239 // allocated in the end of the GOT. We need to adjust the offset to take
1240 // in account 'local' and 'global' GOT entries.
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001241 P->r_offset += InX::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001242 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001243 }
1244
1245 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001246 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001247 std::stable_sort((Elf_Rela *)BufBegin,
1248 (Elf_Rela *)BufBegin + Relocs.size(),
1249 compRelocations<ELFT, Elf_Rela>);
1250 else
1251 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1252 compRelocations<ELFT, Elf_Rel>);
1253 }
1254}
1255
1256template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1257 return this->Entsize * Relocs.size();
1258}
1259
Rui Ueyama945055a2017-02-27 03:07:41 +00001260template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
George Rimar69b17c32017-05-16 10:04:42 +00001261 this->Link = InX::DynSymTab ? InX::DynSymTab->OutSec->SectionIndex
1262 : InX::SymTab->OutSec->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001263
1264 // Set required output section properties.
1265 this->OutSec->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001266}
1267
George Rimarf45f6812017-05-16 08:53:30 +00001268SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001269 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001270 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001271 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001272 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001273 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001274
1275// Orders symbols according to their positions in the GOT,
1276// in compliance with MIPS ABI rules.
1277// See "Global Offset Table" in Chapter 5 in the following document
1278// for detailed description:
1279// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001280static bool sortMipsSymbols(const SymbolTableEntry &L,
1281 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001282 // Sort entries related to non-local preemptible symbols by GOT indexes.
1283 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001284 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1285 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001286 if (LIsInLocalGot || RIsInLocalGot)
1287 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001288 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001289}
1290
Rui Ueyamabb07d102017-02-27 03:31:19 +00001291// Finalize a symbol table. The ELF spec requires that all local
1292// symbols precede global symbols, so we sort symbol entries in this
1293// function. (For .dynsym, we don't do that because symbols for
1294// dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001295void SymbolTableBaseSection::finalizeContents() {
Rui Ueyama6e967342017-02-28 03:29:12 +00001296 this->OutSec->Link = StrTabSec.OutSec->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001297
Rui Ueyama6e967342017-02-28 03:29:12 +00001298 // If it is a .dynsym, there should be no local symbols, but we need
1299 // to do a few things for the dynamic linker.
1300 if (this->Type == SHT_DYNSYM) {
1301 // Section's Info field has the index of the first non-local symbol.
1302 // Because the first symbol entry is a null entry, 1 is the first.
Rui Ueyama6e967342017-02-28 03:29:12 +00001303 this->OutSec->Info = 1;
1304
George Rimarf45f6812017-05-16 08:53:30 +00001305 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001306 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001307 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001308 } else if (Config->EMachine == EM_MIPS) {
1309 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1310 }
1311
1312 size_t I = 0;
1313 for (const SymbolTableEntry &S : Symbols)
1314 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001315 return;
Peter Smith55865432017-02-20 11:12:33 +00001316 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001317}
Peter Smith55865432017-02-20 11:12:33 +00001318
George Rimarf45f6812017-05-16 08:53:30 +00001319void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001320 if (this->Type == SHT_DYNSYM)
1321 return;
1322 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001323 auto It = std::stable_partition(
1324 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1325 return S.Symbol->isLocal() ||
1326 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1327 });
1328 size_t NumLocals = It - Symbols.begin();
Rui Ueyama1f032532017-02-28 01:56:36 +00001329 this->OutSec->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001330}
1331
George Rimarf45f6812017-05-16 08:53:30 +00001332void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001333 // Adding a local symbol to a .dynsym is a bug.
1334 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001335
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001336 bool HashIt = B->isLocal();
1337 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001338}
1339
George Rimarf45f6812017-05-16 08:53:30 +00001340size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001341 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1342 if (E.Symbol == Body)
1343 return true;
1344 // This is used for -r, so we have to handle multiple section
1345 // symbols being combined.
1346 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola5616adf2017-03-08 22:36:28 +00001347 return cast<DefinedRegular>(Body)->Section->getOutputSection() ==
1348 cast<DefinedRegular>(E.Symbol)->Section->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001349 return false;
1350 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001351 if (I == Symbols.end())
1352 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001353 return I - Symbols.begin() + 1;
1354}
1355
George Rimarf45f6812017-05-16 08:53:30 +00001356template <class ELFT>
1357SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1358 : SymbolTableBaseSection(StrTabSec) {
1359 this->Entsize = sizeof(Elf_Sym);
1360}
1361
Rui Ueyama1f032532017-02-28 01:56:36 +00001362// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001363template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001364 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001365 Buf += sizeof(Elf_Sym);
1366
Eugene Leviant9230db92016-11-17 09:16:34 +00001367 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001368
Rui Ueyama1f032532017-02-28 01:56:36 +00001369 for (SymbolTableEntry &Ent : Symbols) {
1370 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001371
Rui Ueyama1b003182017-02-28 19:22:09 +00001372 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001373 if (Body->isLocal()) {
1374 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1375 } else {
1376 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1377 ESym->setVisibility(Body->symbol()->Visibility);
1378 }
1379
1380 ESym->st_name = Ent.StrTabOffset;
Rui Ueyama3bc39012017-02-27 22:39:50 +00001381 ESym->st_size = Body->getSize<ELFT>();
Eugene Leviant9230db92016-11-17 09:16:34 +00001382
Rui Ueyama1b003182017-02-28 19:22:09 +00001383 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001384 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001385 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001386 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001387 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001388 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001389 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001390
1391 // st_value is usually an address of a symbol, but that has a
1392 // special meaining for uninstantiated common symbols (this can
1393 // occur if -r is given).
1394 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001395 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001396 else
George Rimarf64618a2017-03-17 11:56:54 +00001397 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001398
Rui Ueyama1f032532017-02-28 01:56:36 +00001399 ++ESym;
1400 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001401
Rui Ueyama1f032532017-02-28 01:56:36 +00001402 // On MIPS we need to mark symbol which has a PLT entry and requires
1403 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1404 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1405 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1406 if (Config->EMachine == EM_MIPS) {
1407 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1408
1409 for (SymbolTableEntry &Ent : Symbols) {
1410 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001411 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001412 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001413
1414 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001415 if (auto *D = dyn_cast<DefinedRegular>(Body))
1416 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001417 ESym->st_other |= STO_MIPS_PIC;
1418 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001419 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001420 }
1421}
1422
Rui Ueyamae4120632017-02-28 22:05:13 +00001423// .hash and .gnu.hash sections contain on-disk hash tables that map
1424// symbol names to their dynamic symbol table indices. Their purpose
1425// is to help the dynamic linker resolve symbols quickly. If ELF files
1426// don't have them, the dynamic linker has to do linear search on all
1427// dynamic symbols, which makes programs slower. Therefore, a .hash
1428// section is added to a DSO by default. A .gnu.hash is added if you
1429// give the -hash-style=gnu or -hash-style=both option.
1430//
1431// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1432// Each ELF file has a list of DSOs that the ELF file depends on and a
1433// list of dynamic symbols that need to be resolved from any of the
1434// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1435// where m is the number of DSOs and n is the number of dynamic
1436// symbols. For modern large programs, both m and n are large. So
1437// making each step faster by using hash tables substiantially
1438// improves time to load programs.
1439//
1440// (Note that this is not the only way to design the shared library.
1441// For instance, the Windows DLL takes a different approach. On
1442// Windows, each dynamic symbol has a name of DLL from which the symbol
1443// has to be resolved. That makes the cost of symbol resolution O(n).
1444// This disables some hacky techniques you can use on Unix such as
1445// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1446//
1447// Due to historical reasons, we have two different hash tables, .hash
1448// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1449// and better version of .hash. .hash is just an on-disk hash table, but
1450// .gnu.hash has a bloom filter in addition to a hash table to skip
1451// DSOs very quickly. If you are sure that your dynamic linker knows
1452// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1453// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001454GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001455 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1456}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001457
George Rimarf45f6812017-05-16 08:53:30 +00001458void GnuHashTableSection::finalizeContents() {
1459 this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001460
1461 // Computes bloom filter size in word size. We want to allocate 8
1462 // bits for each symbol. It must be a power of two.
1463 if (Symbols.empty())
1464 MaskWords = 1;
1465 else
George Rimar5f73bc92017-03-29 15:23:28 +00001466 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001467
George Rimar5f73bc92017-03-29 15:23:28 +00001468 Size = 16; // Header
1469 Size += Config->Wordsize * MaskWords; // Bloom filter
1470 Size += NBuckets * 4; // Hash buckets
1471 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001472}
1473
George Rimarf45f6812017-05-16 08:53:30 +00001474void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001475 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001476 write32(Buf, NBuckets, Config->Endianness);
George Rimarf45f6812017-05-16 08:53:30 +00001477 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
George Rimar5f73bc92017-03-29 15:23:28 +00001478 Config->Endianness);
1479 write32(Buf + 8, MaskWords, Config->Endianness);
1480 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001481 Buf += 16;
1482
Rui Ueyama7986b452017-03-01 18:09:09 +00001483 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001484 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001485 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001486 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001487}
1488
Rui Ueyama7986b452017-03-01 18:09:09 +00001489// This function writes a 2-bit bloom filter. This bloom filter alone
1490// usually filters out 80% or more of all symbol lookups [1].
1491// The dynamic linker uses the hash table only when a symbol is not
1492// filtered out by a bloom filter.
1493//
1494// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1495// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001496void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001497 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001498 for (const Entry &Sym : Symbols) {
1499 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001500 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1501 Val |= uint64_t(1) << (Sym.Hash % C);
1502 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1503 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001504 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001505}
1506
George Rimarf45f6812017-05-16 08:53:30 +00001507void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001508 // Group symbols by hash value.
1509 std::vector<std::vector<Entry>> Syms(NBuckets);
1510 for (const Entry &Ent : Symbols)
1511 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001512
Rui Ueyamae13373b2017-03-01 02:51:42 +00001513 // Write hash buckets. Hash buckets contain indices in the following
1514 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001515 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001516 for (size_t I = 0; I < NBuckets; ++I)
1517 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001518 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001519
1520 // Write a hash value table. It represents a sequence of chains that
1521 // share the same hash modulo value. The last element of each chain
1522 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001523 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001524 size_t I = 0;
1525 for (std::vector<Entry> &Vec : Syms) {
1526 if (Vec.empty())
1527 continue;
1528 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001529 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1530 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001531 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001532}
1533
1534static uint32_t hashGnu(StringRef Name) {
1535 uint32_t H = 5381;
1536 for (uint8_t C : Name)
1537 H = (H << 5) + H + C;
1538 return H;
1539}
1540
Rui Ueyamae13373b2017-03-01 02:51:42 +00001541// Returns a number of hash buckets to accomodate given number of elements.
1542// We want to choose a moderate number that is not too small (which
1543// causes too many hash collisions) and not too large (which wastes
1544// disk space.)
1545//
1546// We return a prime number because it (is believed to) achieve good
1547// hash distribution.
1548static size_t getBucketSize(size_t NumSymbols) {
1549 // List of largest prime numbers that are not greater than 2^n + 1.
1550 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1551 251, 127, 61, 31, 13, 7, 3, 1})
1552 if (N <= NumSymbols)
1553 return N;
1554 return 0;
1555}
1556
Eugene Leviantbe809a72016-11-18 06:44:18 +00001557// Add symbols to this symbol hash table. Note that this function
1558// destructively sort a given vector -- which is needed because
1559// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001560void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001561 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1562 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001563 std::vector<SymbolTableEntry>::iterator Mid =
1564 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1565 return S.Symbol->isUndefined();
1566 });
1567 if (Mid == V.end())
1568 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001569
1570 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1571 SymbolBody *B = Ent.Symbol;
1572 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001573 }
1574
Rui Ueyamae13373b2017-03-01 02:51:42 +00001575 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001576 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001577 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001578 return L.Hash % NBuckets < R.Hash % NBuckets;
1579 });
1580
1581 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001582 for (const Entry &Ent : Symbols)
1583 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001584}
1585
Eugene Leviantb96e8092016-11-18 09:06:47 +00001586template <class ELFT>
1587HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001588 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1589 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001590}
1591
Rui Ueyama945055a2017-02-27 03:07:41 +00001592template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
George Rimar69b17c32017-05-16 10:04:42 +00001593 this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001594
1595 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001596 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001597
1598 // Create as many buckets as there are symbols.
1599 // FIXME: This is simplistic. We can try to optimize it, but implementing
1600 // support for SHT_GNU_HASH is probably even more profitable.
George Rimar69b17c32017-05-16 10:04:42 +00001601 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001602 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001603}
1604
1605template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001606 // A 32-bit integer type in the target endianness.
1607 typedef typename ELFT::Word Elf_Word;
1608
George Rimar69b17c32017-05-16 10:04:42 +00001609 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001610
Eugene Leviantb96e8092016-11-18 09:06:47 +00001611 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1612 *P++ = NumSymbols; // nbucket
1613 *P++ = NumSymbols; // nchain
1614
1615 Elf_Word *Buckets = P;
1616 Elf_Word *Chains = P + NumSymbols;
1617
George Rimar69b17c32017-05-16 10:04:42 +00001618 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001619 SymbolBody *Body = S.Symbol;
1620 StringRef Name = Body->getName();
1621 unsigned I = Body->DynsymIndex;
1622 uint32_t Hash = hashSysV(Name) % NumSymbols;
1623 Chains[I] = Buckets[Hash];
1624 Buckets[Hash] = I;
1625 }
1626}
1627
George Rimardfc020e2017-03-17 11:01:57 +00001628PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001629 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Peter Smithf09245a2017-02-09 10:56:15 +00001630 HeaderSize(S) {}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001631
George Rimardfc020e2017-03-17 11:01:57 +00001632void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001633 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1634 // linker to resolve dynsyms at runtime. Write such code.
1635 if (HeaderSize != 0)
1636 Target->writePltHeader(Buf);
1637 size_t Off = HeaderSize;
1638 // The IPlt is immediately after the Plt, account for this in RelOff
1639 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001640
1641 for (auto &I : Entries) {
1642 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001643 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001644 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001645 uint64_t Plt = this->getVA() + Off;
1646 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1647 Off += Target->PltEntrySize;
1648 }
1649}
1650
George Rimardfc020e2017-03-17 11:01:57 +00001651template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001652 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001653 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1654 if (HeaderSize == 0) {
1655 PltRelocSection = In<ELFT>::RelaIplt;
1656 Sym.IsInIplt = true;
1657 }
1658 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001659 Entries.push_back(std::make_pair(&Sym, RelOff));
1660}
1661
George Rimardfc020e2017-03-17 11:01:57 +00001662size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001663 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001664}
1665
Peter Smith96943762017-01-25 10:31:16 +00001666// Some architectures such as additional symbols in the PLT section. For
1667// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001668void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001669 // The PLT may have symbols defined for the Header, the IPLT has no header
1670 if (HeaderSize != 0)
1671 Target->addPltHeaderSymbols(this);
1672 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001673 for (size_t I = 0; I < Entries.size(); ++I) {
1674 Target->addPltSymbols(this, Off);
1675 Off += Target->PltEntrySize;
1676 }
1677}
1678
George Rimardfc020e2017-03-17 11:01:57 +00001679unsigned PltSection::getPltRelocOff() const {
1680 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001681}
1682
George Rimar35e846e2017-03-21 08:19:34 +00001683GdbIndexSection::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001684 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001685 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001686
George Rimarec02b8d2016-12-15 12:07:53 +00001687// Iterative hash function for symbol's name is described in .gdb_index format
1688// specification. Note that we use one for version 5 to 7 here, it is different
1689// for version 4.
1690static uint32_t hash(StringRef Str) {
1691 uint32_t R = 0;
1692 for (uint8_t C : Str)
1693 R = R * 67 + tolower(C) - 113;
1694 return R;
1695}
1696
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001697static std::vector<std::pair<uint64_t, uint64_t>>
1698readCuList(DWARFContext &Dwarf, InputSection *Sec) {
1699 std::vector<std::pair<uint64_t, uint64_t>> Ret;
1700 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1701 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1702 return Ret;
1703}
1704
Peter Collingbourne0a2678e2017-05-15 17:59:21 +00001705static InputSection *findSection(ArrayRef<InputSectionBase *> Arr,
1706 uint64_t Offset) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001707 for (InputSectionBase *S : Arr)
Peter Collingbourne0a2678e2017-05-15 17:59:21 +00001708 if (auto *IS = dyn_cast_or_null<InputSection>(S))
1709 if (IS != &InputSection::Discarded && IS->Live &&
1710 Offset >= IS->getOffsetInFile() &&
1711 Offset < IS->getOffsetInFile() + IS->getSize())
1712 return IS;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001713 return nullptr;
1714}
1715
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001716static std::vector<AddressEntry>
1717readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) {
1718 std::vector<AddressEntry> Ret;
1719
1720 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1721 DWARFAddressRangesVector Ranges;
1722 CU->collectAddressRanges(Ranges);
1723
George Rimar35e846e2017-03-21 08:19:34 +00001724 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimard8daafd2017-05-16 12:34:51 +00001725 for (DWARFAddressRange &R : Ranges)
1726 if (InputSection *S = findSection(Sections, R.LowPC))
1727 Ret.push_back({S, R.LowPC - S->getOffsetInFile(),
1728 R.HighPC - S->getOffsetInFile(), CurrentCU});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001729 ++CurrentCU;
1730 }
1731 return Ret;
1732}
1733
1734static std::vector<std::pair<StringRef, uint8_t>>
1735readPubNamesAndTypes(DWARFContext &Dwarf, bool IsLE) {
1736 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1737 Dwarf.getGnuPubTypesSection()};
1738
1739 std::vector<std::pair<StringRef, uint8_t>> Ret;
1740 for (StringRef D : Data) {
1741 DWARFDebugPubTable PubTable(D, IsLE, true);
1742 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1743 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1744 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1745 }
1746 return Ret;
1747}
1748
1749class ObjInfoTy : public llvm::LoadedObjectInfo {
1750 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
1751 auto &S = static_cast<const object::ELFSectionRef &>(Sec);
1752 if (S.getFlags() & ELF::SHF_ALLOC)
1753 return S.getOffset();
1754 return 0;
1755 }
1756
1757 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override { return {}; }
1758};
1759
George Rimar35e846e2017-03-21 08:19:34 +00001760void GdbIndexSection::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001761 Expected<std::unique_ptr<object::ObjectFile>> Obj =
George Rimar05423482017-03-20 10:47:00 +00001762 object::ObjectFile::createObjectFile(Sec->File->MB);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001763 if (!Obj) {
George Rimar05423482017-03-20 10:47:00 +00001764 error(toString(Sec->File) + ": error creating DWARF context");
George Rimar8b547392016-12-15 09:08:13 +00001765 return;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001766 }
1767
1768 ObjInfoTy ObjInfo;
1769 DWARFContextInMemory Dwarf(*Obj.get(), &ObjInfo);
George Rimar8b547392016-12-15 09:08:13 +00001770
1771 size_t CuId = CompilationUnits.size();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001772 for (std::pair<uint64_t, uint64_t> &P : readCuList(Dwarf, Sec))
1773 CompilationUnits.push_back(P);
George Rimar8b547392016-12-15 09:08:13 +00001774
George Rimar35e846e2017-03-21 08:19:34 +00001775 for (AddressEntry &Ent : readAddressArea(Dwarf, Sec, CuId))
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001776 AddressArea.push_back(Ent);
George Rimarec02b8d2016-12-15 12:07:53 +00001777
1778 std::vector<std::pair<StringRef, uint8_t>> NamesAndTypes =
George Rimar35e846e2017-03-21 08:19:34 +00001779 readPubNamesAndTypes(Dwarf, Config->IsLE);
George Rimarec02b8d2016-12-15 12:07:53 +00001780
1781 for (std::pair<StringRef, uint8_t> &Pair : NamesAndTypes) {
1782 uint32_t Hash = hash(Pair.first);
1783 size_t Offset = StringPool.add(Pair.first);
1784
1785 bool IsNew;
1786 GdbSymbol *Sym;
1787 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1788 if (IsNew) {
1789 Sym->CuVectorIndex = CuVectors.size();
George Rimar1ef2e232017-05-26 18:07:25 +00001790 CuVectors.resize(CuVectors.size() + 1);
George Rimarec02b8d2016-12-15 12:07:53 +00001791 }
1792
George Rimar8684dba2017-05-26 12:16:39 +00001793 CuVectors[Sym->CuVectorIndex].insert((Pair.second << 24) | (uint32_t)CuId);
George Rimarec02b8d2016-12-15 12:07:53 +00001794 }
Eugene Levianta113a412016-11-21 09:24:43 +00001795}
1796
George Rimar35e846e2017-03-21 08:19:34 +00001797void GdbIndexSection::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001798 if (Finalized)
1799 return;
1800 Finalized = true;
1801
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001802 for (InputSectionBase *S : InputSections)
1803 if (InputSection *IS = dyn_cast<InputSection>(S))
1804 if (IS->OutSec && IS->Name == ".debug_info")
1805 readDwarf(IS);
1806
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001807 SymbolTable.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001808
1809 // GdbIndex header consist from version fields
1810 // and 5 more fields with different kinds of offsets.
1811 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
George Rimar8b547392016-12-15 09:08:13 +00001812 SymTabOffset = CuTypesOffset + AddressArea.size() * AddressEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001813
1814 ConstantPoolOffset =
1815 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1816
George Rimarc1a03642017-05-26 12:09:26 +00001817 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001818 CuVectorsOffset.push_back(CuVectorsSize);
1819 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1820 }
1821 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1822
1823 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001824}
1825
George Rimar35e846e2017-03-21 08:19:34 +00001826size_t GdbIndexSection::getSize() const {
1827 const_cast<GdbIndexSection *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001828 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001829}
1830
George Rimar35e846e2017-03-21 08:19:34 +00001831void GdbIndexSection::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001832 write32le(Buf, 7); // Write version.
1833 write32le(Buf + 4, CuListOffset); // CU list offset.
1834 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1835 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1836 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1837 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001838 Buf += 24;
1839
1840 // Write the CU list.
George Rimarf6abfd72017-03-20 10:40:40 +00001841 for (std::pair<uint64_t, uint64_t> CU : CompilationUnits) {
Eugene Levianta113a412016-11-21 09:24:43 +00001842 write64le(Buf, CU.first);
1843 write64le(Buf + 8, CU.second);
1844 Buf += 16;
1845 }
George Rimar8b547392016-12-15 09:08:13 +00001846
1847 // Write the address area.
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001848 for (AddressEntry &E : AddressArea) {
George Rimarf6abfd72017-03-20 10:40:40 +00001849 uint64_t BaseAddr = E.Section->OutSec->Addr + E.Section->getOffset(0);
George Rimar8b547392016-12-15 09:08:13 +00001850 write64le(Buf, BaseAddr + E.LowAddress);
1851 write64le(Buf + 8, BaseAddr + E.HighAddress);
1852 write32le(Buf + 16, E.CuIndex);
1853 Buf += 20;
1854 }
George Rimarec02b8d2016-12-15 12:07:53 +00001855
1856 // Write the symbol table.
1857 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1858 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1859 if (Sym) {
1860 size_t NameOffset =
1861 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1862 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1863 write32le(Buf, NameOffset);
1864 write32le(Buf + 4, CuVectorOffset);
1865 }
1866 Buf += 8;
1867 }
1868
1869 // Write the CU vectors into the constant pool.
George Rimarc1a03642017-05-26 12:09:26 +00001870 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001871 write32le(Buf, CuVec.size());
1872 Buf += 4;
George Rimar5f5905e2017-05-26 12:01:40 +00001873 for (uint32_t Val : CuVec) {
1874 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00001875 Buf += 4;
1876 }
1877 }
1878
1879 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001880}
1881
George Rimar35e846e2017-03-21 08:19:34 +00001882bool GdbIndexSection::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001883 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001884}
1885
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001886template <class ELFT>
1887EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001888 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001889
1890// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1891// Each entry of the search table consists of two values,
1892// the starting PC from where FDEs covers, and the FDE's address.
1893// It is sorted by PC.
1894template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1895 const endianness E = ELFT::TargetEndianness;
1896
1897 // Sort the FDE list by their PC and uniqueify. Usually there is only
1898 // one FDE for a PC (i.e. function), but if ICF merges two functions
1899 // into one, there can be more than one FDEs pointing to the address.
1900 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1901 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1902 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1903 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1904
1905 Buf[0] = 1;
1906 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1907 Buf[2] = DW_EH_PE_udata4;
1908 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola66b4e212017-02-23 22:06:28 +00001909 write32<E>(Buf + 4, In<ELFT>::EhFrame->OutSec->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001910 write32<E>(Buf + 8, Fdes.size());
1911 Buf += 12;
1912
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001913 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001914 for (FdeData &Fde : Fdes) {
1915 write32<E>(Buf, Fde.Pc - VA);
1916 write32<E>(Buf + 4, Fde.FdeVA - VA);
1917 Buf += 8;
1918 }
1919}
1920
1921template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1922 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001923 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001924}
1925
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001926template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001927void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1928 Fdes.push_back({Pc, FdeVA});
1929}
1930
George Rimar11992c862016-11-25 08:05:41 +00001931template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001932 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001933}
1934
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001935template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001936VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001937 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1938 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001939
1940static StringRef getFileDefName() {
1941 if (!Config->SoName.empty())
1942 return Config->SoName;
1943 return Config->OutputFile;
1944}
1945
Rui Ueyama945055a2017-02-27 03:07:41 +00001946template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00001947 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001948 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00001949 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001950
Rafael Espindola895aea62017-05-11 22:02:41 +00001951 this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001952
1953 // sh_info should be set to the number of definitions. This fact is missed in
1954 // documentation, but confirmed by binutils community:
1955 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rui Ueyamac3726f82017-02-28 04:41:20 +00001956 this->OutSec->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001957}
1958
1959template <class ELFT>
1960void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1961 StringRef Name, size_t NameOff) {
1962 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1963 Verdef->vd_version = 1;
1964 Verdef->vd_cnt = 1;
1965 Verdef->vd_aux = sizeof(Elf_Verdef);
1966 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1967 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1968 Verdef->vd_ndx = Index;
1969 Verdef->vd_hash = hashSysV(Name);
1970
1971 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1972 Verdaux->vda_name = NameOff;
1973 Verdaux->vda_next = 0;
1974}
1975
1976template <class ELFT>
1977void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1978 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1979
1980 for (VersionDefinition &V : Config->VersionDefinitions) {
1981 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1982 writeOne(Buf, V.Id, V.Name, V.NameOff);
1983 }
1984
1985 // Need to terminate the last version definition.
1986 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1987 Verdef->vd_next = 0;
1988}
1989
1990template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
1991 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1992}
1993
1994template <class ELFT>
1995VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001996 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00001997 ".gnu.version") {
1998 this->Entsize = sizeof(Elf_Versym);
1999}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002000
Rui Ueyama945055a2017-02-27 03:07:41 +00002001template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002002 // At the moment of june 2016 GNU docs does not mention that sh_link field
2003 // should be set, but Sun docs do. Also readelf relies on this field.
George Rimar69b17c32017-05-16 10:04:42 +00002004 this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002005}
2006
2007template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002008 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002009}
2010
2011template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2012 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002013 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002014 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2015 ++OutVersym;
2016 }
2017}
2018
George Rimar11992c862016-11-25 08:05:41 +00002019template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2020 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2021}
2022
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002023template <class ELFT>
2024VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002025 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2026 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002027 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2028 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2029 // First identifiers are reserved by verdef section if it exist.
2030 NextIndex = getVerDefNum() + 1;
2031}
2032
2033template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002034void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2035 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2036 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002037 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2038 return;
2039 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002040
2041 auto *File = cast<SharedFile<ELFT>>(SS->File);
2042
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002043 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2044 // to create one by adding it to our needed list and creating a dynstr entry
2045 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002046 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002047 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002048 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002049 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2050 // prepare to create one by allocating a version identifier and creating a
2051 // dynstr entry for the version name.
2052 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002053 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2054 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002055 NV.Index = NextIndex++;
2056 }
2057 SS->symbol()->VersionId = NV.Index;
2058}
2059
2060template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2061 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2062 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2063 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2064
2065 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2066 // Create an Elf_Verneed for this DSO.
2067 Verneed->vn_version = 1;
2068 Verneed->vn_cnt = P.first->VerdefMap.size();
2069 Verneed->vn_file = P.second;
2070 Verneed->vn_aux =
2071 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2072 Verneed->vn_next = sizeof(Elf_Verneed);
2073 ++Verneed;
2074
2075 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2076 // VerdefMap, which will only contain references to needed version
2077 // definitions. Each Elf_Vernaux is based on the information contained in
2078 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2079 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2080 // data structures within a single input file.
2081 for (auto &NV : P.first->VerdefMap) {
2082 Vernaux->vna_hash = NV.first->vd_hash;
2083 Vernaux->vna_flags = 0;
2084 Vernaux->vna_other = NV.second.Index;
2085 Vernaux->vna_name = NV.second.StrTab;
2086 Vernaux->vna_next = sizeof(Elf_Vernaux);
2087 ++Vernaux;
2088 }
2089
2090 Vernaux[-1].vna_next = 0;
2091 }
2092 Verneed[-1].vn_next = 0;
2093}
2094
Rui Ueyama945055a2017-02-27 03:07:41 +00002095template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002096 this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex;
Rui Ueyamac3726f82017-02-28 04:41:20 +00002097 this->OutSec->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002098}
2099
2100template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2101 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2102 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2103 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2104 return Size;
2105}
2106
George Rimar11992c862016-11-25 08:05:41 +00002107template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2108 return getNeedNum() == 0;
2109}
2110
Rafael Espindola6119b862017-03-06 20:23:56 +00002111MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002112 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002113 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002114 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002115
Rafael Espindola6119b862017-03-06 20:23:56 +00002116void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002117 assert(!Finalized);
2118 MS->MergeSec = this;
2119 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002120}
2121
Rafael Espindola6119b862017-03-06 20:23:56 +00002122void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002123
Rafael Espindola6119b862017-03-06 20:23:56 +00002124bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002125 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2126}
2127
Rafael Espindola6119b862017-03-06 20:23:56 +00002128void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002129 // Add all string pieces to the string table builder to create section
2130 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002131 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002132 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2133 if (Sec->Pieces[I].Live)
2134 Builder.add(Sec->getData(I));
2135
2136 // Fix the string table content. After this, the contents will never change.
2137 Builder.finalize();
2138
2139 // finalize() fixed tail-optimized strings, so we can now get
2140 // offsets of strings. Get an offset for each string and save it
2141 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002142 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002143 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2144 if (Sec->Pieces[I].Live)
2145 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2146}
2147
Rafael Espindola6119b862017-03-06 20:23:56 +00002148void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002149 // Add all string pieces to the string table builder to create section
2150 // contents. Because we are not tail-optimizing, offsets of strings are
2151 // fixed when they are added to the builder (string table builder contains
2152 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002153 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002154 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2155 if (Sec->Pieces[I].Live)
2156 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2157
2158 Builder.finalizeInOrder();
2159}
2160
Rafael Espindola6119b862017-03-06 20:23:56 +00002161void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002162 if (Finalized)
2163 return;
2164 Finalized = true;
2165 if (shouldTailMerge())
2166 finalizeTailMerge();
2167 else
2168 finalizeNoTailMerge();
2169}
2170
Rafael Espindola6119b862017-03-06 20:23:56 +00002171size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002172 // We should finalize string builder to know the size.
Rafael Espindola6119b862017-03-06 20:23:56 +00002173 const_cast<MergeSyntheticSection *>(this)->finalizeContents();
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002174 return Builder.getSize();
2175}
2176
George Rimar42886c42017-03-15 12:02:31 +00002177MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002178 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2179 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002180
George Rimar90a528b2017-03-21 09:01:39 +00002181ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002182 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002183 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002184
2185// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2186// This section will have been sorted last in the .ARM.exidx table.
2187// This table entry will have the form:
2188// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002189// The sentinel must have the PREL31 value of an address higher than any
2190// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002191void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002192 // The Sections are sorted in order of ascending PREL31 address with the
2193 // sentinel last. We need to find the InputSection that precedes the
2194 // sentinel. By construction the Sentinel is in the last
2195 // InputSectionDescription as the InputSection that precedes it.
2196 OutputSectionCommand *C = Script->getCmd(OutSec);
2197 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
2198 [](const BaseCommand *Base) {
2199 return isa<InputSectionDescription>(Base);
2200 });
2201 auto L = cast<InputSectionDescription>(*ISD);
2202 InputSection *Highest = L->Sections[L->Sections.size() - 2];
2203 InputSection *LS = cast<InputSection>(Highest->getLinkOrderDep());
2204 uint64_t S = LS->OutSec->Addr + LS->getOffset(LS->getSize());
2205 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002206 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2207 write32le(Buf + 4, 0x1);
2208}
2209
George Rimar7b827042017-03-16 10:40:50 +00002210ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002211 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002212 Config->Wordsize, ".text.thunk") {
Peter Smith3a52eb02017-02-01 10:26:03 +00002213 this->OutSec = OS;
2214 this->OutSecOff = Off;
2215}
2216
George Rimar7b827042017-03-16 10:40:50 +00002217void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002218 uint64_t Off = alignTo(Size, T->alignment);
2219 T->Offset = Off;
2220 Thunks.push_back(T);
2221 T->addSymbols(*this);
2222 Size = Off + T->size();
2223}
2224
George Rimar7b827042017-03-16 10:40:50 +00002225void ThunkSection::writeTo(uint8_t *Buf) {
2226 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002227 T->writeTo(Buf + T->Offset, *this);
2228}
2229
George Rimar7b827042017-03-16 10:40:50 +00002230InputSection *ThunkSection::getTargetInputSection() const {
2231 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002232 return T->getTargetInputSection();
2233}
2234
George Rimar9782ca52017-03-15 15:29:29 +00002235InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002236BssSection *InX::Bss;
2237BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002238BuildIdSection *InX::BuildId;
George Rimar9782ca52017-03-15 15:29:29 +00002239InputSection *InX::Common;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002240SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002241StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002242SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002243InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002244GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002245GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002246GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002247GnuHashTableSection *InX::GnuHashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002248IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002249MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002250MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002251PltSection *InX::Plt;
2252PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002253StringTableSection *InX::ShStrTab;
2254StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002255SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002256
George Rimara9189572017-03-17 16:50:07 +00002257template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2258template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2259template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2260template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2261
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002262template InputSection *elf::createCommonSection<ELF32LE>();
2263template InputSection *elf::createCommonSection<ELF32BE>();
2264template InputSection *elf::createCommonSection<ELF64LE>();
2265template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002266
Rafael Espindola6119b862017-03-06 20:23:56 +00002267template MergeInputSection *elf::createCommentSection<ELF32LE>();
2268template MergeInputSection *elf::createCommentSection<ELF32BE>();
2269template MergeInputSection *elf::createCommentSection<ELF64LE>();
2270template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002271
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002272template class elf::MipsAbiFlagsSection<ELF32LE>;
2273template class elf::MipsAbiFlagsSection<ELF32BE>;
2274template class elf::MipsAbiFlagsSection<ELF64LE>;
2275template class elf::MipsAbiFlagsSection<ELF64BE>;
2276
Simon Atanasyance02cf02016-11-09 21:36:56 +00002277template class elf::MipsOptionsSection<ELF32LE>;
2278template class elf::MipsOptionsSection<ELF32BE>;
2279template class elf::MipsOptionsSection<ELF64LE>;
2280template class elf::MipsOptionsSection<ELF64BE>;
2281
2282template class elf::MipsReginfoSection<ELF32LE>;
2283template class elf::MipsReginfoSection<ELF32BE>;
2284template class elf::MipsReginfoSection<ELF64LE>;
2285template class elf::MipsReginfoSection<ELF64BE>;
2286
Eugene Leviant6380ce22016-11-15 12:26:55 +00002287template class elf::DynamicSection<ELF32LE>;
2288template class elf::DynamicSection<ELF32BE>;
2289template class elf::DynamicSection<ELF64LE>;
2290template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002291
2292template class elf::RelocationSection<ELF32LE>;
2293template class elf::RelocationSection<ELF32BE>;
2294template class elf::RelocationSection<ELF64LE>;
2295template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002296
2297template class elf::SymbolTableSection<ELF32LE>;
2298template class elf::SymbolTableSection<ELF32BE>;
2299template class elf::SymbolTableSection<ELF64LE>;
2300template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002301
Eugene Leviantb96e8092016-11-18 09:06:47 +00002302template class elf::HashTableSection<ELF32LE>;
2303template class elf::HashTableSection<ELF32BE>;
2304template class elf::HashTableSection<ELF64LE>;
2305template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002306
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002307template class elf::EhFrameHeader<ELF32LE>;
2308template class elf::EhFrameHeader<ELF32BE>;
2309template class elf::EhFrameHeader<ELF64LE>;
2310template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002311
2312template class elf::VersionTableSection<ELF32LE>;
2313template class elf::VersionTableSection<ELF32BE>;
2314template class elf::VersionTableSection<ELF64LE>;
2315template class elf::VersionTableSection<ELF64BE>;
2316
2317template class elf::VersionNeedSection<ELF32LE>;
2318template class elf::VersionNeedSection<ELF32BE>;
2319template class elf::VersionNeedSection<ELF64LE>;
2320template class elf::VersionNeedSection<ELF64BE>;
2321
2322template class elf::VersionDefinitionSection<ELF32LE>;
2323template class elf::VersionDefinitionSection<ELF32BE>;
2324template class elf::VersionDefinitionSection<ELF64LE>;
2325template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002326
Rafael Espindola66b4e212017-02-23 22:06:28 +00002327template class elf::EhFrameSection<ELF32LE>;
2328template class elf::EhFrameSection<ELF32BE>;
2329template class elf::EhFrameSection<ELF64LE>;
2330template class elf::EhFrameSection<ELF64BE>;