blob: ef7944c81002f65bbf04db689a68be6f07dd6171 [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"
Rui Ueyama6e5fda92017-10-26 21:37:17 +000018#include "Bits.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000019#include "Config.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000020#include "InputFiles.h"
Eugene Leviant17b7a572016-11-22 17:49:14 +000021#include "LinkerScript.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000022#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000023#include "SymbolTable.h"
Rafael Espindolad26b52f2017-12-09 16:56:18 +000024#include "Symbols.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000025#include "Target.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000026#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000027#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000028#include "lld/Common/Memory.h"
Rui Ueyamaee173712018-02-28 17:38:19 +000029#include "lld/Common/Strings.h"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000030#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000031#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000033#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000034#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000035#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000036#include "llvm/Support/Endian.h"
Peter Collingbourne5c54f152017-10-27 17:49:40 +000037#include "llvm/Support/LEB128.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000038#include "llvm/Support/MD5.h"
39#include "llvm/Support/RandomNumberGenerator.h"
40#include "llvm/Support/SHA1.h"
41#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000042#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000043#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000044
45using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000046using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000047using namespace llvm::ELF;
48using namespace llvm::object;
49using namespace llvm::support;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000050
51using namespace lld;
52using namespace lld::elf;
53
Fangrui Song0c483022018-03-09 18:03:22 +000054using llvm::support::endian::write32le;
55using llvm::support::endian::write64le;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000056
Fangrui Song0c483022018-03-09 18:03:22 +000057constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyama79048e42017-10-27 03:59:34 +000058
Rui Ueyama9320cb02017-02-27 02:56:02 +000059uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000060 if (OutputSection *Sec = getParent())
61 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000062 return 0;
63}
64
Rui Ueyama3da3f062016-11-10 20:20:37 +000065// Returns an LLD version string.
66static ArrayRef<uint8_t> getVersion() {
67 // Check LLD_VERSION first for ease of testing.
68 // You can get consitent output by using the environment variable.
69 // This is only for testing.
70 StringRef S = getenv("LLD_VERSION");
71 if (S.empty())
72 S = Saver.save(Twine("Linker: ") + getLLDVersion());
73
74 // +1 to include the terminating '\0'.
75 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000076}
Rui Ueyama3da3f062016-11-10 20:20:37 +000077
78// Creates a .comment section containing LLD version info.
79// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000080// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000081// The returned object is a mergeable string section.
Rafael Espindola5c73c492017-12-21 01:21:59 +000082MergeInputSection *elf::createCommentSection() {
83 return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
84 getVersion(), ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +000085}
86
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000087// .MIPS.abiflags section.
88template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +000089MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +000090 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +000091 Flags(Flags) {
92 this->Entsize = sizeof(Elf_Mips_ABIFlags);
93}
Rui Ueyama12f2da82016-11-22 03:57:06 +000094
95template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
96 memcpy(Buf, &Flags, sizeof(Flags));
97}
98
99template <class ELFT>
100MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
101 Elf_Mips_ABIFlags Flags = {};
102 bool Create = false;
103
Rui Ueyama536a2672017-02-27 02:32:08 +0000104 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000105 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000106 continue;
107 Sec->Live = false;
108 Create = true;
109
Rui Ueyama25f30882017-10-27 03:25:04 +0000110 std::string Filename = toString(Sec->File);
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000111 const size_t Size = Sec->Data.size();
112 // Older version of BFD (such as the default FreeBSD linker) concatenate
113 // .MIPS.abiflags instead of merging. To allow for this case (or potential
114 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
115 if (Size < sizeof(Elf_Mips_ABIFlags)) {
116 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
117 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000118 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000119 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000120 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000121 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000122 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000123 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000124 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000125 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000126
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000127 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000128 // select the highest number of ISA/Rev/Ext.
129 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
130 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
131 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
132 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
133 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
134 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
135 Flags.ases |= S->ases;
136 Flags.flags1 |= S->flags1;
137 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000138 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000139 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000140
Rui Ueyama12f2da82016-11-22 03:57:06 +0000141 if (Create)
142 return make<MipsAbiFlagsSection<ELFT>>(Flags);
143 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000144}
145
Simon Atanasyance02cf02016-11-09 21:36:56 +0000146// .MIPS.options section.
147template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000148MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000149 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000150 Reginfo(Reginfo) {
151 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
152}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000153
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000154template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
155 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
156 Options->kind = ODK_REGINFO;
157 Options->size = getSize();
158
159 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000160 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000161 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000162}
163
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000164template <class ELFT>
165MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
166 // N64 ABI only.
167 if (!ELFT::Is64Bits)
168 return nullptr;
169
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000170 std::vector<InputSectionBase *> Sections;
171 for (InputSectionBase *Sec : InputSections)
172 if (Sec->Type == SHT_MIPS_OPTIONS)
173 Sections.push_back(Sec);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000174
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000175 if (Sections.empty())
176 return nullptr;
177
178 Elf_Mips_RegInfo Reginfo = {};
179 for (InputSectionBase *Sec : Sections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000180 Sec->Live = false;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000181
Rui Ueyama25f30882017-10-27 03:25:04 +0000182 std::string Filename = toString(Sec->File);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000183 ArrayRef<uint8_t> D = Sec->Data;
184
185 while (!D.empty()) {
186 if (D.size() < sizeof(Elf_Mips_Options)) {
187 error(Filename + ": invalid size of .MIPS.options section");
188 break;
189 }
190
191 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
192 if (Opt->kind == ODK_REGINFO) {
193 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
194 error(Filename + ": unsupported non-zero ri_gp_value");
195 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000196 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000197 break;
198 }
199
200 if (!Opt->size)
201 fatal(Filename + ": zero option descriptor size");
202 D = D.slice(Opt->size);
203 }
204 };
205
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000206 return make<MipsOptionsSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000207}
208
209// MIPS .reginfo section.
210template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000211MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000212 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000213 Reginfo(Reginfo) {
214 this->Entsize = sizeof(Elf_Mips_RegInfo);
215}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000216
Rui Ueyamab71cae92016-11-22 03:57:08 +0000217template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000218 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000219 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000220 memcpy(Buf, &Reginfo, sizeof(Reginfo));
221}
222
223template <class ELFT>
224MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
225 // Section should be alive for O32 and N32 ABIs only.
226 if (ELFT::Is64Bits)
227 return nullptr;
228
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000229 std::vector<InputSectionBase *> Sections;
230 for (InputSectionBase *Sec : InputSections)
231 if (Sec->Type == SHT_MIPS_REGINFO)
232 Sections.push_back(Sec);
Rui Ueyamab71cae92016-11-22 03:57:08 +0000233
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000234 if (Sections.empty())
235 return nullptr;
236
237 Elf_Mips_RegInfo Reginfo = {};
238 for (InputSectionBase *Sec : Sections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000239 Sec->Live = false;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000240
241 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama25f30882017-10-27 03:25:04 +0000242 error(toString(Sec->File) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000243 return nullptr;
244 }
245 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
246 if (Config->Relocatable && R->ri_gp_value)
Rui Ueyama25f30882017-10-27 03:25:04 +0000247 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000248
249 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000250 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000251 };
252
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000253 return make<MipsReginfoSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000254}
255
Rui Ueyama3255a522017-02-27 02:32:49 +0000256InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000257 // StringSaver guarantees that the returned string ends with '\0'.
258 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000259 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
260
Rafael Espindolace3b52c2017-12-21 02:11:51 +0000261 auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
262 ".interp");
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000263 Sec->Live = true;
264 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000265}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000266
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000267Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
Rafael Espindola1037eef2017-12-19 23:59:35 +0000268 uint64_t Size, InputSectionBase &Section) {
269 auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
270 Value, Size, &Section);
George Rimar69b17c32017-05-16 10:04:42 +0000271 if (InX::SymTab)
272 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000273 return S;
274}
275
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000276static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000277 switch (Config->BuildId) {
278 case BuildIdKind::Fast:
279 return 8;
280 case BuildIdKind::Md5:
281 case BuildIdKind::Uuid:
282 return 16;
283 case BuildIdKind::Sha1:
284 return 20;
285 case BuildIdKind::Hexstring:
286 return Config->BuildIdVector.size();
287 default:
288 llvm_unreachable("unknown BuildIdKind");
289 }
290}
291
George Rimar6c2949d2017-03-20 16:40:21 +0000292BuildIdSection::BuildIdSection()
Jake Ehrlich1128dc52017-10-30 22:08:11 +0000293 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000294 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000295
George Rimar6c2949d2017-03-20 16:40:21 +0000296void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyama79048e42017-10-27 03:59:34 +0000297 write32(Buf, 4); // Name size
298 write32(Buf + 4, HashSize); // Content size
299 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000300 memcpy(Buf + 12, "GNU", 4); // Name string
301 HashBuf = Buf + 16;
302}
303
Rui Ueyama35e00752016-11-10 00:12:28 +0000304// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000305static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
306 size_t ChunkSize) {
307 std::vector<ArrayRef<uint8_t>> Ret;
308 while (Arr.size() > ChunkSize) {
309 Ret.push_back(Arr.take_front(ChunkSize));
310 Arr = Arr.drop_front(ChunkSize);
311 }
312 if (!Arr.empty())
313 Ret.push_back(Arr);
314 return Ret;
315}
316
Rui Ueyama35e00752016-11-10 00:12:28 +0000317// Computes a hash value of Data using a given hash function.
318// In order to utilize multiple cores, we first split data into 1MB
319// chunks, compute a hash for each chunk, and then compute a hash value
320// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000321void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000322 llvm::ArrayRef<uint8_t> Data,
323 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000324 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000325 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000326
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000327 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000328 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000329 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
330 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000331
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000332 // Write to the final output buffer.
333 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000334}
335
Rui Ueyama732f4e22017-10-04 00:21:17 +0000336BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
337 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Peter Collingbourne6c55a702017-11-06 04:33:58 +0000338 this->Bss = true;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000339 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000340 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000341 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000342}
Peter Smithebfe9942017-02-09 10:27:57 +0000343
George Rimar6c2949d2017-03-20 16:40:21 +0000344void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000345 switch (Config->BuildId) {
346 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000347 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000348 write64le(Dest, xxHash64(toStringRef(Arr)));
349 });
350 break;
351 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000352 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000353 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000354 });
355 break;
356 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000357 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000358 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000359 });
360 break;
361 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000362 if (auto EC = getRandomBytes(HashBuf, HashSize))
363 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000364 break;
365 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000366 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000367 break;
368 default:
369 llvm_unreachable("unknown BuildIdKind");
370 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000371}
372
Rui Ueyama572247f2017-10-27 03:13:39 +0000373EhFrameSection::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000374 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000375
376// Search for an existing CIE record or create a new one.
377// CIE records from input object files are uniquified by their contents
378// and where their relocations point to.
Rui Ueyama572247f2017-10-27 03:13:39 +0000379template <class ELFT, class RelTy>
380CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000381 auto *Sec = cast<EhInputSection>(Cie.Sec);
Fangrui Song0c483022018-03-09 18:03:22 +0000382 if (read32(Cie.data().data() + 4) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000383 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
384
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000385 Symbol *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000386 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000387 if (FirstRelI != (unsigned)-1)
388 Personality =
389 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
390
391 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000392 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000393
394 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000395 if (!Rec) {
396 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000397 Rec->Cie = &Cie;
398 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000399 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000400 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000401}
402
403// There is one FDE per function. Returns true if a given FDE
404// points to a live function.
Rui Ueyama572247f2017-10-27 03:13:39 +0000405template <class ELFT, class RelTy>
406bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000407 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000408 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000409
410 // An FDE should point to some function because FDEs are to describe
411 // functions. That's however not always the case due to an issue of
412 // ld.gold with -r. ld.gold may discard only functions and leave their
413 // corresponding FDEs, which results in creating bad .eh_frame sections.
414 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000415 if (FirstRelI == (unsigned)-1)
416 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000417
Rafael Espindola66b4e212017-02-23 22:06:28 +0000418 const RelTy &Rel = Rels[FirstRelI];
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000419 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000420
421 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +0000422 if (auto *D = dyn_cast<Defined>(&B))
Rafael Espindola13dbf942017-12-13 17:36:53 +0000423 if (SectionBase *Sec = D->Section)
424 return Sec->Live;
Rui Ueyama27a357c2017-09-18 19:15:54 +0000425 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000426}
427
428// .eh_frame is a sequence of CIE or FDE records. In general, there
429// is one CIE record per input object file which is followed by
430// a list of FDEs. This function searches an existing CIE or create a new
431// one and associates FDEs to the CIE.
Rui Ueyama572247f2017-10-27 03:13:39 +0000432template <class ELFT, class RelTy>
433void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000434 DenseMap<size_t, CieRecord *> OffsetToCie;
435 for (EhSectionPiece &Piece : Sec->Pieces) {
436 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000437 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000438 return;
439
440 size_t Offset = Piece.InputOff;
Fangrui Song0c483022018-03-09 18:03:22 +0000441 uint32_t ID = read32(Piece.data().data() + 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000442 if (ID == 0) {
Rui Ueyama572247f2017-10-27 03:13:39 +0000443 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000444 continue;
445 }
446
447 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000448 CieRecord *Rec = OffsetToCie[CieOffset];
449 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000450 fatal(toString(Sec) + ": invalid CIE reference");
451
Rui Ueyama572247f2017-10-27 03:13:39 +0000452 if (!isFdeLive<ELFT>(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000453 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000454 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000455 NumFdes++;
456 }
457}
458
Rui Ueyama572247f2017-10-27 03:13:39 +0000459template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000460 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000461 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000462
463 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000464 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000465
Petr Hosek7b793212017-03-10 20:00:42 +0000466 for (auto *DS : Sec->DependentSections)
467 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000468
469 // .eh_frame is a sequence of CIE or FDE records. This function
470 // splits it into pieces so that we can call
471 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000472 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000473 if (Sec->Pieces.empty())
474 return;
475
Rui Ueyamabfa84322017-10-26 22:30:25 +0000476 if (Sec->AreRelocsRela)
Rui Ueyama572247f2017-10-27 03:13:39 +0000477 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
Rui Ueyamafaa38022017-09-19 20:28:03 +0000478 else
Rui Ueyama572247f2017-10-27 03:13:39 +0000479 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000480}
481
Rafael Espindola66b4e212017-02-23 22:06:28 +0000482static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
483 memcpy(Buf, D.data(), D.size());
484
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000485 size_t Aligned = alignTo(D.size(), Config->Wordsize);
Andrew Ng6dee7362017-09-07 08:43:56 +0000486
487 // Zero-clear trailing padding if it exists.
488 memset(Buf + D.size(), 0, Aligned - D.size());
489
Rafael Espindola66b4e212017-02-23 22:06:28 +0000490 // Fix the size field. -4 since size does not include the size field itself.
Rui Ueyama79048e42017-10-27 03:59:34 +0000491 write32(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000492}
493
Rui Ueyama572247f2017-10-27 03:13:39 +0000494void EhFrameSection::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000495 if (this->Size)
496 return; // Already finalized.
497
498 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000499 for (CieRecord *Rec : CieRecords) {
500 Rec->Cie->OutputOff = Off;
501 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000502
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000503 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000504 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000505 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000506 }
507 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000508
509 // The LSB standard does not allow a .eh_frame section with zero
510 // Call Frame Information records. Therefore add a CIE record length
511 // 0 as a terminator if this .eh_frame section is empty.
512 if (Off == 0)
513 Off = 4;
514
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000515 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000516}
517
Rui Ueyamac0552252017-10-27 03:13:24 +0000518// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
519// to get an FDE from an address to which FDE is applied. This function
520// returns a list of such pairs.
Rui Ueyama572247f2017-10-27 03:13:39 +0000521std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
Rui Ueyamac0552252017-10-27 03:13:24 +0000522 uint8_t *Buf = getParent()->Loc + OutSecOff;
523 std::vector<FdeData> Ret;
524
525 for (CieRecord *Rec : CieRecords) {
Rui Ueyama86297522017-10-27 03:14:09 +0000526 uint8_t Enc = getFdeEncoding(Rec->Cie);
Rui Ueyamac0552252017-10-27 03:13:24 +0000527 for (EhSectionPiece *Fde : Rec->Fdes) {
528 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
529 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
530 Ret.push_back({Pc, FdeVA});
531 }
532 }
533 return Ret;
534}
535
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000536static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000537 switch (Size) {
538 case DW_EH_PE_udata2:
Fangrui Song0c483022018-03-09 18:03:22 +0000539 return read16(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000540 case DW_EH_PE_udata4:
Fangrui Song0c483022018-03-09 18:03:22 +0000541 return read32(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000542 case DW_EH_PE_udata8:
Fangrui Song0c483022018-03-09 18:03:22 +0000543 return read64(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000544 case DW_EH_PE_absptr:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000545 return readUint(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000546 }
547 fatal("unknown FDE size encoding");
548}
549
550// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
551// We need it to create .eh_frame_hdr section.
Rui Ueyama572247f2017-10-27 03:13:39 +0000552uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
553 uint8_t Enc) const {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000554 // The starting address to which this FDE applies is
555 // stored at FDE + 8 byte.
556 size_t Off = FdeOff + 8;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000557 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000558 if ((Enc & 0x70) == DW_EH_PE_absptr)
559 return Addr;
560 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000561 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000562 fatal("unknown FDE size relative encoding");
563}
564
Rui Ueyama572247f2017-10-27 03:13:39 +0000565void EhFrameSection::writeTo(uint8_t *Buf) {
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000566 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000567 for (CieRecord *Rec : CieRecords) {
568 size_t CieOffset = Rec->Cie->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000569 writeCieFde(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000570
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000571 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000572 size_t Off = Fde->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000573 writeCieFde(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000574
575 // FDE's second word should have the offset to an associated CIE.
576 // Write it.
Rui Ueyama79048e42017-10-27 03:59:34 +0000577 write32(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000578 }
579 }
580
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000581 // Apply relocations. .eh_frame section contents are not contiguous
582 // in the output buffer, but relocateAlloc() still works because
583 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000584 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000585 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000586}
587
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000588GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000589 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
590 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000591
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000592void GotSection::addEntry(Symbol &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000593 Sym.GotIndex = NumEntries;
594 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000595}
596
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000597bool GotSection::addDynTlsEntry(Symbol &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000598 if (Sym.GlobalDynIndex != -1U)
599 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000600 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000601 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000602 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000603 return true;
604}
605
606// Reserves TLS entries for a TLS module ID and a TLS block offset.
607// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000608bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000609 if (TlsIndexOff != uint32_t(-1))
610 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000611 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000612 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000613 return true;
614}
615
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000616uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000617 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000618}
619
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000620uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000621 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000622}
623
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000624void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000625
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000626bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000627 // We need to emit a GOT even if it's empty if there's a relocation that is
628 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
Peter Smith18aa0be2018-03-11 20:58:18 +0000629 // (i.e. _GLOBAL_OFFSET_TABLE_) that the target defines relative to the .got.
630 return NumEntries == 0 && !HasGotOffRel &&
631 !(ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt);
George Rimar11992c862016-11-25 08:05:41 +0000632}
633
Igor Kudrin202a9f62017-07-14 08:10:45 +0000634void GotSection::writeTo(uint8_t *Buf) {
635 // Buf points to the start of this section's buffer,
636 // whereas InputSectionBase::relocateAlloc() expects its argument
637 // to point to the start of the output section.
638 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
639}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640
George Rimar14534eb2017-03-20 16:44:28 +0000641MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000642 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
643 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000644
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000645void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000646 // For "true" local symbols which can be referenced from the same module
647 // only compiler creates two instructions for address loading:
648 //
649 // lw $8, 0($gp) # R_MIPS_GOT16
650 // addi $8, $8, 0 # R_MIPS_LO16
651 //
652 // The first instruction loads high 16 bits of the symbol address while
653 // the second adds an offset. That allows to reduce number of required
654 // GOT entries because only one global offset table entry is necessary
655 // for every 64 KBytes of local data. So for local symbols we need to
656 // allocate number of GOT entries to hold all required "page" addresses.
657 //
658 // All global symbols (hidden and regular) considered by compiler uniformly.
659 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
660 // to load address of the symbol. So for each such symbol we need to
661 // allocate dedicated GOT entry to store its address.
662 //
663 // If a symbol is preemptible we need help of dynamic linker to get its
664 // final address. The corresponding GOT entries are allocated in the
665 // "global" part of GOT. Entries for non preemptible global symbol allocated
666 // in the "local" part of GOT.
667 //
668 // See "Global Offset Table" in Chapter 5:
669 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
670 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
671 // At this point we do not know final symbol value so to reduce number
672 // of allocated GOT entries do the following trick. Save all output
673 // sections referenced by GOT relocations. Then later in the `finalize`
674 // method calculate number of "pages" required to cover all saved output
675 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000676 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000677 return;
678 }
679 if (Sym.isTls()) {
680 // GOT entries created for MIPS TLS relocations behave like
681 // almost GOT entries from other ABIs. They go to the end
682 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000683 Sym.GotIndex = TlsEntries.size();
684 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000685 return;
686 }
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000687 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000688 if (S.isInGot() && !A)
689 return;
690 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000691 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000692 return;
693 Items.emplace_back(&S, A);
694 if (!A)
695 S.GotIndex = NewIndex;
696 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000697 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000698 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000699 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000700 Sym.IsInGlobalMipsGot = true;
701 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000702 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000703 Sym.Is32BitMipsGot = true;
704 } else {
705 // Hold local GOT entries accessed via a 16-bit index separately.
706 // That allows to write them in the beginning of the GOT and keep
707 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000708 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000709 }
710}
711
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000712bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000713 if (Sym.GlobalDynIndex != -1U)
714 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000715 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000716 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000717 TlsEntries.push_back(nullptr);
718 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000719 return true;
720}
721
722// Reserves TLS entries for a TLS module ID and a TLS block offset.
723// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000724bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000725 if (TlsIndexOff != uint32_t(-1))
726 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000727 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000728 TlsEntries.push_back(nullptr);
729 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000730 return true;
731}
732
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000733static uint64_t getMipsPageAddr(uint64_t Addr) {
734 return (Addr + 0x8000) & ~0xffff;
735}
736
737static uint64_t getMipsPageCount(uint64_t Size) {
738 return (Size + 0xfffe) / 0xffff + 1;
739}
740
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000741uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
George Rimar14534eb2017-03-20 16:44:28 +0000742 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000743 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000744 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
745 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
746 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000747 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000748 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000749}
750
Rui Ueyama48882242017-11-04 00:31:04 +0000751uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
752 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000753 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000754 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000755 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000756 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000757 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000758 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000759 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000760 Index += LocalEntries.size();
761 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000762 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000763 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000764 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000765 auto It = EntryIndexMap.find({&B, Addend});
766 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000767 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000768 }
George Rimar14534eb2017-03-20 16:44:28 +0000769 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000770}
771
George Rimar14534eb2017-03-20 16:44:28 +0000772uint64_t MipsGotSection::getTlsOffset() const {
773 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000774}
775
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000776uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
George Rimar14534eb2017-03-20 16:44:28 +0000777 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000778}
779
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000780const Symbol *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000781 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000782}
783
George Rimar14534eb2017-03-20 16:44:28 +0000784unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000785 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
786 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000787}
788
George Rimar67c60722017-07-18 11:55:35 +0000789void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000790
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000791bool MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000792 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000793 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000794 // For each output section referenced by GOT page relocations calculate
795 // and save into PageIndexMap an upper bound of MIPS GOT entries required
796 // to store page addresses of local symbols. We assume the worst case -
797 // each 64kb page of the output section has at least one GOT relocation
798 // against it. And take in account the case when the section intersects
799 // page boundaries.
800 P.second = PageEntriesNum;
801 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000802 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000803 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000804 Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000805 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000806}
807
George Rimar14534eb2017-03-20 16:44:28 +0000808bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000809 // We add the .got section to the result for dynamic MIPS target because
810 // its address and properties are mentioned in the .dynamic section.
811 return Config->Relocatable;
812}
813
George Rimar67c60722017-07-18 11:55:35 +0000814uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000815
George Rimar14534eb2017-03-20 16:44:28 +0000816void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000817 // Set the MSB of the second GOT slot. This is not required by any
818 // MIPS ABI documentation, though.
819 //
820 // There is a comment in glibc saying that "The MSB of got[1] of a
821 // gnu object is set to identify gnu objects," and in GNU gold it
822 // says "the second entry will be used by some runtime loaders".
823 // But how this field is being used is unclear.
824 //
825 // We are not really willing to mimic other linkers behaviors
826 // without understanding why they do that, but because all files
827 // generated by GNU tools have this special GOT value, and because
828 // we've been doing this for years, it is probably a safe bet to
829 // keep doing this for now. We really need to revisit this to see
830 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000831 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
832 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000833 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000834 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000835 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000836 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000837 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000838 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
839 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000840 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000841 }
George Rimar14534eb2017-03-20 16:44:28 +0000842 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000843 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000844 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000845 Buf += Config->Wordsize;
Rui Ueyama48882242017-11-04 00:31:04 +0000846 const Symbol *Sym = SA.first;
847 uint64_t VA = Sym->getVA(SA.second);
Simon Atanasyan5a4e2132017-11-08 23:34:34 +0000848 if (Sym->StOther & STO_MIPS_MICROMIPS)
849 VA |= 1;
George Rimar14534eb2017-03-20 16:44:28 +0000850 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000851 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000852 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
853 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
854 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000855 // Initialize TLS-related GOT entries. If the entry has a corresponding
856 // dynamic relocations, leave it initialized by zero. Write down adjusted
857 // TLS symbol's values otherwise. To calculate the adjustments use offsets
858 // for thread-local storage.
859 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000860 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000861 writeUint(Buf + TlsIndexOff, 1);
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000862 for (const Symbol *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000863 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000864 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000865 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000866 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000867 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
868 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000869 }
870 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000871 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
872 writeUint(Entry, 1);
873 Entry += Config->Wordsize;
874 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000875 }
876 }
877}
878
George Rimar10f74fc2017-03-15 09:12:56 +0000879GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000880 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
881 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000882
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000883void GotPltSection::addEntry(Symbol &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000884 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
885 Entries.push_back(&Sym);
886}
887
George Rimar10f74fc2017-03-15 09:12:56 +0000888size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000889 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
890 Target->GotPltEntrySize;
891}
892
George Rimar10f74fc2017-03-15 09:12:56 +0000893void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000894 Target->writeGotPltHeader(Buf);
895 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000896 for (const Symbol *B : Entries) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000897 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000898 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000899 }
900}
901
Peter Smith18aa0be2018-03-11 20:58:18 +0000902bool GotPltSection::empty() const {
903 // We need to emit a GOT.PLT even if it's empty if there's a symbol that
904 // references the _GLOBAL_OFFSET_TABLE_ and the Target defines the symbol
905 // relative to the .got.plt section.
906 return Entries.empty() &&
907 !(ElfSym::GlobalOffsetTable && Target->GotBaseSymInGotPlt);
908}
909
Peter Smithbaffdb82016-12-08 12:58:55 +0000910// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
911// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000912IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000913 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
914 Target->GotPltEntrySize,
915 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000916
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000917void IgotPltSection::addEntry(Symbol &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000918 Sym.IsInIgot = true;
919 Sym.GotPltIndex = Entries.size();
920 Entries.push_back(&Sym);
921}
922
George Rimar10f74fc2017-03-15 09:12:56 +0000923size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000924 return Entries.size() * Target->GotPltEntrySize;
925}
926
George Rimar10f74fc2017-03-15 09:12:56 +0000927void IgotPltSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000928 for (const Symbol *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000929 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000930 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000931 }
932}
933
George Rimar49648002017-03-15 09:32:36 +0000934StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
935 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000936 Dynamic(Dynamic) {
937 // ELF string tables start with a NUL byte.
938 addString("");
939}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000940
941// Adds a string to the string table. If HashIt is true we hash and check for
942// duplicates. It is optional because the name of global symbols are already
943// uniqued and hashing them again has a big cost for a small value: uniquing
944// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000945unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000946 if (HashIt) {
947 auto R = StringMap.insert(std::make_pair(S, this->Size));
948 if (!R.second)
949 return R.first->second;
950 }
951 unsigned Ret = this->Size;
952 this->Size = this->Size + S.size() + 1;
953 Strings.push_back(S);
954 return Ret;
955}
956
George Rimar49648002017-03-15 09:32:36 +0000957void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000958 for (StringRef S : Strings) {
959 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000960 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000961 Buf += S.size() + 1;
962 }
963}
964
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000965// Returns the number of version definition entries. Because the first entry
966// is for the version definition itself, it is the number of versioned symbols
967// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000968static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
969
970template <class ELFT>
971DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000972 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +0000973 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000974 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +0000975
Petr Hosekffa786f2017-05-26 19:12:38 +0000976 // .dynamic section is not writable on MIPS and on Fuchsia OS
977 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000978 // See "Special Section" in Chapter 4 in the following document:
979 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +0000980 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +0000981 this->Flags = SHF_ALLOC;
982
Rui Ueyama22e55512017-12-15 19:39:59 +0000983 // Add strings to .dynstr early so that .dynstr's size will be
984 // fixed early.
985 for (StringRef S : Config->FilterList)
986 addInt(DT_FILTER, InX::DynStrTab->addString(S));
987 for (StringRef S : Config->AuxiliaryList)
988 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
989
990 if (!Config->Rpath.empty())
991 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
992 InX::DynStrTab->addString(Config->Rpath));
993
994 for (InputFile *File : SharedFiles) {
995 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
996 if (F->IsNeeded)
997 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
998 }
999 if (!Config->SoName.empty())
1000 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001001}
1002
Rui Ueyama15475e92017-11-24 02:15:51 +00001003template <class ELFT>
1004void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1005 Entries.push_back({Tag, Fn});
1006}
1007
1008template <class ELFT>
1009void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1010 Entries.push_back({Tag, [=] { return Val; }});
1011}
1012
1013template <class ELFT>
1014void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1015 Entries.push_back(
1016 {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1017}
1018
1019template <class ELFT>
1020void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1021 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1022}
1023
1024template <class ELFT>
1025void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1026 Entries.push_back({Tag, [=] { return Sec->Size; }});
1027}
1028
1029template <class ELFT>
1030void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1031 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1032}
1033
Rui Ueyama22e55512017-12-15 19:39:59 +00001034// Add remaining entries to complete .dynamic contents.
1035template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1036 if (this->Size)
1037 return; // Already finalized.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001038
1039 // Set DT_FLAGS and DT_FLAGS_1.
1040 uint32_t DtFlags = 0;
1041 uint32_t DtFlags1 = 0;
1042 if (Config->Bsymbolic)
1043 DtFlags |= DF_SYMBOLIC;
1044 if (Config->ZNodelete)
1045 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001046 if (Config->ZNodlopen)
1047 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001048 if (Config->ZNow) {
1049 DtFlags |= DF_BIND_NOW;
1050 DtFlags1 |= DF_1_NOW;
1051 }
1052 if (Config->ZOrigin) {
1053 DtFlags |= DF_ORIGIN;
1054 DtFlags1 |= DF_1_ORIGIN;
1055 }
Rui Ueyama7c18abf2018-03-01 22:56:52 +00001056 if (!Config->ZText)
1057 DtFlags |= DF_TEXTREL;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001058
1059 if (DtFlags)
Rui Ueyama15475e92017-11-24 02:15:51 +00001060 addInt(DT_FLAGS, DtFlags);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001061 if (DtFlags1)
Rui Ueyama15475e92017-11-24 02:15:51 +00001062 addInt(DT_FLAGS_1, DtFlags1);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001063
Petr Hosekffa786f2017-05-26 19:12:38 +00001064 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1065 // need it for each process, so we don't write it for DSOs. The loader writes
1066 // the pointer into this entry.
1067 //
1068 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1069 // systems (currently only Fuchsia OS) provide other means to give the
1070 // debugger this information. Such systems may choose make .dynamic read-only.
1071 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1072 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
Rui Ueyama15475e92017-11-24 02:15:51 +00001073 addInt(DT_DEBUG, 0);
George Rimarb4081bb2017-05-12 08:04:58 +00001074
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001075 this->Link = InX::DynStrTab->getParent()->SectionIndex;
George Rimar32085882017-12-30 08:40:45 +00001076 if (!InX::RelaDyn->empty()) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001077 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1078 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001079
1080 bool IsRela = Config->IsRela;
Rui Ueyama15475e92017-11-24 02:15:51 +00001081 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1082 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001083
1084 // MIPS dynamic loader does not support RELCOUNT tag.
1085 // The problem is in the tight relation between dynamic
1086 // relocations and GOT. So do not emit this tag on MIPS.
1087 if (Config->EMachine != EM_MIPS) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001088 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001089 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama15475e92017-11-24 02:15:51 +00001090 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001091 }
1092 }
George Rimaredb61162017-12-31 07:42:54 +00001093 // .rel[a].plt section usually consists of two parts, containing plt and
1094 // iplt relocations. It is possible to have only iplt relocations in the
1095 // output. In that case RelaPlt is empty and have zero offset, the same offset
1096 // as RelaIplt have. And we still want to emit proper dynamic tags for that
1097 // case, so here we always use RelaPlt as marker for the begining of
1098 // .rel[a].plt section.
1099 if (InX::RelaPlt->getParent()->Live) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001100 addInSec(DT_JMPREL, InX::RelaPlt);
1101 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
Rui Ueyama0cc14832017-06-28 17:05:39 +00001102 switch (Config->EMachine) {
1103 case EM_MIPS:
Rui Ueyama15475e92017-11-24 02:15:51 +00001104 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001105 break;
1106 case EM_SPARCV9:
Rui Ueyama15475e92017-11-24 02:15:51 +00001107 addInSec(DT_PLTGOT, InX::Plt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001108 break;
1109 default:
Rui Ueyama15475e92017-11-24 02:15:51 +00001110 addInSec(DT_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001111 break;
1112 }
Rui Ueyama15475e92017-11-24 02:15:51 +00001113 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001114 }
1115
Rui Ueyama15475e92017-11-24 02:15:51 +00001116 addInSec(DT_SYMTAB, InX::DynSymTab);
1117 addInt(DT_SYMENT, sizeof(Elf_Sym));
1118 addInSec(DT_STRTAB, InX::DynStrTab);
1119 addInt(DT_STRSZ, InX::DynStrTab->getSize());
George Rimar0a7412f2017-03-09 08:48:34 +00001120 if (!Config->ZText)
Rui Ueyama15475e92017-11-24 02:15:51 +00001121 addInt(DT_TEXTREL, 0);
George Rimar69b17c32017-05-16 10:04:42 +00001122 if (InX::GnuHashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001123 addInSec(DT_GNU_HASH, InX::GnuHashTab);
George Rimaraaf54712017-09-27 09:14:59 +00001124 if (InX::HashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001125 addInSec(DT_HASH, InX::HashTab);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001126
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001127 if (Out::PreinitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001128 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1129 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001130 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001131 if (Out::InitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001132 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1133 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001134 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001135 if (Out::FiniArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001136 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1137 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001138 }
1139
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001140 if (Symbol *B = Symtab->find(Config->Init))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001141 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001142 addSym(DT_INIT, B);
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001143 if (Symbol *B = Symtab->find(Config->Fini))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001144 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001145 addSym(DT_FINI, B);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001146
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001147 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1148 if (HasVerNeed || In<ELFT>::VerDef)
Rui Ueyama15475e92017-11-24 02:15:51 +00001149 addInSec(DT_VERSYM, In<ELFT>::VerSym);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001150 if (In<ELFT>::VerDef) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001151 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1152 addInt(DT_VERDEFNUM, getVerDefNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001153 }
1154 if (HasVerNeed) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001155 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1156 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001157 }
1158
1159 if (Config->EMachine == EM_MIPS) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001160 addInt(DT_MIPS_RLD_VERSION, 1);
1161 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1162 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1163 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
James Hendersonf70c5be2017-11-22 12:04:21 +00001164
Rui Ueyama15475e92017-11-24 02:15:51 +00001165 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
James Hendersonf70c5be2017-11-22 12:04:21 +00001166
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001167 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama15475e92017-11-24 02:15:51 +00001168 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001169 else
Rui Ueyama15475e92017-11-24 02:15:51 +00001170 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1171 addInSec(DT_PLTGOT, InX::MipsGot);
Rafael Espindola895aea62017-05-11 22:02:41 +00001172 if (InX::MipsRldMap)
Rui Ueyama15475e92017-11-24 02:15:51 +00001173 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001174 }
1175
Rui Ueyama15475e92017-11-24 02:15:51 +00001176 addInt(DT_NULL, 0);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001177
George Rimar8f3a6c82017-10-06 10:06:13 +00001178 getParent()->Link = this->Link;
1179 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001180}
1181
1182template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1183 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1184
Rui Ueyama15475e92017-11-24 02:15:51 +00001185 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1186 P->d_tag = KV.first;
1187 P->d_un.d_val = KV.second();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001188 ++P;
1189 }
1190}
1191
George Rimar97def8c2017-03-17 12:07:44 +00001192uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001193 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001194}
1195
Alexander Richardson048e2502018-02-19 11:00:15 +00001196int64_t DynamicReloc::computeAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001197 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001198 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001199 return Addend;
1200}
1201
George Rimar97def8c2017-03-17 12:07:44 +00001202uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001203 if (Sym && !UseSymVA)
1204 return Sym->DynsymIndex;
1205 return 0;
1206}
1207
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001208RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1209 int32_t DynamicTag,
1210 int32_t SizeDynamicTag)
1211 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1212 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001213
Rafael Espindolad49866e2018-02-13 16:06:11 +00001214void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
Rafael Espindola35cf8bb2018-02-13 16:03:52 +00001215 uint64_t OffsetInSec, Symbol *Sym) {
1216 addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1217}
1218
Rafael Espindolad49866e2018-02-13 16:06:11 +00001219void RelocationBaseSection::addReloc(RelType DynType,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001220 InputSectionBase *InputSec,
Rafael Espindolab9603252018-02-16 16:53:04 +00001221 uint64_t OffsetInSec, Symbol *Sym,
1222 int64_t Addend, RelExpr Expr,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001223 RelType Type) {
Alexander Richardsoncfb60932018-02-16 10:01:17 +00001224 // Write the addends to the relocated address if required. We skip
1225 // it if the written value would be zero.
Rafael Espindolab9603252018-02-16 16:53:04 +00001226 if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0))
Rafael Espindola73584cb2018-01-05 20:08:38 +00001227 InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
Rafael Espindolab9603252018-02-16 16:53:04 +00001228 addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
Rafael Espindola73584cb2018-01-05 20:08:38 +00001229}
1230
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001231void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001232 if (Reloc.Type == Target->RelativeRel)
1233 ++NumRelativeRelocs;
1234 Relocs.push_back(Reloc);
1235}
1236
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001237void RelocationBaseSection::finalizeContents() {
1238 // If all relocations are R_*_RELATIVE they don't refer to any
1239 // dynamic symbol and we don't need a dynamic symbol table. If that
1240 // is the case, just use 0 as the link.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001241 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001242
1243 // Set required output section properties.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001244 getParent()->Link = Link;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001245}
1246
1247template <class ELFT>
1248static void encodeDynamicReloc(typename ELFT::Rela *P,
1249 const DynamicReloc &Rel) {
1250 if (Config->IsRela)
Alexander Richardson048e2502018-02-19 11:00:15 +00001251 P->r_addend = Rel.computeAddend();
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001252 P->r_offset = Rel.getOffset();
1253 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1254 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1255 // entries. These entries are placed after the global and local sections of
1256 // the GOT. At the point when we create these relocations, the size of the
1257 // global and local sections is unknown, so the offset that we store in the
1258 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1259 // the GOT, rather than being relative to the start of the GOT. This line of
1260 // code adds the size of the global and local sections to the virtual
1261 // address computed by getOffset() in order to adjust it into the TLS
1262 // section.
1263 P->r_offset += InX::MipsGot->getTlsOffset();
1264 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1265}
1266
1267template <class ELFT>
1268RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1269 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1270 Config->IsRela ? DT_RELA : DT_REL,
1271 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1272 Sort(Sort) {
1273 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1274}
1275
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001276static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) {
1277 bool AIsRel = A.Type == Target->RelativeRel;
1278 bool BIsRel = B.Type == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001279 if (AIsRel != BIsRel)
1280 return AIsRel;
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001281 return A.getSymIndex() < B.getSymIndex();
Eugene Levianta96d9022016-11-16 10:02:27 +00001282}
1283
1284template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001285 if (Sort)
1286 std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1287
George Rimar97def8c2017-03-17 12:07:44 +00001288 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001289 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001290 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001291 }
Eugene Levianta96d9022016-11-16 10:02:27 +00001292}
1293
1294template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1295 return this->Entsize * Relocs.size();
1296}
1297
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001298template <class ELFT>
1299AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1300 StringRef Name)
1301 : RelocationBaseSection(
1302 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1303 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1304 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1305 this->Entsize = 1;
1306}
Eugene Levianta96d9022016-11-16 10:02:27 +00001307
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001308template <class ELFT>
1309bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1310 // This function computes the contents of an Android-format packed relocation
1311 // section.
1312 //
1313 // This format compresses relocations by using relocation groups to factor out
1314 // fields that are common between relocations and storing deltas from previous
1315 // relocations in SLEB128 format (which has a short representation for small
1316 // numbers). A good example of a relocation type with common fields is
1317 // R_*_RELATIVE, which is normally used to represent function pointers in
1318 // vtables. In the REL format, each relative relocation has the same r_info
1319 // field, and is only different from other relative relocations in terms of
1320 // the r_offset field. By sorting relocations by offset, grouping them by
1321 // r_info and representing each relocation with only the delta from the
1322 // previous offset, each 8-byte relocation can be compressed to as little as 1
1323 // byte (or less with run-length encoding). This relocation packer was able to
1324 // reduce the size of the relocation section in an Android Chromium DSO from
1325 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1326 //
1327 // A relocation section consists of a header containing the literal bytes
1328 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1329 // elements are the total number of relocations in the section and an initial
1330 // r_offset value. The remaining elements define a sequence of relocation
1331 // groups. Each relocation group starts with a header consisting of the
1332 // following elements:
1333 //
1334 // - the number of relocations in the relocation group
1335 // - flags for the relocation group
1336 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1337 // for each relocation in the group.
1338 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1339 // field for each relocation in the group.
1340 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1341 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1342 // each relocation in the group.
1343 //
1344 // Following the relocation group header are descriptions of each of the
1345 // relocations in the group. They consist of the following elements:
1346 //
1347 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1348 // delta for this relocation.
1349 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1350 // field for this relocation.
1351 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1352 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1353 // this relocation.
1354
1355 size_t OldSize = RelocData.size();
1356
1357 RelocData = {'A', 'P', 'S', '2'};
1358 raw_svector_ostream OS(RelocData);
Rui Ueyama04c821c2017-12-08 02:20:50 +00001359 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001360
1361 // The format header includes the number of relocations and the initial
1362 // offset (we set this to zero because the first relocation group will
1363 // perform the initial adjustment).
Rui Ueyama04c821c2017-12-08 02:20:50 +00001364 Add(Relocs.size());
1365 Add(0);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001366
1367 std::vector<Elf_Rela> Relatives, NonRelatives;
1368
1369 for (const DynamicReloc &Rel : Relocs) {
1370 Elf_Rela R;
1371 encodeDynamicReloc<ELFT>(&R, Rel);
1372
1373 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1374 Relatives.push_back(R);
1375 else
1376 NonRelatives.push_back(R);
1377 }
1378
1379 std::sort(Relatives.begin(), Relatives.end(),
1380 [](const Elf_Rel &A, const Elf_Rel &B) {
1381 return A.r_offset < B.r_offset;
1382 });
1383
1384 // Try to find groups of relative relocations which are spaced one word
1385 // apart from one another. These generally correspond to vtable entries. The
1386 // format allows these groups to be encoded using a sort of run-length
1387 // encoding, but each group will cost 7 bytes in addition to the offset from
1388 // the previous group, so it is only profitable to do this for groups of
1389 // size 8 or larger.
1390 std::vector<Elf_Rela> UngroupedRelatives;
1391 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1392 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1393 std::vector<Elf_Rela> Group;
1394 do {
1395 Group.push_back(*I++);
1396 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1397
1398 if (Group.size() < 8)
1399 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1400 Group.end());
1401 else
1402 RelativeGroups.emplace_back(std::move(Group));
1403 }
1404
1405 unsigned HasAddendIfRela =
1406 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1407
1408 uint64_t Offset = 0;
1409 uint64_t Addend = 0;
1410
1411 // Emit the run-length encoding for the groups of adjacent relative
1412 // relocations. Each group is represented using two groups in the packed
1413 // format. The first is used to set the current offset to the start of the
1414 // group (and also encodes the first relocation), and the second encodes the
1415 // remaining relocations.
1416 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1417 // The first relocation in the group.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001418 Add(1);
1419 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1420 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1421 Add(G[0].r_offset - Offset);
1422 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001423 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001424 Add(G[0].r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001425 Addend = G[0].r_addend;
1426 }
1427
1428 // The remaining relocations.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001429 Add(G.size() - 1);
1430 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1431 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1432 Add(Config->Wordsize);
1433 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001434 if (Config->IsRela) {
1435 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001436 Add(I->r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001437 Addend = I->r_addend;
1438 }
1439 }
1440
1441 Offset = G.back().r_offset;
1442 }
1443
1444 // Now the ungrouped relatives.
1445 if (!UngroupedRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001446 Add(UngroupedRelatives.size());
1447 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1448 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001449 for (Elf_Rela &R : UngroupedRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001450 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001451 Offset = R.r_offset;
1452 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001453 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001454 Addend = R.r_addend;
1455 }
1456 }
1457 }
1458
1459 // Finally the non-relative relocations.
1460 std::sort(NonRelatives.begin(), NonRelatives.end(),
1461 [](const Elf_Rela &A, const Elf_Rela &B) {
1462 return A.r_offset < B.r_offset;
1463 });
1464 if (!NonRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001465 Add(NonRelatives.size());
1466 Add(HasAddendIfRela);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001467 for (Elf_Rela &R : NonRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001468 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001469 Offset = R.r_offset;
Rui Ueyama04c821c2017-12-08 02:20:50 +00001470 Add(R.r_info);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001471 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001472 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001473 Addend = R.r_addend;
1474 }
1475 }
1476 }
1477
1478 // Returns whether the section size changed. We need to keep recomputing both
1479 // section layout and the contents of this section until the size converges
1480 // because changing this section's size can affect section layout, which in
1481 // turn can affect the sizes of the LEB-encoded integers stored in this
1482 // section.
1483 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001484}
1485
George Rimarf45f6812017-05-16 08:53:30 +00001486SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001487 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001488 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001489 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001490 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001491 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001492
1493// Orders symbols according to their positions in the GOT,
1494// in compliance with MIPS ABI rules.
1495// See "Global Offset Table" in Chapter 5 in the following document
1496// for detailed description:
1497// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001498static bool sortMipsSymbols(const SymbolTableEntry &L,
1499 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001500 // Sort entries related to non-local preemptible symbols by GOT indexes.
1501 // All other entries go to the first part of GOT in arbitrary order.
Zachary Turnera104d552017-11-03 22:33:49 +00001502 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1503 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001504 if (LIsInLocalGot || RIsInLocalGot)
1505 return !RIsInLocalGot;
Zachary Turnera104d552017-11-03 22:33:49 +00001506 return L.Sym->GotIndex < R.Sym->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001507}
1508
George Rimarf45f6812017-05-16 08:53:30 +00001509void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001510 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001511
Rui Ueyama6e967342017-02-28 03:29:12 +00001512 // If it is a .dynsym, there should be no local symbols, but we need
1513 // to do a few things for the dynamic linker.
1514 if (this->Type == SHT_DYNSYM) {
1515 // Section's Info field has the index of the first non-local symbol.
1516 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001517 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001518
George Rimarf45f6812017-05-16 08:53:30 +00001519 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001520 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001521 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001522 } else if (Config->EMachine == EM_MIPS) {
1523 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1524 }
1525
1526 size_t I = 0;
Zachary Turnera104d552017-11-03 22:33:49 +00001527 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001528 return;
Peter Smith55865432017-02-20 11:12:33 +00001529 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001530}
Peter Smith55865432017-02-20 11:12:33 +00001531
George Rimar0d6f30e2017-10-18 13:06:18 +00001532// The ELF spec requires that all local symbols precede global symbols, so we
1533// sort symbol entries in this function. (For .dynsym, we don't do that because
1534// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001535void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001536 if (this->Type == SHT_DYNSYM)
1537 return;
1538 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001539 auto It = std::stable_partition(
1540 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
Zachary Turnera104d552017-11-03 22:33:49 +00001541 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
Rui Ueyama6e967342017-02-28 03:29:12 +00001542 });
1543 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001544 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001545}
1546
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001547void SymbolTableBaseSection::addSymbol(Symbol *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001548 // Adding a local symbol to a .dynsym is a bug.
1549 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001550
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001551 bool HashIt = B->isLocal();
1552 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001553}
1554
Rui Ueyama48882242017-11-04 00:31:04 +00001555size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
George Rimar5d6efd12017-09-27 09:08:53 +00001556 // Initializes symbol lookup tables lazily. This is used only
1557 // for -r or -emit-relocs.
1558 llvm::call_once(OnceFlag, [&] {
1559 SymbolIndexMap.reserve(Symbols.size());
1560 size_t I = 0;
1561 for (const SymbolTableEntry &E : Symbols) {
Zachary Turnera104d552017-11-03 22:33:49 +00001562 if (E.Sym->Type == STT_SECTION)
1563 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001564 else
Zachary Turnera104d552017-11-03 22:33:49 +00001565 SymbolIndexMap[E.Sym] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001566 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001567 });
George Rimar5d6efd12017-09-27 09:08:53 +00001568
1569 // Section symbols are mapped based on their output sections
1570 // to maintain their semantics.
Rui Ueyama48882242017-11-04 00:31:04 +00001571 if (Sym->Type == STT_SECTION)
1572 return SectionIndexMap.lookup(Sym->getOutputSection());
1573 return SymbolIndexMap.lookup(Sym);
George Rimar190bac52017-01-23 14:07:23 +00001574}
1575
George Rimarf45f6812017-05-16 08:53:30 +00001576template <class ELFT>
1577SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1578 : SymbolTableBaseSection(StrTabSec) {
1579 this->Entsize = sizeof(Elf_Sym);
1580}
1581
Rui Ueyama1f032532017-02-28 01:56:36 +00001582// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001583template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001584 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001585 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001586 Buf += sizeof(Elf_Sym);
1587
Eugene Leviant9230db92016-11-17 09:16:34 +00001588 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001589
Rui Ueyama1f032532017-02-28 01:56:36 +00001590 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001591 Symbol *Sym = Ent.Sym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001592
Rui Ueyama1b003182017-02-28 19:22:09 +00001593 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001594 ESym->st_other = 0;
Rui Ueyama48882242017-11-04 00:31:04 +00001595 if (Sym->isLocal()) {
1596 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
Rui Ueyama1f032532017-02-28 01:56:36 +00001597 } else {
Rui Ueyama48882242017-11-04 00:31:04 +00001598 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1599 ESym->setVisibility(Sym->Visibility);
Rui Ueyama1f032532017-02-28 01:56:36 +00001600 }
1601
1602 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001603
Rui Ueyama1b003182017-02-28 19:22:09 +00001604 // Set a section index.
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001605 BssSection *CommonSec = nullptr;
1606 if (!Config->DefineCommon)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001607 if (auto *D = dyn_cast<Defined>(Sym))
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001608 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1609 if (CommonSec)
1610 ESym->st_shndx = SHN_COMMON;
1611 else if (const OutputSection *OutSec = Sym->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001612 ESym->st_shndx = OutSec->SectionIndex;
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001613 else if (isa<Defined>(Sym))
Eugene Leviant9230db92016-11-17 09:16:34 +00001614 ESym->st_shndx = SHN_ABS;
George Rimar2727ce22017-10-06 09:56:24 +00001615 else
1616 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001617
George Rimardbe843d2017-06-28 09:51:33 +00001618 // Copy symbol size if it is a defined symbol. st_size is not significant
1619 // for undefined symbols, so whether copying it or not is up to us if that's
1620 // the case. We'll leave it as zero because by not setting a value, we can
1621 // get the exact same outputs for two sets of input files that differ only
1622 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001623 if (ESym->st_shndx == SHN_UNDEF)
1624 ESym->st_size = 0;
1625 else
Rui Ueyama48882242017-11-04 00:31:04 +00001626 ESym->st_size = Sym->getSize();
George Rimardbe843d2017-06-28 09:51:33 +00001627
Rui Ueyama1b003182017-02-28 19:22:09 +00001628 // st_value is usually an address of a symbol, but that has a
1629 // special meaining for uninstantiated common symbols (this can
1630 // occur if -r is given).
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001631 if (CommonSec)
1632 ESym->st_value = CommonSec->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001633 else
Rui Ueyama48882242017-11-04 00:31:04 +00001634 ESym->st_value = Sym->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001635
Rui Ueyama1f032532017-02-28 01:56:36 +00001636 ++ESym;
1637 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001638
Rui Ueyama1f032532017-02-28 01:56:36 +00001639 // On MIPS we need to mark symbol which has a PLT entry and requires
1640 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1641 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1642 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1643 if (Config->EMachine == EM_MIPS) {
1644 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1645
1646 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001647 Symbol *Sym = Ent.Sym;
1648 if (Sym->isInPlt() && Sym->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001649 ESym->st_other |= STO_MIPS_PLT;
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001650 if (isMicroMips()) {
1651 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1652 // defined microMIPS symbols and shared symbols with PLT record.
1653 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1654 (Sym->isShared() && Sym->NeedsPltAddr)) {
1655 if (StrTabSec.isDynamic())
1656 ESym->st_value |= 1;
1657 ESym->st_other |= STO_MIPS_MICROMIPS;
1658 }
1659 }
Rui Ueyama1f032532017-02-28 01:56:36 +00001660 if (Config->Relocatable)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001661 if (auto *D = dyn_cast<Defined>(Sym))
Rui Ueyama7957b082017-11-07 00:04:22 +00001662 if (isMipsPIC<ELFT>(D))
Rui Ueyama1f032532017-02-28 01:56:36 +00001663 ESym->st_other |= STO_MIPS_PIC;
1664 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001665 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001666 }
1667}
1668
Rui Ueyamae4120632017-02-28 22:05:13 +00001669// .hash and .gnu.hash sections contain on-disk hash tables that map
1670// symbol names to their dynamic symbol table indices. Their purpose
1671// is to help the dynamic linker resolve symbols quickly. If ELF files
1672// don't have them, the dynamic linker has to do linear search on all
1673// dynamic symbols, which makes programs slower. Therefore, a .hash
1674// section is added to a DSO by default. A .gnu.hash is added if you
1675// give the -hash-style=gnu or -hash-style=both option.
1676//
1677// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1678// Each ELF file has a list of DSOs that the ELF file depends on and a
1679// list of dynamic symbols that need to be resolved from any of the
1680// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1681// where m is the number of DSOs and n is the number of dynamic
1682// symbols. For modern large programs, both m and n are large. So
1683// making each step faster by using hash tables substiantially
1684// improves time to load programs.
1685//
1686// (Note that this is not the only way to design the shared library.
1687// For instance, the Windows DLL takes a different approach. On
1688// Windows, each dynamic symbol has a name of DLL from which the symbol
1689// has to be resolved. That makes the cost of symbol resolution O(n).
1690// This disables some hacky techniques you can use on Unix such as
1691// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1692//
1693// Due to historical reasons, we have two different hash tables, .hash
1694// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1695// and better version of .hash. .hash is just an on-disk hash table, but
1696// .gnu.hash has a bloom filter in addition to a hash table to skip
1697// DSOs very quickly. If you are sure that your dynamic linker knows
1698// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1699// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001700GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001701 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1702}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001703
George Rimarf45f6812017-05-16 08:53:30 +00001704void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001705 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001706
Rui Ueyama517366c2018-01-19 23:54:31 +00001707 // Computes bloom filter size in word size. We want to allocate 12
Rui Ueyamae13373b2017-03-01 02:51:42 +00001708 // bits for each symbol. It must be a power of two.
Rui Ueyama517366c2018-01-19 23:54:31 +00001709 if (Symbols.empty()) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001710 MaskWords = 1;
Rui Ueyama517366c2018-01-19 23:54:31 +00001711 } else {
1712 uint64_t NumBits = Symbols.size() * 12;
1713 MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8));
1714 }
Rui Ueyamae13373b2017-03-01 02:51:42 +00001715
George Rimar5f73bc92017-03-29 15:23:28 +00001716 Size = 16; // Header
1717 Size += Config->Wordsize * MaskWords; // Bloom filter
1718 Size += NBuckets * 4; // Hash buckets
1719 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001720}
1721
George Rimarf45f6812017-05-16 08:53:30 +00001722void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamac4e50bf2017-12-06 00:49:48 +00001723 // The output buffer is not guaranteed to be zero-cleared because we pre-
1724 // fill executable sections with trap instructions. This is a precaution
1725 // for that case, which happens only when -no-rosegment is given.
1726 memset(Buf, 0, Size);
1727
Rui Ueyamae13373b2017-03-01 02:51:42 +00001728 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001729 write32(Buf, NBuckets);
1730 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1731 write32(Buf + 8, MaskWords);
1732 write32(Buf + 12, getShift2());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001733 Buf += 16;
1734
Rui Ueyama7986b452017-03-01 18:09:09 +00001735 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001736 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001737 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001738 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001739}
1740
Rui Ueyama7986b452017-03-01 18:09:09 +00001741// This function writes a 2-bit bloom filter. This bloom filter alone
1742// usually filters out 80% or more of all symbol lookups [1].
1743// The dynamic linker uses the hash table only when a symbol is not
1744// filtered out by a bloom filter.
1745//
1746// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1747// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001748void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama2f8af792018-01-20 00:14:16 +00001749 unsigned C = Config->Is64 ? 64 : 32;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001750 for (const Entry &Sym : Symbols) {
1751 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001752 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1753 Val |= uint64_t(1) << (Sym.Hash % C);
1754 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1755 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001756 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001757}
1758
George Rimarf45f6812017-05-16 08:53:30 +00001759void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001760 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rafael Espindolaf9f2abe2017-12-07 18:51:19 +00001761 uint32_t OldBucket = -1;
George Rimar5f73bc92017-03-29 15:23:28 +00001762 uint32_t *Values = Buckets + NBuckets;
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001763 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001764 // Write a hash value. It represents a sequence of chains that share the
1765 // same hash modulo value. The last element of each chain is terminated by
1766 // LSB 1.
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001767 uint32_t Hash = I->Hash;
1768 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
1769 Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
1770 write32(Values++, Hash);
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001771
1772 if (I->BucketIdx == OldBucket)
1773 continue;
1774 // Write a hash bucket. Hash buckets contain indices in the following hash
1775 // value table.
1776 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1777 OldBucket = I->BucketIdx;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001778 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001779}
1780
1781static uint32_t hashGnu(StringRef Name) {
1782 uint32_t H = 5381;
1783 for (uint8_t C : Name)
1784 H = (H << 5) + H + C;
1785 return H;
1786}
1787
1788// Add symbols to this symbol hash table. Note that this function
1789// destructively sort a given vector -- which is needed because
1790// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001791void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001792 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1793 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001794 std::vector<SymbolTableEntry>::iterator Mid =
1795 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001796 // Shared symbols that this executable preempts are special. The dynamic
1797 // linker has to look them up, so they have to be in the hash table.
Zachary Turnera104d552017-11-03 22:33:49 +00001798 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001799 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001800 return !S.Sym->isDefined();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001801 });
George Rimar2ab93622018-03-14 08:52:39 +00001802
Rui Ueyama4e6b8222018-03-14 19:01:00 +00001803 // We chose load factor 4 for the on-disk hash table. For each hash
1804 // collision, the dynamic linker will compare a uint32_t hash value.
1805 // Since the integer comparison is quite fast, we believe we can
1806 // make the load factor even larger. 4 is just a conservative choice.
1807 //
1808 // Note that we don't want to create a zero-sized hash table because
1809 // Android loader as of 2018 doesn't like a .gnu.hash containing such
1810 // table. If that's the case, we create a hash table with one unused
1811 // dummy slot.
George Rimar2ab93622018-03-14 08:52:39 +00001812 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
1813
Eugene Leviantbe809a72016-11-18 06:44:18 +00001814 if (Mid == V.end())
1815 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001816
Rui Ueyama22788262017-12-02 00:37:13 +00001817 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1818 Symbol *B = Ent.Sym;
1819 uint32_t Hash = hashGnu(B->getName());
1820 uint32_t BucketIdx = Hash % NBuckets;
1821 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
1822 }
1823
1824 std::stable_sort(
1825 Symbols.begin(), Symbols.end(),
1826 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
Eugene Leviantbe809a72016-11-18 06:44:18 +00001827
1828 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001829 for (const Entry &Ent : Symbols)
Rui Ueyama48882242017-11-04 00:31:04 +00001830 V.push_back({Ent.Sym, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001831}
1832
George Rimaraaf54712017-09-27 09:14:59 +00001833HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001834 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1835 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001836}
1837
George Rimaraaf54712017-09-27 09:14:59 +00001838void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001839 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001840
George Rimar67c60722017-07-18 11:55:35 +00001841 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001842 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001843
1844 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001845 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001846 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001847}
1848
George Rimaraaf54712017-09-27 09:14:59 +00001849void HashTableSection::writeTo(uint8_t *Buf) {
Shoaib Meenaid79bbf42018-01-11 06:57:01 +00001850 // See comment in GnuHashTableSection::writeTo.
1851 memset(Buf, 0, Size);
1852
George Rimar69b17c32017-05-16 10:04:42 +00001853 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001854
George Rimaraaf54712017-09-27 09:14:59 +00001855 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00001856 write32(P++, NumSymbols); // nbucket
1857 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001858
George Rimaraaf54712017-09-27 09:14:59 +00001859 uint32_t *Buckets = P;
1860 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001861
George Rimar69b17c32017-05-16 10:04:42 +00001862 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Rui Ueyama48882242017-11-04 00:31:04 +00001863 Symbol *Sym = S.Sym;
1864 StringRef Name = Sym->getName();
1865 unsigned I = Sym->DynsymIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001866 uint32_t Hash = hashSysV(Name) % NumSymbols;
1867 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00001868 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001869 }
1870}
1871
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00001872PltSection::PltSection(bool IsIplt)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001873 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00001874 HeaderSize(IsIplt ? 0 : Target->PltHeaderSize), IsIplt(IsIplt) {
Rui Ueyama0cc14832017-06-28 17:05:39 +00001875 // The PLT needs to be writable on SPARC as the dynamic linker will
1876 // modify the instructions in the PLT entries.
1877 if (Config->EMachine == EM_SPARCV9)
1878 this->Flags |= SHF_WRITE;
1879}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001880
George Rimardfc020e2017-03-17 11:01:57 +00001881void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001882 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1883 // linker to resolve dynsyms at runtime. Write such code.
George Rimar9fc2c642018-01-12 09:35:57 +00001884 if (!IsIplt)
Peter Smithf09245a2017-02-09 10:56:15 +00001885 Target->writePltHeader(Buf);
1886 size_t Off = HeaderSize;
1887 // The IPlt is immediately after the Plt, account for this in RelOff
1888 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001889
1890 for (auto &I : Entries) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001891 const Symbol *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001892 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001893 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001894 uint64_t Plt = this->getVA() + Off;
1895 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1896 Off += Target->PltEntrySize;
1897 }
1898}
1899
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001900template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001901 Sym.PltIndex = Entries.size();
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001902 RelocationBaseSection *PltRelocSection = InX::RelaPlt;
George Rimar9fc2c642018-01-12 09:35:57 +00001903 if (IsIplt) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001904 PltRelocSection = InX::RelaIplt;
Peter Smithf09245a2017-02-09 10:56:15 +00001905 Sym.IsInIplt = true;
1906 }
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001907 unsigned RelOff =
1908 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001909 Entries.push_back(std::make_pair(&Sym, RelOff));
1910}
1911
George Rimardfc020e2017-03-17 11:01:57 +00001912size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001913 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001914}
1915
Peter Smith96943762017-01-25 10:31:16 +00001916// Some architectures such as additional symbols in the PLT section. For
1917// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001918void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001919 // The PLT may have symbols defined for the Header, the IPLT has no header
George Rimar9fc2c642018-01-12 09:35:57 +00001920 if (!IsIplt)
Rafael Espindola1037eef2017-12-19 23:59:35 +00001921 Target->addPltHeaderSymbols(*this);
Peter Smithf09245a2017-02-09 10:56:15 +00001922 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001923 for (size_t I = 0; I < Entries.size(); ++I) {
Rafael Espindola1037eef2017-12-19 23:59:35 +00001924 Target->addPltSymbols(*this, Off);
Peter Smith96943762017-01-25 10:31:16 +00001925 Off += Target->PltEntrySize;
1926 }
1927}
1928
George Rimardfc020e2017-03-17 11:01:57 +00001929unsigned PltSection::getPltRelocOff() const {
George Rimar9fc2c642018-01-12 09:35:57 +00001930 return IsIplt ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001931}
1932
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001933// The string hash function for .gdb_index.
1934static uint32_t computeGdbHash(StringRef S) {
1935 uint32_t H = 0;
1936 for (uint8_t C : S)
1937 H = H * 67 + tolower(C) - 113;
1938 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001939}
1940
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001941static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1942 std::vector<GdbIndexChunk::CuEntry> Ret;
1943 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1944 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001945 return Ret;
1946}
1947
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001948static std::vector<GdbIndexChunk::AddressEntry>
1949readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1950 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001951
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001952 uint32_t CuIdx = 0;
1953 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001954 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001955 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001956
George Rimar35e846e2017-03-21 08:19:34 +00001957 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001958 for (DWARFAddressRange &R : Ranges) {
1959 InputSectionBase *S = Sections[R.SectionIndex];
1960 if (!S || S == &InputSection::Discarded || !S->Live)
1961 continue;
1962 // Range list with zero size has no effect.
1963 if (R.LowPC == R.HighPC)
1964 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001965 auto *IS = cast<InputSection>(S);
1966 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001967 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001968 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001969 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001970 }
1971 return Ret;
1972}
1973
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001974static std::vector<GdbIndexChunk::NameTypeEntry>
1975readPubNamesAndTypes(DWARFContext &Dwarf) {
1976 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1977 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001978
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001979 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1980 for (StringRef Sec : {Sec1, Sec2}) {
1981 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001982 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1983 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1984 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1985 Ret.push_back({S, Ent.Descriptor.toBits()});
1986 }
1987 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001988 }
1989 return Ret;
1990}
1991
George Rimar86665622017-06-07 16:59:11 +00001992static std::vector<InputSection *> getDebugInfoSections() {
1993 std::vector<InputSection *> Ret;
1994 for (InputSectionBase *S : InputSections)
1995 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001996 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001997 Ret.push_back(IS);
1998 return Ret;
1999}
2000
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002001void GdbIndexSection::fixCuIndex() {
2002 uint32_t Idx = 0;
2003 for (GdbIndexChunk &Chunk : Chunks) {
2004 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
2005 Ent.CuIndex += Idx;
2006 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00002007 }
2008}
2009
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002010std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2011 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002012 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002013 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002014
2015 for (GdbIndexChunk &Chunk : Chunks) {
2016 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002017 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002018 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002019 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2020 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002021 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002022 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002023
2024 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2025 // duplicate entries, so we want to dedup them.
2026 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2027 uint32_t Val = (Ent.Type << 24) | Idx;
2028 if (Vec.empty() || Vec.back() != Val)
2029 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002030 }
2031 Idx += Chunk.CompilationUnits.size();
2032 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002033
2034 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002035 return Ret;
2036}
George Rimar8b547392016-12-15 09:08:13 +00002037
Rafael Espindola300b3862017-07-12 23:56:53 +00002038template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002039 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002040 std::vector<InputSection *> Sections = getDebugInfoSections();
2041 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002042
George Rimar2d23da02017-08-01 14:57:13 +00002043 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002044 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2045 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2046
2047 Chunks[I].DebugInfoSec = Sections[I];
2048 Chunks[I].CompilationUnits = readCuList(Dwarf);
2049 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2050 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002051 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002052
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002053 // .debug_gnu_pub{names,types} are useless in executables.
2054 // They are present in input object files solely for creating
2055 // a .gdb_index. So we can remove it from the output.
2056 for (InputSectionBase *S : InputSections)
2057 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2058 S->Live = false;
2059
2060 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002061 return make<GdbIndexSection>(std::move(Chunks));
2062}
2063
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002064static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002065 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002066 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002067 Ret += D.CompilationUnits.size();
2068 return Ret;
2069}
George Rimarec02b8d2016-12-15 12:07:53 +00002070
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002071static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002072 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002073 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002074 Ret += D.AddressAreas.size();
2075 return Ret;
2076}
2077
2078std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002079 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2080 if (Size < 1024)
2081 Size = 1024;
2082
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002083 uint32_t Mask = Size - 1;
2084 std::vector<GdbSymbol *> Ret(Size);
2085
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002086 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002087 GdbSymbol *Sym = KV.second;
2088 uint32_t I = Sym->NameHash & Mask;
2089 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2090
2091 while (Ret[I])
2092 I = (I + Step) & Mask;
2093 Ret[I] = Sym;
2094 }
George Rimar86665622017-06-07 16:59:11 +00002095 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002096}
2097
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002098GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002099 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002100 fixCuIndex();
2101 CuVectors = createCuVectors();
2102 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002103
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002104 // Compute offsets early to know the section size.
2105 // Each chunk size needs to be in sync with what we write in writeTo.
2106 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2107 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2108 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002109
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002110 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002111 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002112 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002113 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002114 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002115 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002116}
2117
George Rimar35e846e2017-03-21 08:19:34 +00002118size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002119 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002120}
2121
George Rimar35e846e2017-03-21 08:19:34 +00002122void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002123 // Write the section header.
2124 write32le(Buf, 7);
2125 write32le(Buf + 4, CuListOffset);
2126 write32le(Buf + 8, CuTypesOffset);
2127 write32le(Buf + 12, CuTypesOffset);
2128 write32le(Buf + 16, SymtabOffset);
2129 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002130 Buf += 24;
2131
2132 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002133 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002134 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002135 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002136 write64le(Buf + 8, Cu.CuLength);
2137 Buf += 16;
2138 }
Eugene Levianta113a412016-11-21 09:24:43 +00002139 }
George Rimar8b547392016-12-15 09:08:13 +00002140
2141 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002142 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002143 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00002144 uint64_t BaseAddr =
2145 E.Section->getParent()->Addr + E.Section->getOffset(0);
2146 write64le(Buf, BaseAddr + E.LowAddress);
2147 write64le(Buf + 8, BaseAddr + E.HighAddress);
2148 write32le(Buf + 16, E.CuIndex);
2149 Buf += 20;
2150 }
George Rimar8b547392016-12-15 09:08:13 +00002151 }
George Rimarec02b8d2016-12-15 12:07:53 +00002152
2153 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002154 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002155 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002156 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2157 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002158 }
2159 Buf += 8;
2160 }
2161
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002162 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002163 for (ArrayRef<uint32_t> Vec : CuVectors) {
2164 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002165 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002166 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002167 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002168 Buf += 4;
2169 }
2170 }
2171
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002172 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002173 for (auto &KV : Symbols) {
2174 CachedHashStringRef S = KV.first;
2175 GdbSymbol *Sym = KV.second;
2176 size_t Off = Sym->NameOffset;
2177 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002178 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002179 }
Eugene Levianta113a412016-11-21 09:24:43 +00002180}
2181
George Rimar67c60722017-07-18 11:55:35 +00002182bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002183
Rui Ueyama02551ab2017-10-27 03:14:24 +00002184EhFrameHeader::EhFrameHeader()
Rafael Espindola6b2b4502018-01-23 05:23:23 +00002185 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002186
2187// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2188// Each entry of the search table consists of two values,
2189// the starting PC from where FDEs covers, and the FDE's address.
2190// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002191void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002192 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002193
Rui Ueyama02551ab2017-10-27 03:14:24 +00002194 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002195
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002196 // Sort the FDE list by their PC and uniqueify. Usually there is only
2197 // one FDE for a PC (i.e. function), but if ICF merges two functions
2198 // into one, there can be more than one FDEs pointing to the address.
2199 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2200 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2201 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2202 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2203
2204 Buf[0] = 1;
2205 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2206 Buf[2] = DW_EH_PE_udata4;
2207 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002208 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2209 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002210 Buf += 12;
2211
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002212 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002213 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002214 write32(Buf, Fde.Pc - VA);
2215 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002216 Buf += 8;
2217 }
2218}
2219
Rui Ueyama02551ab2017-10-27 03:14:24 +00002220size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002221 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002222 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002223}
2224
Rui Ueyama02551ab2017-10-27 03:14:24 +00002225bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002226
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002227template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002228VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002229 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2230 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002231
2232static StringRef getFileDefName() {
2233 if (!Config->SoName.empty())
2234 return Config->SoName;
2235 return Config->OutputFile;
2236}
2237
Rui Ueyama945055a2017-02-27 03:07:41 +00002238template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002239 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002240 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002241 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002242
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002243 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002244
2245 // sh_info should be set to the number of definitions. This fact is missed in
2246 // documentation, but confirmed by binutils community:
2247 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002248 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002249}
2250
2251template <class ELFT>
2252void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2253 StringRef Name, size_t NameOff) {
2254 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2255 Verdef->vd_version = 1;
2256 Verdef->vd_cnt = 1;
2257 Verdef->vd_aux = sizeof(Elf_Verdef);
2258 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2259 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2260 Verdef->vd_ndx = Index;
2261 Verdef->vd_hash = hashSysV(Name);
2262
2263 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2264 Verdaux->vda_name = NameOff;
2265 Verdaux->vda_next = 0;
2266}
2267
2268template <class ELFT>
2269void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2270 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2271
2272 for (VersionDefinition &V : Config->VersionDefinitions) {
2273 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2274 writeOne(Buf, V.Id, V.Name, V.NameOff);
2275 }
2276
2277 // Need to terminate the last version definition.
2278 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2279 Verdef->vd_next = 0;
2280}
2281
2282template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2283 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2284}
2285
2286template <class ELFT>
2287VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002288 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002289 ".gnu.version") {
2290 this->Entsize = sizeof(Elf_Versym);
2291}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002292
Rui Ueyama945055a2017-02-27 03:07:41 +00002293template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002294 // At the moment of june 2016 GNU docs does not mention that sh_link field
2295 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002296 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002297}
2298
2299template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002300 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002301}
2302
2303template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2304 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002305 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Zachary Turnera104d552017-11-03 22:33:49 +00002306 OutVersym->vs_index = S.Sym->VersionId;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002307 ++OutVersym;
2308 }
2309}
2310
George Rimar11992c862016-11-25 08:05:41 +00002311template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2312 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2313}
2314
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002315template <class ELFT>
2316VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002317 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2318 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002319 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2320 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2321 // First identifiers are reserved by verdef section if it exist.
2322 NextIndex = getVerDefNum() + 1;
2323}
2324
2325template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002326void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002327 SharedFile<ELFT> &File = SS->getFile<ELFT>();
2328 const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex];
Rui Ueyama4076fa12017-02-26 23:35:34 +00002329 if (!Ver) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002330 SS->VersionId = VER_NDX_GLOBAL;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002331 return;
2332 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002333
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002334 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2335 // to create one by adding it to our needed list and creating a dynstr entry
2336 // for the soname.
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002337 if (File.VerdefMap.empty())
2338 Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)});
2339 typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002340 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2341 // prepare to create one by allocating a version identifier and creating a
2342 // dynstr entry for the version name.
2343 if (NV.Index == 0) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002344 NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() +
Rafael Espindola895aea62017-05-11 22:02:41 +00002345 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002346 NV.Index = NextIndex++;
2347 }
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002348 SS->VersionId = NV.Index;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002349}
2350
2351template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2352 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2353 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2354 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2355
2356 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2357 // Create an Elf_Verneed for this DSO.
2358 Verneed->vn_version = 1;
2359 Verneed->vn_cnt = P.first->VerdefMap.size();
2360 Verneed->vn_file = P.second;
2361 Verneed->vn_aux =
2362 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2363 Verneed->vn_next = sizeof(Elf_Verneed);
2364 ++Verneed;
2365
2366 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2367 // VerdefMap, which will only contain references to needed version
2368 // definitions. Each Elf_Vernaux is based on the information contained in
2369 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2370 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2371 // data structures within a single input file.
2372 for (auto &NV : P.first->VerdefMap) {
2373 Vernaux->vna_hash = NV.first->vd_hash;
2374 Vernaux->vna_flags = 0;
2375 Vernaux->vna_other = NV.second.Index;
2376 Vernaux->vna_name = NV.second.StrTab;
2377 Vernaux->vna_next = sizeof(Elf_Vernaux);
2378 ++Vernaux;
2379 }
2380
2381 Vernaux[-1].vna_next = 0;
2382 }
2383 Verneed[-1].vn_next = 0;
2384}
2385
Rui Ueyama945055a2017-02-27 03:07:41 +00002386template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002387 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2388 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002389}
2390
2391template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2392 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2393 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2394 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2395 return Size;
2396}
2397
George Rimar11992c862016-11-25 08:05:41 +00002398template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2399 return getNeedNum() == 0;
2400}
2401
Rafael Espindola6119b862017-03-06 20:23:56 +00002402void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002403 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002404 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002405}
2406
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002407MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2408 uint64_t Flags, uint32_t Alignment)
2409 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2410 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002411
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002412size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2413
2414void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002415
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002416void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002417 // Add all string pieces to the string table builder to create section
2418 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002419 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002420 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2421 if (Sec->Pieces[I].Live)
2422 Builder.add(Sec->getData(I));
2423
2424 // Fix the string table content. After this, the contents will never change.
2425 Builder.finalize();
2426
2427 // finalize() fixed tail-optimized strings, so we can now get
2428 // offsets of strings. Get an offset for each string and save it
2429 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002430 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002431 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2432 if (Sec->Pieces[I].Live)
2433 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2434}
2435
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002436void MergeNoTailSection::writeTo(uint8_t *Buf) {
2437 for (size_t I = 0; I < NumShards; ++I)
2438 Shards[I].write(Buf + ShardOffsets[I]);
2439}
2440
2441// This function is very hot (i.e. it can take several seconds to finish)
2442// because sometimes the number of inputs is in an order of magnitude of
2443// millions. So, we use multi-threading.
2444//
2445// For any strings S and T, we know S is not mergeable with T if S's hash
2446// value is different from T's. If that's the case, we can safely put S and
2447// T into different string builders without worrying about merge misses.
2448// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002449void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002450 // Initializes string table builders.
2451 for (size_t I = 0; I < NumShards; ++I)
2452 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2453
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002454 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2455 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002456 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002457 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002458 Concurrency =
2459 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002460
2461 // Add section pieces to the builders.
2462 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2463 for (MergeInputSection *Sec : Sections) {
2464 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
Rui Ueyama95bf5092017-10-21 23:20:13 +00002465 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Dimitry Andric656714a2018-01-11 08:03:22 +00002466 if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002467 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002468 }
2469 }
2470 });
2471
2472 // Compute an in-section offset for each shard.
2473 size_t Off = 0;
2474 for (size_t I = 0; I < NumShards; ++I) {
2475 Shards[I].finalizeInOrder();
2476 if (Shards[I].getSize() > 0)
2477 Off = alignTo(Off, Alignment);
2478 ShardOffsets[I] = Off;
2479 Off += Shards[I].getSize();
2480 }
2481 Size = Off;
2482
2483 // So far, section pieces have offsets from beginning of shards, but
2484 // we want offsets from beginning of the whole section. Fix them.
2485 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002486 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2487 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002488 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002489 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002490 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002491}
2492
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002493static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2494 uint32_t Type,
2495 uint64_t Flags,
2496 uint32_t Alignment) {
2497 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2498 if (ShouldTailMerge)
2499 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2500 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002501}
2502
Rui Ueyamaac114d22018-02-12 21:56:14 +00002503// Debug sections may be compressed by zlib. Decompress if exists.
Rui Ueyama2b714b52017-10-11 03:12:53 +00002504void elf::decompressSections() {
2505 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2506 if (Sec->Live)
Rui Ueyamaac114d22018-02-12 21:56:14 +00002507 Sec->maybeDecompress();
Rui Ueyama2b714b52017-10-11 03:12:53 +00002508 });
2509}
2510
2511// This function scans over the inputsections to create mergeable
2512// synthetic sections.
2513//
2514// It removes MergeInputSections from the input section array and adds
2515// new synthetic sections at the location of the first input section
2516// that it replaces. It then finalizes each synthetic section in order
2517// to compute an output offset for each piece of each input section.
2518void elf::mergeSections() {
2519 // splitIntoPieces needs to be called on each MergeInputSection
2520 // before calling finalizeContents(). Do that first.
2521 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2522 if (Sec->Live)
2523 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2524 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002525 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002526
2527 std::vector<MergeSyntheticSection *> MergeSections;
2528 for (InputSectionBase *&S : InputSections) {
2529 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2530 if (!MS)
2531 continue;
2532
2533 // We do not want to handle sections that are not alive, so just remove
2534 // them instead of trying to merge.
2535 if (!MS->Live)
2536 continue;
2537
George Rimar78e27e82017-12-01 09:04:52 +00002538 StringRef OutsecName = getOutputSectionName(MS);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002539 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2540
2541 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002542 // While we could create a single synthetic section for two different
2543 // values of Entsize, it is better to take Entsize into consideration.
2544 //
2545 // With a single synthetic section no two pieces with different Entsize
2546 // could be equal, so we may as well have two sections.
2547 //
2548 // Using Entsize in here also allows us to propagate it to the synthetic
2549 // section.
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002550 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002551 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002552 });
2553 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002554 MergeSyntheticSection *Syn =
2555 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002556 MergeSections.push_back(Syn);
2557 I = std::prev(MergeSections.end());
2558 S = Syn;
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002559 Syn->Entsize = MS->Entsize;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002560 } else {
2561 S = nullptr;
2562 }
2563 (*I)->addSection(MS);
2564 }
2565 for (auto *MS : MergeSections)
2566 MS->finalizeContents();
2567
2568 std::vector<InputSectionBase *> &V = InputSections;
2569 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2570}
2571
George Rimar42886c42017-03-15 12:02:31 +00002572MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002573 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2574 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002575
George Rimar90a528b2017-03-21 09:01:39 +00002576ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002577 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002578 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002579
2580// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2581// This section will have been sorted last in the .ARM.exidx table.
2582// This table entry will have the form:
2583// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002584// The sentinel must have the PREL31 value of an address higher than any
2585// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002586void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Igor Kudrinf01caab2017-12-14 06:23:50 +00002587 assert(Highest);
Igor Kudrin5966d152017-12-20 08:56:10 +00002588 uint64_t S =
2589 Highest->getParent()->Addr + Highest->getOffset(Highest->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002590 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002591 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002592 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002593}
2594
Igor Kudrin5966d152017-12-20 08:56:10 +00002595// The sentinel has to be removed if there are no other .ARM.exidx entries.
2596bool ARMExidxSentinelSection::empty() const {
George Rimar563e4f22018-02-22 09:55:28 +00002597 for (InputSection *IS : getInputSections(getParent()))
2598 if (!isa<ARMExidxSentinelSection>(IS))
2599 return false;
Igor Kudrin5966d152017-12-20 08:56:10 +00002600 return true;
2601}
2602
George Rimar7b827042017-03-16 10:40:50 +00002603ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002604 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002605 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002606 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002607 this->OutSecOff = Off;
2608}
2609
George Rimar7b827042017-03-16 10:40:50 +00002610void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002611 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002612 T->Offset = Off;
2613 Thunks.push_back(T);
2614 T->addSymbols(*this);
2615 Size = Off + T->size();
2616}
2617
George Rimar7b827042017-03-16 10:40:50 +00002618void ThunkSection::writeTo(uint8_t *Buf) {
2619 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002620 T->writeTo(Buf + T->Offset, *this);
2621}
2622
George Rimar7b827042017-03-16 10:40:50 +00002623InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002624 if (Thunks.empty())
2625 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002626 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002627 return T->getTargetInputSection();
2628}
2629
George Rimar9782ca52017-03-15 15:29:29 +00002630InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002631BssSection *InX::Bss;
2632BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002633BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002634EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002635EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002636SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002637StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002638SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002639InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002640GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002641GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002642GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002643GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002644HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002645IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002646MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002647MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002648PltSection *InX::Plt;
2649PltSection *InX::Iplt;
Rafael Espindola58946cd2017-12-10 19:44:42 +00002650RelocationBaseSection *InX::RelaDyn;
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002651RelocationBaseSection *InX::RelaPlt;
2652RelocationBaseSection *InX::RelaIplt;
George Rimar9782ca52017-03-15 15:29:29 +00002653StringTableSection *InX::ShStrTab;
2654StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002655SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002656
Rafael Espindola300b3862017-07-12 23:56:53 +00002657template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2658template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2659template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2660template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2661
Rui Ueyama572247f2017-10-27 03:13:39 +00002662template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2663template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2664template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2665template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2666
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002667template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2668template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2669template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2670template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
George Rimara9189572017-03-17 16:50:07 +00002671
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002672template class elf::MipsAbiFlagsSection<ELF32LE>;
2673template class elf::MipsAbiFlagsSection<ELF32BE>;
2674template class elf::MipsAbiFlagsSection<ELF64LE>;
2675template class elf::MipsAbiFlagsSection<ELF64BE>;
2676
Simon Atanasyance02cf02016-11-09 21:36:56 +00002677template class elf::MipsOptionsSection<ELF32LE>;
2678template class elf::MipsOptionsSection<ELF32BE>;
2679template class elf::MipsOptionsSection<ELF64LE>;
2680template class elf::MipsOptionsSection<ELF64BE>;
2681
2682template class elf::MipsReginfoSection<ELF32LE>;
2683template class elf::MipsReginfoSection<ELF32BE>;
2684template class elf::MipsReginfoSection<ELF64LE>;
2685template class elf::MipsReginfoSection<ELF64BE>;
2686
Eugene Leviant6380ce22016-11-15 12:26:55 +00002687template class elf::DynamicSection<ELF32LE>;
2688template class elf::DynamicSection<ELF32BE>;
2689template class elf::DynamicSection<ELF64LE>;
2690template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002691
2692template class elf::RelocationSection<ELF32LE>;
2693template class elf::RelocationSection<ELF32BE>;
2694template class elf::RelocationSection<ELF64LE>;
2695template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002696
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002697template class elf::AndroidPackedRelocationSection<ELF32LE>;
2698template class elf::AndroidPackedRelocationSection<ELF32BE>;
2699template class elf::AndroidPackedRelocationSection<ELF64LE>;
2700template class elf::AndroidPackedRelocationSection<ELF64BE>;
2701
Eugene Leviant9230db92016-11-17 09:16:34 +00002702template class elf::SymbolTableSection<ELF32LE>;
2703template class elf::SymbolTableSection<ELF32BE>;
2704template class elf::SymbolTableSection<ELF64LE>;
2705template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002706
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002707template class elf::VersionTableSection<ELF32LE>;
2708template class elf::VersionTableSection<ELF32BE>;
2709template class elf::VersionTableSection<ELF64LE>;
2710template class elf::VersionTableSection<ELF64BE>;
2711
2712template class elf::VersionNeedSection<ELF32LE>;
2713template class elf::VersionNeedSection<ELF32BE>;
2714template class elf::VersionNeedSection<ELF64LE>;
2715template class elf::VersionNeedSection<ELF64BE>;
2716
2717template class elf::VersionDefinitionSection<ELF32LE>;
2718template class elf::VersionDefinitionSection<ELF32BE>;
2719template class elf::VersionDefinitionSection<ELF64LE>;
2720template class elf::VersionDefinitionSection<ELF64BE>;