blob: 4c6cbff979949aae42a541b26657a39584501972 [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.
Eric Christopher7baac212018-03-20 18:10:30 +000068 // You can get consistent output by using the environment variable.
Rui Ueyama3da3f062016-11-10 20:20:37 +000069 // 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
Peter Collingbournec5391ce2018-03-29 22:32:13 +0000267Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
268 uint64_t Size, InputSectionBase &Section) {
Rafael Espindola1037eef2017-12-19 23:59:35 +0000269 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,
Zaara Syedac65ae142018-03-26 17:50:52 +0000590 Target->GotEntrySize, ".got") {
591 // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the
592 // .got. If there are no references to .TOC. in the symbol table,
593 // ElfSym::GlobalOffsetTable will not be defined and we won't need to save
594 // .TOC. in the .got. When it is defined, we increase NumEntries by the number
595 // of entries used to emit ElfSym::GlobalOffsetTable.
596 if (ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt)
597 NumEntries += Target->GotHeaderEntriesNum;
598}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000599
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000600void GotSection::addEntry(Symbol &Sym) {
Zaara Syedac65ae142018-03-26 17:50:52 +0000601 Sym.GotIndex = NumEntries;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000602 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000603}
604
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000605bool GotSection::addDynTlsEntry(Symbol &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000606 if (Sym.GlobalDynIndex != -1U)
607 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000608 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000609 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000610 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000611 return true;
612}
613
614// Reserves TLS entries for a TLS module ID and a TLS block offset.
615// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000616bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000617 if (TlsIndexOff != uint32_t(-1))
618 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000619 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000620 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000621 return true;
622}
623
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000624uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000625 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000626}
627
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000628uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000629 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000630}
631
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000632void GotSection::finalizeContents() {
Zaara Syedac65ae142018-03-26 17:50:52 +0000633 Size = NumEntries * Config->Wordsize;
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000634}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000635
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000636bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000637 // We need to emit a GOT even if it's empty if there's a relocation that is
638 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
Peter Smith3d044f52018-03-19 06:52:51 +0000639 // (i.e. _GLOBAL_OFFSET_TABLE_) that the target defines relative to the .got.
640 return NumEntries == 0 && !HasGotOffRel &&
641 !(ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt);
George Rimar11992c862016-11-25 08:05:41 +0000642}
643
Igor Kudrin202a9f62017-07-14 08:10:45 +0000644void GotSection::writeTo(uint8_t *Buf) {
645 // Buf points to the start of this section's buffer,
646 // whereas InputSectionBase::relocateAlloc() expects its argument
647 // to point to the start of the output section.
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000648 Target->writeGotHeader(Buf);
649 Buf += Target->GotHeaderEntriesNum * Target->GotEntrySize;
Igor Kudrin202a9f62017-07-14 08:10:45 +0000650 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
651}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000652
George Rimar14534eb2017-03-20 16:44:28 +0000653MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000654 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
655 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000656
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000657void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000658 // For "true" local symbols which can be referenced from the same module
659 // only compiler creates two instructions for address loading:
660 //
661 // lw $8, 0($gp) # R_MIPS_GOT16
662 // addi $8, $8, 0 # R_MIPS_LO16
663 //
664 // The first instruction loads high 16 bits of the symbol address while
665 // the second adds an offset. That allows to reduce number of required
666 // GOT entries because only one global offset table entry is necessary
667 // for every 64 KBytes of local data. So for local symbols we need to
668 // allocate number of GOT entries to hold all required "page" addresses.
669 //
670 // All global symbols (hidden and regular) considered by compiler uniformly.
671 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
672 // to load address of the symbol. So for each such symbol we need to
673 // allocate dedicated GOT entry to store its address.
674 //
675 // If a symbol is preemptible we need help of dynamic linker to get its
676 // final address. The corresponding GOT entries are allocated in the
677 // "global" part of GOT. Entries for non preemptible global symbol allocated
678 // in the "local" part of GOT.
679 //
680 // See "Global Offset Table" in Chapter 5:
681 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
682 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
683 // At this point we do not know final symbol value so to reduce number
684 // of allocated GOT entries do the following trick. Save all output
685 // sections referenced by GOT relocations. Then later in the `finalize`
686 // method calculate number of "pages" required to cover all saved output
687 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000688 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000689 return;
690 }
691 if (Sym.isTls()) {
692 // GOT entries created for MIPS TLS relocations behave like
693 // almost GOT entries from other ABIs. They go to the end
694 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000695 Sym.GotIndex = TlsEntries.size();
696 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000697 return;
698 }
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000699 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000700 if (S.isInGot() && !A)
701 return;
702 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000703 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000704 return;
705 Items.emplace_back(&S, A);
706 if (!A)
707 S.GotIndex = NewIndex;
708 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000709 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000710 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000711 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000712 Sym.IsInGlobalMipsGot = true;
713 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000714 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000715 Sym.Is32BitMipsGot = true;
716 } else {
717 // Hold local GOT entries accessed via a 16-bit index separately.
718 // That allows to write them in the beginning of the GOT and keep
719 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000720 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000721 }
722}
723
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000724bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000725 if (Sym.GlobalDynIndex != -1U)
726 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000727 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000728 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000729 TlsEntries.push_back(nullptr);
730 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000731 return true;
732}
733
734// Reserves TLS entries for a TLS module ID and a TLS block offset.
735// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000736bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000737 if (TlsIndexOff != uint32_t(-1))
738 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000739 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000740 TlsEntries.push_back(nullptr);
741 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000742 return true;
743}
744
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000745static uint64_t getMipsPageAddr(uint64_t Addr) {
746 return (Addr + 0x8000) & ~0xffff;
747}
748
749static uint64_t getMipsPageCount(uint64_t Size) {
750 return (Size + 0xfffe) / 0xffff + 1;
751}
752
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000753uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
George Rimar14534eb2017-03-20 16:44:28 +0000754 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000755 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000756 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
757 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
758 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000759 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000760 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000761}
762
Rui Ueyama48882242017-11-04 00:31:04 +0000763uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
764 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000765 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000766 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000767 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000768 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000769 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000770 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000771 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000772 Index += LocalEntries.size();
773 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000774 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000775 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000776 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000777 auto It = EntryIndexMap.find({&B, Addend});
778 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000779 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000780 }
George Rimar14534eb2017-03-20 16:44:28 +0000781 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000782}
783
George Rimar14534eb2017-03-20 16:44:28 +0000784uint64_t MipsGotSection::getTlsOffset() const {
785 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000786}
787
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000788uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
George Rimar14534eb2017-03-20 16:44:28 +0000789 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790}
791
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000792const Symbol *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000793 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794}
795
George Rimar14534eb2017-03-20 16:44:28 +0000796unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000797 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
798 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000799}
800
George Rimar67c60722017-07-18 11:55:35 +0000801void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000802
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000803bool MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000804 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000805 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000806 // For each output section referenced by GOT page relocations calculate
807 // and save into PageIndexMap an upper bound of MIPS GOT entries required
808 // to store page addresses of local symbols. We assume the worst case -
809 // each 64kb page of the output section has at least one GOT relocation
810 // against it. And take in account the case when the section intersects
811 // page boundaries.
812 P.second = PageEntriesNum;
813 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000814 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000815 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000816 Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000817 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000818}
819
George Rimar14534eb2017-03-20 16:44:28 +0000820bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000821 // We add the .got section to the result for dynamic MIPS target because
822 // its address and properties are mentioned in the .dynamic section.
823 return Config->Relocatable;
824}
825
George Rimar67c60722017-07-18 11:55:35 +0000826uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000827
George Rimar14534eb2017-03-20 16:44:28 +0000828void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000829 // Set the MSB of the second GOT slot. This is not required by any
830 // MIPS ABI documentation, though.
831 //
832 // There is a comment in glibc saying that "The MSB of got[1] of a
833 // gnu object is set to identify gnu objects," and in GNU gold it
834 // says "the second entry will be used by some runtime loaders".
835 // But how this field is being used is unclear.
836 //
837 // We are not really willing to mimic other linkers behaviors
838 // without understanding why they do that, but because all files
839 // generated by GNU tools have this special GOT value, and because
840 // we've been doing this for years, it is probably a safe bet to
841 // keep doing this for now. We really need to revisit this to see
842 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000843 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
844 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000845 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000846 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000847 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000848 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000849 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000850 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
851 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000852 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000853 }
George Rimar14534eb2017-03-20 16:44:28 +0000854 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000855 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000856 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000857 Buf += Config->Wordsize;
Rui Ueyama48882242017-11-04 00:31:04 +0000858 const Symbol *Sym = SA.first;
859 uint64_t VA = Sym->getVA(SA.second);
Simon Atanasyan5a4e2132017-11-08 23:34:34 +0000860 if (Sym->StOther & STO_MIPS_MICROMIPS)
861 VA |= 1;
George Rimar14534eb2017-03-20 16:44:28 +0000862 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000863 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000864 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
865 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
866 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000867 // Initialize TLS-related GOT entries. If the entry has a corresponding
868 // dynamic relocations, leave it initialized by zero. Write down adjusted
869 // TLS symbol's values otherwise. To calculate the adjustments use offsets
870 // for thread-local storage.
871 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000872 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000873 writeUint(Buf + TlsIndexOff, 1);
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000874 for (const Symbol *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000875 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000876 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000877 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000878 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000879 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
880 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000881 }
882 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000883 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
884 writeUint(Entry, 1);
885 Entry += Config->Wordsize;
886 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000887 }
888 }
889}
890
George Rimar10f74fc2017-03-15 09:12:56 +0000891GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000892 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
893 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000894
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000895void GotPltSection::addEntry(Symbol &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000896 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
897 Entries.push_back(&Sym);
898}
899
George Rimar10f74fc2017-03-15 09:12:56 +0000900size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000901 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
902 Target->GotPltEntrySize;
903}
904
George Rimar10f74fc2017-03-15 09:12:56 +0000905void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000906 Target->writeGotPltHeader(Buf);
907 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000908 for (const Symbol *B : Entries) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000909 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000910 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000911 }
912}
913
Peter Smith3d044f52018-03-19 06:52:51 +0000914bool GotPltSection::empty() const {
915 // We need to emit a GOT.PLT even if it's empty if there's a symbol that
916 // references the _GLOBAL_OFFSET_TABLE_ and the Target defines the symbol
917 // relative to the .got.plt section.
918 return Entries.empty() &&
919 !(ElfSym::GlobalOffsetTable && Target->GotBaseSymInGotPlt);
920}
921
Peter Smithbaffdb82016-12-08 12:58:55 +0000922// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
923// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000924IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000925 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
926 Target->GotPltEntrySize,
927 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000928
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000929void IgotPltSection::addEntry(Symbol &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000930 Sym.IsInIgot = true;
931 Sym.GotPltIndex = Entries.size();
932 Entries.push_back(&Sym);
933}
934
George Rimar10f74fc2017-03-15 09:12:56 +0000935size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000936 return Entries.size() * Target->GotPltEntrySize;
937}
938
George Rimar10f74fc2017-03-15 09:12:56 +0000939void IgotPltSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000940 for (const Symbol *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000941 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000942 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000943 }
944}
945
George Rimar49648002017-03-15 09:32:36 +0000946StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
947 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000948 Dynamic(Dynamic) {
949 // ELF string tables start with a NUL byte.
950 addString("");
951}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000952
953// Adds a string to the string table. If HashIt is true we hash and check for
954// duplicates. It is optional because the name of global symbols are already
955// uniqued and hashing them again has a big cost for a small value: uniquing
956// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000957unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000958 if (HashIt) {
959 auto R = StringMap.insert(std::make_pair(S, this->Size));
960 if (!R.second)
961 return R.first->second;
962 }
963 unsigned Ret = this->Size;
964 this->Size = this->Size + S.size() + 1;
965 Strings.push_back(S);
966 return Ret;
967}
968
George Rimar49648002017-03-15 09:32:36 +0000969void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000970 for (StringRef S : Strings) {
971 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000972 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000973 Buf += S.size() + 1;
974 }
975}
976
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000977// Returns the number of version definition entries. Because the first entry
978// is for the version definition itself, it is the number of versioned symbols
979// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000980static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
981
982template <class ELFT>
983DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000984 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +0000985 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000986 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +0000987
Petr Hosekffa786f2017-05-26 19:12:38 +0000988 // .dynamic section is not writable on MIPS and on Fuchsia OS
989 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000990 // See "Special Section" in Chapter 4 in the following document:
991 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +0000992 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +0000993 this->Flags = SHF_ALLOC;
994
Rui Ueyama22e55512017-12-15 19:39:59 +0000995 // Add strings to .dynstr early so that .dynstr's size will be
996 // fixed early.
997 for (StringRef S : Config->FilterList)
998 addInt(DT_FILTER, InX::DynStrTab->addString(S));
999 for (StringRef S : Config->AuxiliaryList)
1000 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
1001
1002 if (!Config->Rpath.empty())
1003 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1004 InX::DynStrTab->addString(Config->Rpath));
1005
1006 for (InputFile *File : SharedFiles) {
1007 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1008 if (F->IsNeeded)
1009 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
1010 }
1011 if (!Config->SoName.empty())
1012 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001013}
1014
Rui Ueyama15475e92017-11-24 02:15:51 +00001015template <class ELFT>
1016void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1017 Entries.push_back({Tag, Fn});
1018}
1019
1020template <class ELFT>
1021void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1022 Entries.push_back({Tag, [=] { return Val; }});
1023}
1024
1025template <class ELFT>
1026void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
Rafael Espindola4f058a22018-03-24 00:35:11 +00001027 Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
Rui Ueyama15475e92017-11-24 02:15:51 +00001028}
1029
1030template <class ELFT>
1031void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1032 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1033}
1034
1035template <class ELFT>
1036void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1037 Entries.push_back({Tag, [=] { return Sec->Size; }});
1038}
1039
1040template <class ELFT>
1041void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1042 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1043}
1044
Rui Ueyama22e55512017-12-15 19:39:59 +00001045// Add remaining entries to complete .dynamic contents.
1046template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1047 if (this->Size)
1048 return; // Already finalized.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001049
1050 // Set DT_FLAGS and DT_FLAGS_1.
1051 uint32_t DtFlags = 0;
1052 uint32_t DtFlags1 = 0;
1053 if (Config->Bsymbolic)
1054 DtFlags |= DF_SYMBOLIC;
1055 if (Config->ZNodelete)
1056 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001057 if (Config->ZNodlopen)
1058 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001059 if (Config->ZNow) {
1060 DtFlags |= DF_BIND_NOW;
1061 DtFlags1 |= DF_1_NOW;
1062 }
1063 if (Config->ZOrigin) {
1064 DtFlags |= DF_ORIGIN;
1065 DtFlags1 |= DF_1_ORIGIN;
1066 }
Rui Ueyama7c18abf2018-03-01 22:56:52 +00001067 if (!Config->ZText)
1068 DtFlags |= DF_TEXTREL;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001069
1070 if (DtFlags)
Rui Ueyama15475e92017-11-24 02:15:51 +00001071 addInt(DT_FLAGS, DtFlags);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001072 if (DtFlags1)
Rui Ueyama15475e92017-11-24 02:15:51 +00001073 addInt(DT_FLAGS_1, DtFlags1);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001074
Petr Hosekffa786f2017-05-26 19:12:38 +00001075 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1076 // need it for each process, so we don't write it for DSOs. The loader writes
1077 // the pointer into this entry.
1078 //
1079 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1080 // systems (currently only Fuchsia OS) provide other means to give the
1081 // debugger this information. Such systems may choose make .dynamic read-only.
1082 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1083 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
Rui Ueyama15475e92017-11-24 02:15:51 +00001084 addInt(DT_DEBUG, 0);
George Rimarb4081bb2017-05-12 08:04:58 +00001085
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001086 this->Link = InX::DynStrTab->getParent()->SectionIndex;
George Rimar32085882017-12-30 08:40:45 +00001087 if (!InX::RelaDyn->empty()) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001088 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1089 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001090
1091 bool IsRela = Config->IsRela;
Rui Ueyama15475e92017-11-24 02:15:51 +00001092 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1093 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001094
1095 // MIPS dynamic loader does not support RELCOUNT tag.
1096 // The problem is in the tight relation between dynamic
1097 // relocations and GOT. So do not emit this tag on MIPS.
1098 if (Config->EMachine != EM_MIPS) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001099 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001100 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama15475e92017-11-24 02:15:51 +00001101 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001102 }
1103 }
George Rimaredb61162017-12-31 07:42:54 +00001104 // .rel[a].plt section usually consists of two parts, containing plt and
1105 // iplt relocations. It is possible to have only iplt relocations in the
1106 // output. In that case RelaPlt is empty and have zero offset, the same offset
1107 // as RelaIplt have. And we still want to emit proper dynamic tags for that
1108 // case, so here we always use RelaPlt as marker for the begining of
1109 // .rel[a].plt section.
1110 if (InX::RelaPlt->getParent()->Live) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001111 addInSec(DT_JMPREL, InX::RelaPlt);
1112 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
Rui Ueyama0cc14832017-06-28 17:05:39 +00001113 switch (Config->EMachine) {
1114 case EM_MIPS:
Rui Ueyama15475e92017-11-24 02:15:51 +00001115 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001116 break;
1117 case EM_SPARCV9:
Rui Ueyama15475e92017-11-24 02:15:51 +00001118 addInSec(DT_PLTGOT, InX::Plt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001119 break;
1120 default:
Rui Ueyama15475e92017-11-24 02:15:51 +00001121 addInSec(DT_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001122 break;
1123 }
Rui Ueyama15475e92017-11-24 02:15:51 +00001124 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001125 }
1126
Rui Ueyama15475e92017-11-24 02:15:51 +00001127 addInSec(DT_SYMTAB, InX::DynSymTab);
1128 addInt(DT_SYMENT, sizeof(Elf_Sym));
1129 addInSec(DT_STRTAB, InX::DynStrTab);
1130 addInt(DT_STRSZ, InX::DynStrTab->getSize());
George Rimar0a7412f2017-03-09 08:48:34 +00001131 if (!Config->ZText)
Rui Ueyama15475e92017-11-24 02:15:51 +00001132 addInt(DT_TEXTREL, 0);
George Rimar69b17c32017-05-16 10:04:42 +00001133 if (InX::GnuHashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001134 addInSec(DT_GNU_HASH, InX::GnuHashTab);
George Rimaraaf54712017-09-27 09:14:59 +00001135 if (InX::HashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001136 addInSec(DT_HASH, InX::HashTab);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001137
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001138 if (Out::PreinitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001139 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1140 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001141 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001142 if (Out::InitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001143 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1144 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001145 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001146 if (Out::FiniArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001147 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1148 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001149 }
1150
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001151 if (Symbol *B = Symtab->find(Config->Init))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001152 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001153 addSym(DT_INIT, B);
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001154 if (Symbol *B = Symtab->find(Config->Fini))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001155 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001156 addSym(DT_FINI, B);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001157
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001158 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1159 if (HasVerNeed || In<ELFT>::VerDef)
Rui Ueyama15475e92017-11-24 02:15:51 +00001160 addInSec(DT_VERSYM, In<ELFT>::VerSym);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001161 if (In<ELFT>::VerDef) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001162 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1163 addInt(DT_VERDEFNUM, getVerDefNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001164 }
1165 if (HasVerNeed) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001166 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1167 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001168 }
1169
1170 if (Config->EMachine == EM_MIPS) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001171 addInt(DT_MIPS_RLD_VERSION, 1);
1172 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1173 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1174 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
James Hendersonf70c5be2017-11-22 12:04:21 +00001175
Rui Ueyama15475e92017-11-24 02:15:51 +00001176 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
James Hendersonf70c5be2017-11-22 12:04:21 +00001177
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001178 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama15475e92017-11-24 02:15:51 +00001179 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001180 else
Rui Ueyama15475e92017-11-24 02:15:51 +00001181 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1182 addInSec(DT_PLTGOT, InX::MipsGot);
Rafael Espindola895aea62017-05-11 22:02:41 +00001183 if (InX::MipsRldMap)
Rui Ueyama15475e92017-11-24 02:15:51 +00001184 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001185 }
1186
Rui Ueyama15475e92017-11-24 02:15:51 +00001187 addInt(DT_NULL, 0);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001188
George Rimar8f3a6c82017-10-06 10:06:13 +00001189 getParent()->Link = this->Link;
1190 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001191}
1192
1193template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1194 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1195
Rui Ueyama15475e92017-11-24 02:15:51 +00001196 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1197 P->d_tag = KV.first;
1198 P->d_un.d_val = KV.second();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001199 ++P;
1200 }
1201}
1202
George Rimar97def8c2017-03-17 12:07:44 +00001203uint64_t DynamicReloc::getOffset() const {
Rafael Espindola4f058a22018-03-24 00:35:11 +00001204 return InputSec->getVA(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001205}
1206
Alexander Richardson048e2502018-02-19 11:00:15 +00001207int64_t DynamicReloc::computeAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001208 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001209 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001210 return Addend;
1211}
1212
George Rimar97def8c2017-03-17 12:07:44 +00001213uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001214 if (Sym && !UseSymVA)
1215 return Sym->DynsymIndex;
1216 return 0;
1217}
1218
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001219RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1220 int32_t DynamicTag,
1221 int32_t SizeDynamicTag)
1222 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1223 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001224
Rafael Espindolad49866e2018-02-13 16:06:11 +00001225void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
Rafael Espindola35cf8bb2018-02-13 16:03:52 +00001226 uint64_t OffsetInSec, Symbol *Sym) {
1227 addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1228}
1229
Rafael Espindolad49866e2018-02-13 16:06:11 +00001230void RelocationBaseSection::addReloc(RelType DynType,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001231 InputSectionBase *InputSec,
Rafael Espindolab9603252018-02-16 16:53:04 +00001232 uint64_t OffsetInSec, Symbol *Sym,
1233 int64_t Addend, RelExpr Expr,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001234 RelType Type) {
Alexander Richardsoncfb60932018-02-16 10:01:17 +00001235 // Write the addends to the relocated address if required. We skip
1236 // it if the written value would be zero.
Rafael Espindolab9603252018-02-16 16:53:04 +00001237 if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0))
Rafael Espindola73584cb2018-01-05 20:08:38 +00001238 InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
Rafael Espindolab9603252018-02-16 16:53:04 +00001239 addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
Rafael Espindola73584cb2018-01-05 20:08:38 +00001240}
1241
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001242void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001243 if (Reloc.Type == Target->RelativeRel)
1244 ++NumRelativeRelocs;
1245 Relocs.push_back(Reloc);
1246}
1247
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001248void RelocationBaseSection::finalizeContents() {
1249 // If all relocations are R_*_RELATIVE they don't refer to any
1250 // dynamic symbol and we don't need a dynamic symbol table. If that
1251 // is the case, just use 0 as the link.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001252 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001253
1254 // Set required output section properties.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001255 getParent()->Link = Link;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001256}
1257
1258template <class ELFT>
1259static void encodeDynamicReloc(typename ELFT::Rela *P,
1260 const DynamicReloc &Rel) {
1261 if (Config->IsRela)
Alexander Richardson048e2502018-02-19 11:00:15 +00001262 P->r_addend = Rel.computeAddend();
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001263 P->r_offset = Rel.getOffset();
1264 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1265 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1266 // entries. These entries are placed after the global and local sections of
1267 // the GOT. At the point when we create these relocations, the size of the
1268 // global and local sections is unknown, so the offset that we store in the
1269 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1270 // the GOT, rather than being relative to the start of the GOT. This line of
1271 // code adds the size of the global and local sections to the virtual
1272 // address computed by getOffset() in order to adjust it into the TLS
1273 // section.
1274 P->r_offset += InX::MipsGot->getTlsOffset();
1275 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1276}
1277
1278template <class ELFT>
1279RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1280 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1281 Config->IsRela ? DT_RELA : DT_REL,
1282 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1283 Sort(Sort) {
1284 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1285}
1286
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001287static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) {
1288 bool AIsRel = A.Type == Target->RelativeRel;
1289 bool BIsRel = B.Type == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001290 if (AIsRel != BIsRel)
1291 return AIsRel;
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001292 return A.getSymIndex() < B.getSymIndex();
Eugene Levianta96d9022016-11-16 10:02:27 +00001293}
1294
1295template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001296 if (Sort)
1297 std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1298
George Rimar97def8c2017-03-17 12:07:44 +00001299 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001300 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001301 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001302 }
Eugene Levianta96d9022016-11-16 10:02:27 +00001303}
1304
1305template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1306 return this->Entsize * Relocs.size();
1307}
1308
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001309template <class ELFT>
1310AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1311 StringRef Name)
1312 : RelocationBaseSection(
1313 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1314 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1315 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1316 this->Entsize = 1;
1317}
Eugene Levianta96d9022016-11-16 10:02:27 +00001318
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001319template <class ELFT>
1320bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1321 // This function computes the contents of an Android-format packed relocation
1322 // section.
1323 //
1324 // This format compresses relocations by using relocation groups to factor out
1325 // fields that are common between relocations and storing deltas from previous
1326 // relocations in SLEB128 format (which has a short representation for small
1327 // numbers). A good example of a relocation type with common fields is
1328 // R_*_RELATIVE, which is normally used to represent function pointers in
1329 // vtables. In the REL format, each relative relocation has the same r_info
1330 // field, and is only different from other relative relocations in terms of
1331 // the r_offset field. By sorting relocations by offset, grouping them by
1332 // r_info and representing each relocation with only the delta from the
1333 // previous offset, each 8-byte relocation can be compressed to as little as 1
1334 // byte (or less with run-length encoding). This relocation packer was able to
1335 // reduce the size of the relocation section in an Android Chromium DSO from
1336 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1337 //
1338 // A relocation section consists of a header containing the literal bytes
1339 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1340 // elements are the total number of relocations in the section and an initial
1341 // r_offset value. The remaining elements define a sequence of relocation
1342 // groups. Each relocation group starts with a header consisting of the
1343 // following elements:
1344 //
1345 // - the number of relocations in the relocation group
1346 // - flags for the relocation group
1347 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1348 // for each relocation in the group.
1349 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1350 // field for each relocation in the group.
1351 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1352 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1353 // each relocation in the group.
1354 //
1355 // Following the relocation group header are descriptions of each of the
1356 // relocations in the group. They consist of the following elements:
1357 //
1358 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1359 // delta for this relocation.
1360 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1361 // field for this relocation.
1362 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1363 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1364 // this relocation.
1365
1366 size_t OldSize = RelocData.size();
1367
1368 RelocData = {'A', 'P', 'S', '2'};
1369 raw_svector_ostream OS(RelocData);
Rui Ueyama04c821c2017-12-08 02:20:50 +00001370 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001371
1372 // The format header includes the number of relocations and the initial
1373 // offset (we set this to zero because the first relocation group will
1374 // perform the initial adjustment).
Rui Ueyama04c821c2017-12-08 02:20:50 +00001375 Add(Relocs.size());
1376 Add(0);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001377
1378 std::vector<Elf_Rela> Relatives, NonRelatives;
1379
1380 for (const DynamicReloc &Rel : Relocs) {
1381 Elf_Rela R;
1382 encodeDynamicReloc<ELFT>(&R, Rel);
1383
1384 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1385 Relatives.push_back(R);
1386 else
1387 NonRelatives.push_back(R);
1388 }
1389
1390 std::sort(Relatives.begin(), Relatives.end(),
1391 [](const Elf_Rel &A, const Elf_Rel &B) {
1392 return A.r_offset < B.r_offset;
1393 });
1394
1395 // Try to find groups of relative relocations which are spaced one word
1396 // apart from one another. These generally correspond to vtable entries. The
1397 // format allows these groups to be encoded using a sort of run-length
1398 // encoding, but each group will cost 7 bytes in addition to the offset from
1399 // the previous group, so it is only profitable to do this for groups of
1400 // size 8 or larger.
1401 std::vector<Elf_Rela> UngroupedRelatives;
1402 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1403 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1404 std::vector<Elf_Rela> Group;
1405 do {
1406 Group.push_back(*I++);
1407 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1408
1409 if (Group.size() < 8)
1410 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1411 Group.end());
1412 else
1413 RelativeGroups.emplace_back(std::move(Group));
1414 }
1415
1416 unsigned HasAddendIfRela =
1417 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1418
1419 uint64_t Offset = 0;
1420 uint64_t Addend = 0;
1421
1422 // Emit the run-length encoding for the groups of adjacent relative
1423 // relocations. Each group is represented using two groups in the packed
1424 // format. The first is used to set the current offset to the start of the
1425 // group (and also encodes the first relocation), and the second encodes the
1426 // remaining relocations.
1427 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1428 // The first relocation in the group.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001429 Add(1);
1430 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1431 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1432 Add(G[0].r_offset - Offset);
1433 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001434 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001435 Add(G[0].r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001436 Addend = G[0].r_addend;
1437 }
1438
1439 // The remaining relocations.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001440 Add(G.size() - 1);
1441 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1442 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1443 Add(Config->Wordsize);
1444 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001445 if (Config->IsRela) {
1446 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001447 Add(I->r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001448 Addend = I->r_addend;
1449 }
1450 }
1451
1452 Offset = G.back().r_offset;
1453 }
1454
1455 // Now the ungrouped relatives.
1456 if (!UngroupedRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001457 Add(UngroupedRelatives.size());
1458 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1459 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001460 for (Elf_Rela &R : UngroupedRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001461 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001462 Offset = R.r_offset;
1463 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001464 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001465 Addend = R.r_addend;
1466 }
1467 }
1468 }
1469
1470 // Finally the non-relative relocations.
1471 std::sort(NonRelatives.begin(), NonRelatives.end(),
1472 [](const Elf_Rela &A, const Elf_Rela &B) {
1473 return A.r_offset < B.r_offset;
1474 });
1475 if (!NonRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001476 Add(NonRelatives.size());
1477 Add(HasAddendIfRela);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001478 for (Elf_Rela &R : NonRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001479 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001480 Offset = R.r_offset;
Rui Ueyama04c821c2017-12-08 02:20:50 +00001481 Add(R.r_info);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001482 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001483 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001484 Addend = R.r_addend;
1485 }
1486 }
1487 }
1488
1489 // Returns whether the section size changed. We need to keep recomputing both
1490 // section layout and the contents of this section until the size converges
1491 // because changing this section's size can affect section layout, which in
1492 // turn can affect the sizes of the LEB-encoded integers stored in this
1493 // section.
1494 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001495}
1496
George Rimarf45f6812017-05-16 08:53:30 +00001497SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001498 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001499 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001500 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001501 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001502 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001503
1504// Orders symbols according to their positions in the GOT,
1505// in compliance with MIPS ABI rules.
1506// See "Global Offset Table" in Chapter 5 in the following document
1507// for detailed description:
1508// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001509static bool sortMipsSymbols(const SymbolTableEntry &L,
1510 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001511 // Sort entries related to non-local preemptible symbols by GOT indexes.
1512 // All other entries go to the first part of GOT in arbitrary order.
Zachary Turnera104d552017-11-03 22:33:49 +00001513 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1514 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001515 if (LIsInLocalGot || RIsInLocalGot)
1516 return !RIsInLocalGot;
Zachary Turnera104d552017-11-03 22:33:49 +00001517 return L.Sym->GotIndex < R.Sym->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001518}
1519
George Rimarf45f6812017-05-16 08:53:30 +00001520void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001521 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001522
Rui Ueyama6e967342017-02-28 03:29:12 +00001523 // If it is a .dynsym, there should be no local symbols, but we need
1524 // to do a few things for the dynamic linker.
1525 if (this->Type == SHT_DYNSYM) {
1526 // Section's Info field has the index of the first non-local symbol.
1527 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001528 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001529
George Rimarf45f6812017-05-16 08:53:30 +00001530 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001531 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001532 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001533 } else if (Config->EMachine == EM_MIPS) {
1534 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1535 }
1536
1537 size_t I = 0;
Zachary Turnera104d552017-11-03 22:33:49 +00001538 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001539 return;
Peter Smith55865432017-02-20 11:12:33 +00001540 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001541}
Peter Smith55865432017-02-20 11:12:33 +00001542
George Rimar0d6f30e2017-10-18 13:06:18 +00001543// The ELF spec requires that all local symbols precede global symbols, so we
1544// sort symbol entries in this function. (For .dynsym, we don't do that because
1545// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001546void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001547 if (this->Type == SHT_DYNSYM)
1548 return;
1549 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001550 auto It = std::stable_partition(
1551 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
Zachary Turnera104d552017-11-03 22:33:49 +00001552 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
Rui Ueyama6e967342017-02-28 03:29:12 +00001553 });
1554 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001555 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001556}
1557
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001558void SymbolTableBaseSection::addSymbol(Symbol *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001559 // Adding a local symbol to a .dynsym is a bug.
1560 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001561
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001562 bool HashIt = B->isLocal();
1563 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001564}
1565
Rui Ueyama48882242017-11-04 00:31:04 +00001566size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
George Rimar5d6efd12017-09-27 09:08:53 +00001567 // Initializes symbol lookup tables lazily. This is used only
1568 // for -r or -emit-relocs.
1569 llvm::call_once(OnceFlag, [&] {
1570 SymbolIndexMap.reserve(Symbols.size());
1571 size_t I = 0;
1572 for (const SymbolTableEntry &E : Symbols) {
Zachary Turnera104d552017-11-03 22:33:49 +00001573 if (E.Sym->Type == STT_SECTION)
1574 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001575 else
Zachary Turnera104d552017-11-03 22:33:49 +00001576 SymbolIndexMap[E.Sym] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001577 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001578 });
George Rimar5d6efd12017-09-27 09:08:53 +00001579
1580 // Section symbols are mapped based on their output sections
1581 // to maintain their semantics.
Rui Ueyama48882242017-11-04 00:31:04 +00001582 if (Sym->Type == STT_SECTION)
1583 return SectionIndexMap.lookup(Sym->getOutputSection());
1584 return SymbolIndexMap.lookup(Sym);
George Rimar190bac52017-01-23 14:07:23 +00001585}
1586
George Rimarf45f6812017-05-16 08:53:30 +00001587template <class ELFT>
1588SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1589 : SymbolTableBaseSection(StrTabSec) {
1590 this->Entsize = sizeof(Elf_Sym);
1591}
1592
Rui Ueyama1f032532017-02-28 01:56:36 +00001593// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001594template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001595 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001596 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001597 Buf += sizeof(Elf_Sym);
1598
Eugene Leviant9230db92016-11-17 09:16:34 +00001599 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001600
Rui Ueyama1f032532017-02-28 01:56:36 +00001601 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001602 Symbol *Sym = Ent.Sym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001603
Rui Ueyama1b003182017-02-28 19:22:09 +00001604 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001605 ESym->st_other = 0;
Rui Ueyama48882242017-11-04 00:31:04 +00001606 if (Sym->isLocal()) {
1607 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
Rui Ueyama1f032532017-02-28 01:56:36 +00001608 } else {
Rui Ueyama48882242017-11-04 00:31:04 +00001609 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1610 ESym->setVisibility(Sym->Visibility);
Rui Ueyama1f032532017-02-28 01:56:36 +00001611 }
1612
1613 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001614
Rui Ueyama1b003182017-02-28 19:22:09 +00001615 // Set a section index.
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001616 BssSection *CommonSec = nullptr;
1617 if (!Config->DefineCommon)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001618 if (auto *D = dyn_cast<Defined>(Sym))
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001619 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1620 if (CommonSec)
1621 ESym->st_shndx = SHN_COMMON;
1622 else if (const OutputSection *OutSec = Sym->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001623 ESym->st_shndx = OutSec->SectionIndex;
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001624 else if (isa<Defined>(Sym))
Eugene Leviant9230db92016-11-17 09:16:34 +00001625 ESym->st_shndx = SHN_ABS;
George Rimar2727ce22017-10-06 09:56:24 +00001626 else
1627 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001628
George Rimardbe843d2017-06-28 09:51:33 +00001629 // Copy symbol size if it is a defined symbol. st_size is not significant
1630 // for undefined symbols, so whether copying it or not is up to us if that's
1631 // the case. We'll leave it as zero because by not setting a value, we can
1632 // get the exact same outputs for two sets of input files that differ only
1633 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001634 if (ESym->st_shndx == SHN_UNDEF)
1635 ESym->st_size = 0;
1636 else
Rui Ueyama48882242017-11-04 00:31:04 +00001637 ESym->st_size = Sym->getSize();
George Rimardbe843d2017-06-28 09:51:33 +00001638
Rui Ueyama1b003182017-02-28 19:22:09 +00001639 // st_value is usually an address of a symbol, but that has a
1640 // special meaining for uninstantiated common symbols (this can
1641 // occur if -r is given).
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001642 if (CommonSec)
1643 ESym->st_value = CommonSec->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001644 else
Rui Ueyama48882242017-11-04 00:31:04 +00001645 ESym->st_value = Sym->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001646
Rui Ueyama1f032532017-02-28 01:56:36 +00001647 ++ESym;
1648 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001649
Rui Ueyama1f032532017-02-28 01:56:36 +00001650 // On MIPS we need to mark symbol which has a PLT entry and requires
1651 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1652 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1653 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1654 if (Config->EMachine == EM_MIPS) {
1655 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1656
1657 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001658 Symbol *Sym = Ent.Sym;
1659 if (Sym->isInPlt() && Sym->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001660 ESym->st_other |= STO_MIPS_PLT;
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001661 if (isMicroMips()) {
1662 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1663 // defined microMIPS symbols and shared symbols with PLT record.
1664 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1665 (Sym->isShared() && Sym->NeedsPltAddr)) {
1666 if (StrTabSec.isDynamic())
1667 ESym->st_value |= 1;
1668 ESym->st_other |= STO_MIPS_MICROMIPS;
1669 }
1670 }
Rui Ueyama1f032532017-02-28 01:56:36 +00001671 if (Config->Relocatable)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001672 if (auto *D = dyn_cast<Defined>(Sym))
Rui Ueyama7957b082017-11-07 00:04:22 +00001673 if (isMipsPIC<ELFT>(D))
Rui Ueyama1f032532017-02-28 01:56:36 +00001674 ESym->st_other |= STO_MIPS_PIC;
1675 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001676 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001677 }
1678}
1679
Rui Ueyamae4120632017-02-28 22:05:13 +00001680// .hash and .gnu.hash sections contain on-disk hash tables that map
1681// symbol names to their dynamic symbol table indices. Their purpose
1682// is to help the dynamic linker resolve symbols quickly. If ELF files
1683// don't have them, the dynamic linker has to do linear search on all
1684// dynamic symbols, which makes programs slower. Therefore, a .hash
1685// section is added to a DSO by default. A .gnu.hash is added if you
1686// give the -hash-style=gnu or -hash-style=both option.
1687//
1688// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1689// Each ELF file has a list of DSOs that the ELF file depends on and a
1690// list of dynamic symbols that need to be resolved from any of the
1691// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1692// where m is the number of DSOs and n is the number of dynamic
1693// symbols. For modern large programs, both m and n are large. So
1694// making each step faster by using hash tables substiantially
1695// improves time to load programs.
1696//
1697// (Note that this is not the only way to design the shared library.
1698// For instance, the Windows DLL takes a different approach. On
1699// Windows, each dynamic symbol has a name of DLL from which the symbol
1700// has to be resolved. That makes the cost of symbol resolution O(n).
1701// This disables some hacky techniques you can use on Unix such as
1702// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1703//
1704// Due to historical reasons, we have two different hash tables, .hash
1705// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1706// and better version of .hash. .hash is just an on-disk hash table, but
1707// .gnu.hash has a bloom filter in addition to a hash table to skip
1708// DSOs very quickly. If you are sure that your dynamic linker knows
1709// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1710// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001711GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001712 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1713}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001714
George Rimarf45f6812017-05-16 08:53:30 +00001715void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001716 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001717
Rui Ueyama517366c2018-01-19 23:54:31 +00001718 // Computes bloom filter size in word size. We want to allocate 12
Rui Ueyamae13373b2017-03-01 02:51:42 +00001719 // bits for each symbol. It must be a power of two.
Rui Ueyama517366c2018-01-19 23:54:31 +00001720 if (Symbols.empty()) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001721 MaskWords = 1;
Rui Ueyama517366c2018-01-19 23:54:31 +00001722 } else {
1723 uint64_t NumBits = Symbols.size() * 12;
1724 MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8));
1725 }
Rui Ueyamae13373b2017-03-01 02:51:42 +00001726
George Rimar5f73bc92017-03-29 15:23:28 +00001727 Size = 16; // Header
1728 Size += Config->Wordsize * MaskWords; // Bloom filter
1729 Size += NBuckets * 4; // Hash buckets
1730 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001731}
1732
George Rimarf45f6812017-05-16 08:53:30 +00001733void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamac4e50bf2017-12-06 00:49:48 +00001734 // The output buffer is not guaranteed to be zero-cleared because we pre-
1735 // fill executable sections with trap instructions. This is a precaution
1736 // for that case, which happens only when -no-rosegment is given.
1737 memset(Buf, 0, Size);
1738
Rui Ueyamae13373b2017-03-01 02:51:42 +00001739 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001740 write32(Buf, NBuckets);
1741 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1742 write32(Buf + 8, MaskWords);
Rui Ueyamaba32e732018-03-19 23:04:13 +00001743 write32(Buf + 12, Shift2);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001744 Buf += 16;
1745
Rui Ueyama7986b452017-03-01 18:09:09 +00001746 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001747 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001748 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001749 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001750}
1751
Rui Ueyama7986b452017-03-01 18:09:09 +00001752// This function writes a 2-bit bloom filter. This bloom filter alone
1753// usually filters out 80% or more of all symbol lookups [1].
1754// The dynamic linker uses the hash table only when a symbol is not
1755// filtered out by a bloom filter.
1756//
1757// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1758// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001759void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama2f8af792018-01-20 00:14:16 +00001760 unsigned C = Config->Is64 ? 64 : 32;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001761 for (const Entry &Sym : Symbols) {
1762 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001763 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1764 Val |= uint64_t(1) << (Sym.Hash % C);
Rui Ueyamaba32e732018-03-19 23:04:13 +00001765 Val |= uint64_t(1) << ((Sym.Hash >> Shift2) % C);
George Rimar5f73bc92017-03-29 15:23:28 +00001766 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001767 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001768}
1769
George Rimarf45f6812017-05-16 08:53:30 +00001770void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001771 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rafael Espindolaf9f2abe2017-12-07 18:51:19 +00001772 uint32_t OldBucket = -1;
George Rimar5f73bc92017-03-29 15:23:28 +00001773 uint32_t *Values = Buckets + NBuckets;
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001774 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001775 // Write a hash value. It represents a sequence of chains that share the
1776 // same hash modulo value. The last element of each chain is terminated by
1777 // LSB 1.
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001778 uint32_t Hash = I->Hash;
1779 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
1780 Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
1781 write32(Values++, Hash);
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001782
1783 if (I->BucketIdx == OldBucket)
1784 continue;
1785 // Write a hash bucket. Hash buckets contain indices in the following hash
1786 // value table.
1787 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1788 OldBucket = I->BucketIdx;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001789 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001790}
1791
1792static uint32_t hashGnu(StringRef Name) {
1793 uint32_t H = 5381;
1794 for (uint8_t C : Name)
1795 H = (H << 5) + H + C;
1796 return H;
1797}
1798
1799// Add symbols to this symbol hash table. Note that this function
1800// destructively sort a given vector -- which is needed because
1801// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001802void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001803 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1804 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001805 std::vector<SymbolTableEntry>::iterator Mid =
1806 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001807 // Shared symbols that this executable preempts are special. The dynamic
1808 // linker has to look them up, so they have to be in the hash table.
Zachary Turnera104d552017-11-03 22:33:49 +00001809 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001810 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001811 return !S.Sym->isDefined();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001812 });
George Rimar2ab93622018-03-14 08:52:39 +00001813
Rui Ueyama4e6b8222018-03-14 19:01:00 +00001814 // We chose load factor 4 for the on-disk hash table. For each hash
1815 // collision, the dynamic linker will compare a uint32_t hash value.
1816 // Since the integer comparison is quite fast, we believe we can
1817 // make the load factor even larger. 4 is just a conservative choice.
1818 //
1819 // Note that we don't want to create a zero-sized hash table because
1820 // Android loader as of 2018 doesn't like a .gnu.hash containing such
1821 // table. If that's the case, we create a hash table with one unused
1822 // dummy slot.
George Rimar2ab93622018-03-14 08:52:39 +00001823 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
1824
Eugene Leviantbe809a72016-11-18 06:44:18 +00001825 if (Mid == V.end())
1826 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001827
Rui Ueyama22788262017-12-02 00:37:13 +00001828 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1829 Symbol *B = Ent.Sym;
1830 uint32_t Hash = hashGnu(B->getName());
1831 uint32_t BucketIdx = Hash % NBuckets;
1832 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
1833 }
1834
1835 std::stable_sort(
1836 Symbols.begin(), Symbols.end(),
1837 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
Eugene Leviantbe809a72016-11-18 06:44:18 +00001838
1839 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001840 for (const Entry &Ent : Symbols)
Rui Ueyama48882242017-11-04 00:31:04 +00001841 V.push_back({Ent.Sym, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001842}
1843
George Rimaraaf54712017-09-27 09:14:59 +00001844HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001845 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1846 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001847}
1848
George Rimaraaf54712017-09-27 09:14:59 +00001849void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001850 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001851
George Rimar67c60722017-07-18 11:55:35 +00001852 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001853 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001854
1855 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001856 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001857 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001858}
1859
George Rimaraaf54712017-09-27 09:14:59 +00001860void HashTableSection::writeTo(uint8_t *Buf) {
Shoaib Meenaid79bbf42018-01-11 06:57:01 +00001861 // See comment in GnuHashTableSection::writeTo.
1862 memset(Buf, 0, Size);
1863
George Rimar69b17c32017-05-16 10:04:42 +00001864 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001865
George Rimaraaf54712017-09-27 09:14:59 +00001866 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00001867 write32(P++, NumSymbols); // nbucket
1868 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001869
George Rimaraaf54712017-09-27 09:14:59 +00001870 uint32_t *Buckets = P;
1871 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001872
George Rimar69b17c32017-05-16 10:04:42 +00001873 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Rui Ueyama48882242017-11-04 00:31:04 +00001874 Symbol *Sym = S.Sym;
1875 StringRef Name = Sym->getName();
1876 unsigned I = Sym->DynsymIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001877 uint32_t Hash = hashSysV(Name) % NumSymbols;
1878 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00001879 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001880 }
1881}
1882
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00001883PltSection::PltSection(bool IsIplt)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001884 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00001885 HeaderSize(IsIplt ? 0 : Target->PltHeaderSize), IsIplt(IsIplt) {
Rui Ueyama0cc14832017-06-28 17:05:39 +00001886 // The PLT needs to be writable on SPARC as the dynamic linker will
1887 // modify the instructions in the PLT entries.
1888 if (Config->EMachine == EM_SPARCV9)
1889 this->Flags |= SHF_WRITE;
1890}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001891
George Rimardfc020e2017-03-17 11:01:57 +00001892void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001893 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1894 // linker to resolve dynsyms at runtime. Write such code.
George Rimar9fc2c642018-01-12 09:35:57 +00001895 if (!IsIplt)
Peter Smithf09245a2017-02-09 10:56:15 +00001896 Target->writePltHeader(Buf);
1897 size_t Off = HeaderSize;
1898 // The IPlt is immediately after the Plt, account for this in RelOff
1899 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001900
1901 for (auto &I : Entries) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001902 const Symbol *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001903 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001904 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001905 uint64_t Plt = this->getVA() + Off;
1906 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1907 Off += Target->PltEntrySize;
1908 }
1909}
1910
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001911template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001912 Sym.PltIndex = Entries.size();
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001913 RelocationBaseSection *PltRelocSection = InX::RelaPlt;
George Rimar9fc2c642018-01-12 09:35:57 +00001914 if (IsIplt) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001915 PltRelocSection = InX::RelaIplt;
Peter Smithf09245a2017-02-09 10:56:15 +00001916 Sym.IsInIplt = true;
1917 }
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001918 unsigned RelOff =
1919 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001920 Entries.push_back(std::make_pair(&Sym, RelOff));
1921}
1922
George Rimardfc020e2017-03-17 11:01:57 +00001923size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001924 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001925}
1926
Peter Smith96943762017-01-25 10:31:16 +00001927// Some architectures such as additional symbols in the PLT section. For
1928// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001929void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001930 // The PLT may have symbols defined for the Header, the IPLT has no header
George Rimar9fc2c642018-01-12 09:35:57 +00001931 if (!IsIplt)
Rafael Espindola1037eef2017-12-19 23:59:35 +00001932 Target->addPltHeaderSymbols(*this);
Peter Smithf09245a2017-02-09 10:56:15 +00001933 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001934 for (size_t I = 0; I < Entries.size(); ++I) {
Rafael Espindola1037eef2017-12-19 23:59:35 +00001935 Target->addPltSymbols(*this, Off);
Peter Smith96943762017-01-25 10:31:16 +00001936 Off += Target->PltEntrySize;
1937 }
1938}
1939
George Rimardfc020e2017-03-17 11:01:57 +00001940unsigned PltSection::getPltRelocOff() const {
George Rimar9fc2c642018-01-12 09:35:57 +00001941 return IsIplt ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001942}
1943
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001944// The string hash function for .gdb_index.
1945static uint32_t computeGdbHash(StringRef S) {
1946 uint32_t H = 0;
1947 for (uint8_t C : S)
1948 H = H * 67 + tolower(C) - 113;
1949 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001950}
1951
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001952static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1953 std::vector<GdbIndexChunk::CuEntry> Ret;
1954 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1955 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001956 return Ret;
1957}
1958
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001959static std::vector<GdbIndexChunk::AddressEntry>
1960readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1961 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001962
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001963 uint32_t CuIdx = 0;
1964 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001965 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001966 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001967
George Rimar35e846e2017-03-21 08:19:34 +00001968 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001969 for (DWARFAddressRange &R : Ranges) {
1970 InputSectionBase *S = Sections[R.SectionIndex];
1971 if (!S || S == &InputSection::Discarded || !S->Live)
1972 continue;
1973 // Range list with zero size has no effect.
1974 if (R.LowPC == R.HighPC)
1975 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001976 auto *IS = cast<InputSection>(S);
1977 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001978 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001979 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001980 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001981 }
1982 return Ret;
1983}
1984
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001985static std::vector<GdbIndexChunk::NameTypeEntry>
1986readPubNamesAndTypes(DWARFContext &Dwarf) {
1987 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1988 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001989
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001990 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1991 for (StringRef Sec : {Sec1, Sec2}) {
1992 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001993 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1994 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1995 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1996 Ret.push_back({S, Ent.Descriptor.toBits()});
1997 }
1998 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001999 }
2000 return Ret;
2001}
2002
George Rimar86665622017-06-07 16:59:11 +00002003static std::vector<InputSection *> getDebugInfoSections() {
2004 std::vector<InputSection *> Ret;
2005 for (InputSectionBase *S : InputSections)
2006 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00002007 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00002008 Ret.push_back(IS);
2009 return Ret;
2010}
2011
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002012void GdbIndexSection::fixCuIndex() {
2013 uint32_t Idx = 0;
2014 for (GdbIndexChunk &Chunk : Chunks) {
2015 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
2016 Ent.CuIndex += Idx;
2017 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00002018 }
2019}
2020
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002021std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2022 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002023 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002024 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002025
2026 for (GdbIndexChunk &Chunk : Chunks) {
2027 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002028 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002029 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002030 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2031 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002032 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002033 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002034
2035 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2036 // duplicate entries, so we want to dedup them.
2037 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2038 uint32_t Val = (Ent.Type << 24) | Idx;
2039 if (Vec.empty() || Vec.back() != Val)
2040 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002041 }
2042 Idx += Chunk.CompilationUnits.size();
2043 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002044
2045 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002046 return Ret;
2047}
George Rimar8b547392016-12-15 09:08:13 +00002048
Rafael Espindola300b3862017-07-12 23:56:53 +00002049template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002050 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002051 std::vector<InputSection *> Sections = getDebugInfoSections();
2052 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002053
George Rimar2d23da02017-08-01 14:57:13 +00002054 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002055 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2056 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2057
2058 Chunks[I].DebugInfoSec = Sections[I];
2059 Chunks[I].CompilationUnits = readCuList(Dwarf);
2060 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2061 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002062 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002063
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002064 // .debug_gnu_pub{names,types} are useless in executables.
2065 // They are present in input object files solely for creating
2066 // a .gdb_index. So we can remove it from the output.
2067 for (InputSectionBase *S : InputSections)
2068 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2069 S->Live = false;
2070
2071 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002072 return make<GdbIndexSection>(std::move(Chunks));
2073}
2074
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002075static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002076 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002077 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002078 Ret += D.CompilationUnits.size();
2079 return Ret;
2080}
George Rimarec02b8d2016-12-15 12:07:53 +00002081
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002082static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002083 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002084 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002085 Ret += D.AddressAreas.size();
2086 return Ret;
2087}
2088
2089std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002090 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2091 if (Size < 1024)
2092 Size = 1024;
2093
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002094 uint32_t Mask = Size - 1;
2095 std::vector<GdbSymbol *> Ret(Size);
2096
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002097 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002098 GdbSymbol *Sym = KV.second;
2099 uint32_t I = Sym->NameHash & Mask;
2100 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2101
2102 while (Ret[I])
2103 I = (I + Step) & Mask;
2104 Ret[I] = Sym;
2105 }
George Rimar86665622017-06-07 16:59:11 +00002106 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002107}
2108
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002109GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002110 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002111 fixCuIndex();
2112 CuVectors = createCuVectors();
2113 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002114
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002115 // Compute offsets early to know the section size.
2116 // Each chunk size needs to be in sync with what we write in writeTo.
2117 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2118 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2119 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002120
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002121 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002122 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002123 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002124 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002125 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002126 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002127}
2128
George Rimar35e846e2017-03-21 08:19:34 +00002129size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002130 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002131}
2132
George Rimar35e846e2017-03-21 08:19:34 +00002133void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002134 // Write the section header.
2135 write32le(Buf, 7);
2136 write32le(Buf + 4, CuListOffset);
2137 write32le(Buf + 8, CuTypesOffset);
2138 write32le(Buf + 12, CuTypesOffset);
2139 write32le(Buf + 16, SymtabOffset);
2140 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002141 Buf += 24;
2142
2143 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002144 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002145 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002146 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002147 write64le(Buf + 8, Cu.CuLength);
2148 Buf += 16;
2149 }
Eugene Levianta113a412016-11-21 09:24:43 +00002150 }
George Rimar8b547392016-12-15 09:08:13 +00002151
2152 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002153 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002154 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
Rafael Espindola4f058a22018-03-24 00:35:11 +00002155 uint64_t BaseAddr = E.Section->getVA(0);
George Rimar86665622017-06-07 16:59:11 +00002156 write64le(Buf, BaseAddr + E.LowAddress);
2157 write64le(Buf + 8, BaseAddr + E.HighAddress);
2158 write32le(Buf + 16, E.CuIndex);
2159 Buf += 20;
2160 }
George Rimar8b547392016-12-15 09:08:13 +00002161 }
George Rimarec02b8d2016-12-15 12:07:53 +00002162
2163 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002164 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002165 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002166 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2167 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002168 }
2169 Buf += 8;
2170 }
2171
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002172 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002173 for (ArrayRef<uint32_t> Vec : CuVectors) {
2174 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002175 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002176 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002177 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002178 Buf += 4;
2179 }
2180 }
2181
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002182 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002183 for (auto &KV : Symbols) {
2184 CachedHashStringRef S = KV.first;
2185 GdbSymbol *Sym = KV.second;
2186 size_t Off = Sym->NameOffset;
2187 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002188 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002189 }
Eugene Levianta113a412016-11-21 09:24:43 +00002190}
2191
George Rimar67c60722017-07-18 11:55:35 +00002192bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002193
Rui Ueyama02551ab2017-10-27 03:14:24 +00002194EhFrameHeader::EhFrameHeader()
Rafael Espindola6b2b4502018-01-23 05:23:23 +00002195 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002196
2197// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2198// Each entry of the search table consists of two values,
2199// the starting PC from where FDEs covers, and the FDE's address.
2200// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002201void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002202 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002203
Rui Ueyama02551ab2017-10-27 03:14:24 +00002204 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002205
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002206 // Sort the FDE list by their PC and uniqueify. Usually there is only
2207 // one FDE for a PC (i.e. function), but if ICF merges two functions
2208 // into one, there can be more than one FDEs pointing to the address.
2209 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2210 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2211 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2212 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2213
2214 Buf[0] = 1;
2215 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2216 Buf[2] = DW_EH_PE_udata4;
2217 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002218 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2219 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002220 Buf += 12;
2221
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002222 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002223 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002224 write32(Buf, Fde.Pc - VA);
2225 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002226 Buf += 8;
2227 }
2228}
2229
Rui Ueyama02551ab2017-10-27 03:14:24 +00002230size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002231 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002232 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002233}
2234
Rui Ueyama02551ab2017-10-27 03:14:24 +00002235bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002236
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002237template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002238VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002239 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2240 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002241
2242static StringRef getFileDefName() {
2243 if (!Config->SoName.empty())
2244 return Config->SoName;
2245 return Config->OutputFile;
2246}
2247
Rui Ueyama945055a2017-02-27 03:07:41 +00002248template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002249 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002250 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002251 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002252
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002253 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002254
2255 // sh_info should be set to the number of definitions. This fact is missed in
2256 // documentation, but confirmed by binutils community:
2257 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002258 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002259}
2260
2261template <class ELFT>
2262void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2263 StringRef Name, size_t NameOff) {
2264 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2265 Verdef->vd_version = 1;
2266 Verdef->vd_cnt = 1;
2267 Verdef->vd_aux = sizeof(Elf_Verdef);
2268 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2269 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2270 Verdef->vd_ndx = Index;
2271 Verdef->vd_hash = hashSysV(Name);
2272
2273 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2274 Verdaux->vda_name = NameOff;
2275 Verdaux->vda_next = 0;
2276}
2277
2278template <class ELFT>
2279void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2280 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2281
2282 for (VersionDefinition &V : Config->VersionDefinitions) {
2283 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2284 writeOne(Buf, V.Id, V.Name, V.NameOff);
2285 }
2286
2287 // Need to terminate the last version definition.
2288 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2289 Verdef->vd_next = 0;
2290}
2291
2292template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2293 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2294}
2295
2296template <class ELFT>
2297VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002298 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002299 ".gnu.version") {
2300 this->Entsize = sizeof(Elf_Versym);
2301}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002302
Rui Ueyama945055a2017-02-27 03:07:41 +00002303template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002304 // At the moment of june 2016 GNU docs does not mention that sh_link field
2305 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002306 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002307}
2308
2309template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002310 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002311}
2312
2313template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2314 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002315 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Zachary Turnera104d552017-11-03 22:33:49 +00002316 OutVersym->vs_index = S.Sym->VersionId;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002317 ++OutVersym;
2318 }
2319}
2320
George Rimar11992c862016-11-25 08:05:41 +00002321template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2322 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2323}
2324
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002325template <class ELFT>
2326VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002327 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2328 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002329 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2330 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2331 // First identifiers are reserved by verdef section if it exist.
2332 NextIndex = getVerDefNum() + 1;
2333}
2334
2335template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002336void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002337 SharedFile<ELFT> &File = SS->getFile<ELFT>();
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002338 if (SS->VerdefIndex == VER_NDX_GLOBAL) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002339 SS->VersionId = VER_NDX_GLOBAL;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002340 return;
2341 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002342
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002343 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2344 // to create one by adding it to our needed list and creating a dynstr entry
2345 // for the soname.
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002346 if (File.VerdefMap.empty())
2347 Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)});
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002348 const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex];
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002349 typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver];
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002350
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002351 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2352 // prepare to create one by allocating a version identifier and creating a
2353 // dynstr entry for the version name.
2354 if (NV.Index == 0) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002355 NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() +
Rafael Espindola895aea62017-05-11 22:02:41 +00002356 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002357 NV.Index = NextIndex++;
2358 }
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002359 SS->VersionId = NV.Index;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002360}
2361
2362template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2363 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2364 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2365 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2366
2367 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2368 // Create an Elf_Verneed for this DSO.
2369 Verneed->vn_version = 1;
2370 Verneed->vn_cnt = P.first->VerdefMap.size();
2371 Verneed->vn_file = P.second;
2372 Verneed->vn_aux =
2373 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2374 Verneed->vn_next = sizeof(Elf_Verneed);
2375 ++Verneed;
2376
2377 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2378 // VerdefMap, which will only contain references to needed version
2379 // definitions. Each Elf_Vernaux is based on the information contained in
2380 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2381 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2382 // data structures within a single input file.
2383 for (auto &NV : P.first->VerdefMap) {
2384 Vernaux->vna_hash = NV.first->vd_hash;
2385 Vernaux->vna_flags = 0;
2386 Vernaux->vna_other = NV.second.Index;
2387 Vernaux->vna_name = NV.second.StrTab;
2388 Vernaux->vna_next = sizeof(Elf_Vernaux);
2389 ++Vernaux;
2390 }
2391
2392 Vernaux[-1].vna_next = 0;
2393 }
2394 Verneed[-1].vn_next = 0;
2395}
2396
Rui Ueyama945055a2017-02-27 03:07:41 +00002397template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002398 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2399 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002400}
2401
2402template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2403 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2404 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2405 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2406 return Size;
2407}
2408
George Rimar11992c862016-11-25 08:05:41 +00002409template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2410 return getNeedNum() == 0;
2411}
2412
Rafael Espindola6119b862017-03-06 20:23:56 +00002413void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002414 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002415 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002416}
2417
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002418MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2419 uint64_t Flags, uint32_t Alignment)
2420 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2421 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002422
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002423size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2424
2425void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002426
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002427void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002428 // Add all string pieces to the string table builder to create section
2429 // contents.
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 Builder.add(Sec->getData(I));
2434
2435 // Fix the string table content. After this, the contents will never change.
2436 Builder.finalize();
2437
2438 // finalize() fixed tail-optimized strings, so we can now get
2439 // offsets of strings. Get an offset for each string and save it
2440 // to a corresponding StringPiece for easy access.
Rafael Espindola6cd7af52018-04-03 21:38:18 +00002441 for (MergeInputSection *Sec : Sections) {
2442 Sec->OffsetMap.reserve(Sec->Pieces.size());
2443 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2444 SectionPiece &P = Sec->Pieces[I];
2445 Sec->OffsetMap[P.InputOff] = I;
2446 if (P.Live)
2447 P.OutputOff = Builder.getOffset(Sec->getData(I));
2448 }
2449 }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002450}
2451
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002452void MergeNoTailSection::writeTo(uint8_t *Buf) {
2453 for (size_t I = 0; I < NumShards; ++I)
2454 Shards[I].write(Buf + ShardOffsets[I]);
2455}
2456
2457// This function is very hot (i.e. it can take several seconds to finish)
2458// because sometimes the number of inputs is in an order of magnitude of
2459// millions. So, we use multi-threading.
2460//
2461// For any strings S and T, we know S is not mergeable with T if S's hash
2462// value is different from T's. If that's the case, we can safely put S and
2463// T into different string builders without worrying about merge misses.
2464// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002465void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002466 // Initializes string table builders.
2467 for (size_t I = 0; I < NumShards; ++I)
2468 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2469
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002470 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2471 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002472 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002473 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002474 Concurrency =
2475 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002476
2477 // Add section pieces to the builders.
2478 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2479 for (MergeInputSection *Sec : Sections) {
2480 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
Rui Ueyama95bf5092017-10-21 23:20:13 +00002481 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Dimitry Andric656714a2018-01-11 08:03:22 +00002482 if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002483 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002484 }
2485 }
2486 });
2487
2488 // Compute an in-section offset for each shard.
2489 size_t Off = 0;
2490 for (size_t I = 0; I < NumShards; ++I) {
2491 Shards[I].finalizeInOrder();
2492 if (Shards[I].getSize() > 0)
2493 Off = alignTo(Off, Alignment);
2494 ShardOffsets[I] = Off;
2495 Off += Shards[I].getSize();
2496 }
2497 Size = Off;
2498
2499 // So far, section pieces have offsets from beginning of shards, but
2500 // we want offsets from beginning of the whole section. Fix them.
2501 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola6cd7af52018-04-03 21:38:18 +00002502 Sec->OffsetMap.reserve(Sec->Pieces.size());
2503 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2504 SectionPiece &P = Sec->Pieces[I];
2505 Sec->OffsetMap[P.InputOff] = I;
2506 if (P.Live)
2507 P.OutputOff += ShardOffsets[getShardId(P.Hash)];
2508 }
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002509 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002510}
2511
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002512static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2513 uint32_t Type,
2514 uint64_t Flags,
2515 uint32_t Alignment) {
2516 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2517 if (ShouldTailMerge)
2518 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2519 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002520}
2521
Rui Ueyamaac114d22018-02-12 21:56:14 +00002522// Debug sections may be compressed by zlib. Decompress if exists.
Rui Ueyama2b714b52017-10-11 03:12:53 +00002523void elf::decompressSections() {
2524 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2525 if (Sec->Live)
Rui Ueyamaac114d22018-02-12 21:56:14 +00002526 Sec->maybeDecompress();
Rui Ueyama2b714b52017-10-11 03:12:53 +00002527 });
2528}
2529
2530// This function scans over the inputsections to create mergeable
2531// synthetic sections.
2532//
2533// It removes MergeInputSections from the input section array and adds
2534// new synthetic sections at the location of the first input section
2535// that it replaces. It then finalizes each synthetic section in order
2536// to compute an output offset for each piece of each input section.
2537void elf::mergeSections() {
2538 // splitIntoPieces needs to be called on each MergeInputSection
2539 // before calling finalizeContents(). Do that first.
2540 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2541 if (Sec->Live)
2542 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2543 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002544 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002545
2546 std::vector<MergeSyntheticSection *> MergeSections;
2547 for (InputSectionBase *&S : InputSections) {
2548 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2549 if (!MS)
2550 continue;
2551
2552 // We do not want to handle sections that are not alive, so just remove
2553 // them instead of trying to merge.
2554 if (!MS->Live)
2555 continue;
2556
George Rimar78e27e82017-12-01 09:04:52 +00002557 StringRef OutsecName = getOutputSectionName(MS);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002558 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2559
2560 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002561 // While we could create a single synthetic section for two different
2562 // values of Entsize, it is better to take Entsize into consideration.
2563 //
2564 // With a single synthetic section no two pieces with different Entsize
2565 // could be equal, so we may as well have two sections.
2566 //
2567 // Using Entsize in here also allows us to propagate it to the synthetic
2568 // section.
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002569 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002570 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002571 });
2572 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002573 MergeSyntheticSection *Syn =
2574 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002575 MergeSections.push_back(Syn);
2576 I = std::prev(MergeSections.end());
2577 S = Syn;
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002578 Syn->Entsize = MS->Entsize;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002579 } else {
2580 S = nullptr;
2581 }
2582 (*I)->addSection(MS);
2583 }
Rafael Espindola6cd7af52018-04-03 21:38:18 +00002584 for (auto *MS : MergeSections)
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002585 MS->finalizeContents();
2586
2587 std::vector<InputSectionBase *> &V = InputSections;
2588 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2589}
2590
George Rimar42886c42017-03-15 12:02:31 +00002591MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002592 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2593 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002594
George Rimar90a528b2017-03-21 09:01:39 +00002595ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002596 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002597 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002598
2599// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2600// This section will have been sorted last in the .ARM.exidx table.
2601// This table entry will have the form:
2602// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002603// The sentinel must have the PREL31 value of an address higher than any
2604// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002605void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Igor Kudrinf01caab2017-12-14 06:23:50 +00002606 assert(Highest);
Rafael Espindola4f058a22018-03-24 00:35:11 +00002607 uint64_t S = Highest->getVA(Highest->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002608 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002609 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002610 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002611}
2612
Igor Kudrin5966d152017-12-20 08:56:10 +00002613// The sentinel has to be removed if there are no other .ARM.exidx entries.
2614bool ARMExidxSentinelSection::empty() const {
George Rimar563e4f22018-02-22 09:55:28 +00002615 for (InputSection *IS : getInputSections(getParent()))
2616 if (!isa<ARMExidxSentinelSection>(IS))
2617 return false;
Igor Kudrin5966d152017-12-20 08:56:10 +00002618 return true;
2619}
2620
George Rimar7b827042017-03-16 10:40:50 +00002621ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002622 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002623 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002624 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002625 this->OutSecOff = Off;
2626}
2627
George Rimar7b827042017-03-16 10:40:50 +00002628void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002629 Thunks.push_back(T);
2630 T->addSymbols(*this);
Peter Smith3a52eb02017-02-01 10:26:03 +00002631}
2632
George Rimar7b827042017-03-16 10:40:50 +00002633void ThunkSection::writeTo(uint8_t *Buf) {
Peter Collingbournecebab4a2018-03-28 21:33:31 +00002634 for (Thunk *T : Thunks)
2635 T->writeTo(Buf + T->Offset);
Peter Smith3a52eb02017-02-01 10:26:03 +00002636}
2637
George Rimar7b827042017-03-16 10:40:50 +00002638InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002639 if (Thunks.empty())
2640 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002641 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002642 return T->getTargetInputSection();
2643}
2644
Peter Collingbournec5391ce2018-03-29 22:32:13 +00002645bool ThunkSection::assignOffsets() {
2646 uint64_t Off = 0;
2647 for (Thunk *T : Thunks) {
2648 Off = alignTo(Off, T->Alignment);
2649 T->setOffset(Off);
2650 uint32_t Size = T->size();
2651 T->getThunkTargetSym()->Size = Size;
2652 Off += Size;
2653 }
2654 bool Changed = Off != Size;
2655 Size = Off;
2656 return Changed;
2657}
2658
George Rimar9782ca52017-03-15 15:29:29 +00002659InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002660BssSection *InX::Bss;
2661BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002662BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002663EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002664EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002665SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002666StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002667SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002668InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002669GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002670GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002671GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002672GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002673HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002674IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002675MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002676MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002677PltSection *InX::Plt;
2678PltSection *InX::Iplt;
Rafael Espindola58946cd2017-12-10 19:44:42 +00002679RelocationBaseSection *InX::RelaDyn;
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002680RelocationBaseSection *InX::RelaPlt;
2681RelocationBaseSection *InX::RelaIplt;
George Rimar9782ca52017-03-15 15:29:29 +00002682StringTableSection *InX::ShStrTab;
2683StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002684SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002685
Rafael Espindola300b3862017-07-12 23:56:53 +00002686template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2687template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2688template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2689template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2690
Rui Ueyama572247f2017-10-27 03:13:39 +00002691template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2692template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2693template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2694template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2695
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002696template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2697template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2698template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2699template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
George Rimara9189572017-03-17 16:50:07 +00002700
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002701template class elf::MipsAbiFlagsSection<ELF32LE>;
2702template class elf::MipsAbiFlagsSection<ELF32BE>;
2703template class elf::MipsAbiFlagsSection<ELF64LE>;
2704template class elf::MipsAbiFlagsSection<ELF64BE>;
2705
Simon Atanasyance02cf02016-11-09 21:36:56 +00002706template class elf::MipsOptionsSection<ELF32LE>;
2707template class elf::MipsOptionsSection<ELF32BE>;
2708template class elf::MipsOptionsSection<ELF64LE>;
2709template class elf::MipsOptionsSection<ELF64BE>;
2710
2711template class elf::MipsReginfoSection<ELF32LE>;
2712template class elf::MipsReginfoSection<ELF32BE>;
2713template class elf::MipsReginfoSection<ELF64LE>;
2714template class elf::MipsReginfoSection<ELF64BE>;
2715
Eugene Leviant6380ce22016-11-15 12:26:55 +00002716template class elf::DynamicSection<ELF32LE>;
2717template class elf::DynamicSection<ELF32BE>;
2718template class elf::DynamicSection<ELF64LE>;
2719template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002720
2721template class elf::RelocationSection<ELF32LE>;
2722template class elf::RelocationSection<ELF32BE>;
2723template class elf::RelocationSection<ELF64LE>;
2724template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002725
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002726template class elf::AndroidPackedRelocationSection<ELF32LE>;
2727template class elf::AndroidPackedRelocationSection<ELF32BE>;
2728template class elf::AndroidPackedRelocationSection<ELF64LE>;
2729template class elf::AndroidPackedRelocationSection<ELF64BE>;
2730
Eugene Leviant9230db92016-11-17 09:16:34 +00002731template class elf::SymbolTableSection<ELF32LE>;
2732template class elf::SymbolTableSection<ELF32BE>;
2733template class elf::SymbolTableSection<ELF64LE>;
2734template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002735
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002736template class elf::VersionTableSection<ELF32LE>;
2737template class elf::VersionTableSection<ELF32BE>;
2738template class elf::VersionTableSection<ELF64LE>;
2739template class elf::VersionTableSection<ELF64BE>;
2740
2741template class elf::VersionNeedSection<ELF32LE>;
2742template class elf::VersionNeedSection<ELF32BE>;
2743template class elf::VersionNeedSection<ELF64LE>;
2744template class elf::VersionNeedSection<ELF64BE>;
2745
2746template class elf::VersionDefinitionSection<ELF32LE>;
2747template class elf::VersionDefinitionSection<ELF32BE>;
2748template class elf::VersionDefinitionSection<ELF64LE>;
2749template class elf::VersionDefinitionSection<ELF64BE>;