blob: 4195ed9a2e8fb86260c0f8f0c6a44102901de613 [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"
Simon Atanasyaned9ee692018-06-11 07:24:31 +000032#include "llvm/ADT/SetOperations.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000034#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000035#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000036#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000037#include "llvm/Support/Endian.h"
Peter Collingbourne5c54f152017-10-27 17:49:40 +000038#include "llvm/Support/LEB128.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000039#include "llvm/Support/MD5.h"
40#include "llvm/Support/RandomNumberGenerator.h"
41#include "llvm/Support/SHA1.h"
42#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000043#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000044#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000045
46using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000047using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000048using namespace llvm::ELF;
49using namespace llvm::object;
50using namespace llvm::support;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000051
52using namespace lld;
53using namespace lld::elf;
54
Fangrui Song0c483022018-03-09 18:03:22 +000055using llvm::support::endian::write32le;
56using llvm::support::endian::write64le;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000057
Fangrui Song0c483022018-03-09 18:03:22 +000058constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyama79048e42017-10-27 03:59:34 +000059
Rui Ueyama3da3f062016-11-10 20:20:37 +000060// Returns an LLD version string.
61static ArrayRef<uint8_t> getVersion() {
62 // Check LLD_VERSION first for ease of testing.
Eric Christopher7baac212018-03-20 18:10:30 +000063 // You can get consistent output by using the environment variable.
Rui Ueyama3da3f062016-11-10 20:20:37 +000064 // This is only for testing.
65 StringRef S = getenv("LLD_VERSION");
66 if (S.empty())
67 S = Saver.save(Twine("Linker: ") + getLLDVersion());
68
69 // +1 to include the terminating '\0'.
70 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000071}
Rui Ueyama3da3f062016-11-10 20:20:37 +000072
73// Creates a .comment section containing LLD version info.
74// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000075// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000076// The returned object is a mergeable string section.
Rafael Espindola5c73c492017-12-21 01:21:59 +000077MergeInputSection *elf::createCommentSection() {
78 return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
79 getVersion(), ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +000080}
81
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000082// .MIPS.abiflags section.
83template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +000084MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +000085 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +000086 Flags(Flags) {
87 this->Entsize = sizeof(Elf_Mips_ABIFlags);
88}
Rui Ueyama12f2da82016-11-22 03:57:06 +000089
90template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
91 memcpy(Buf, &Flags, sizeof(Flags));
92}
93
94template <class ELFT>
95MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
96 Elf_Mips_ABIFlags Flags = {};
97 bool Create = false;
98
Rui Ueyama536a2672017-02-27 02:32:08 +000099 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000100 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000101 continue;
102 Sec->Live = false;
103 Create = true;
104
Rui Ueyama25f30882017-10-27 03:25:04 +0000105 std::string Filename = toString(Sec->File);
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000106 const size_t Size = Sec->Data.size();
107 // Older version of BFD (such as the default FreeBSD linker) concatenate
108 // .MIPS.abiflags instead of merging. To allow for this case (or potential
109 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
110 if (Size < sizeof(Elf_Mips_ABIFlags)) {
111 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
112 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000113 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000114 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000115 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000116 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000117 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000118 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000119 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000120 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000121
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000122 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000123 // select the highest number of ISA/Rev/Ext.
124 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
125 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
126 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
127 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
128 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
129 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
130 Flags.ases |= S->ases;
131 Flags.flags1 |= S->flags1;
132 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000133 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000134 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000135
Rui Ueyama12f2da82016-11-22 03:57:06 +0000136 if (Create)
137 return make<MipsAbiFlagsSection<ELFT>>(Flags);
138 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000139}
140
Simon Atanasyance02cf02016-11-09 21:36:56 +0000141// .MIPS.options section.
142template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000143MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000144 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000145 Reginfo(Reginfo) {
146 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
147}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000148
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000149template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
150 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
151 Options->kind = ODK_REGINFO;
152 Options->size = getSize();
153
154 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000155 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000156 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000157}
158
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000159template <class ELFT>
160MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
161 // N64 ABI only.
162 if (!ELFT::Is64Bits)
163 return nullptr;
164
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000165 std::vector<InputSectionBase *> Sections;
166 for (InputSectionBase *Sec : InputSections)
167 if (Sec->Type == SHT_MIPS_OPTIONS)
168 Sections.push_back(Sec);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000169
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000170 if (Sections.empty())
171 return nullptr;
172
173 Elf_Mips_RegInfo Reginfo = {};
174 for (InputSectionBase *Sec : Sections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000175 Sec->Live = false;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000176
Rui Ueyama25f30882017-10-27 03:25:04 +0000177 std::string Filename = toString(Sec->File);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000178 ArrayRef<uint8_t> D = Sec->Data;
179
180 while (!D.empty()) {
181 if (D.size() < sizeof(Elf_Mips_Options)) {
182 error(Filename + ": invalid size of .MIPS.options section");
183 break;
184 }
185
186 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
187 if (Opt->kind == ODK_REGINFO) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000188 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000189 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000190 break;
191 }
192
193 if (!Opt->size)
194 fatal(Filename + ": zero option descriptor size");
195 D = D.slice(Opt->size);
196 }
197 };
198
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000199 return make<MipsOptionsSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000200}
201
202// MIPS .reginfo section.
203template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000204MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000205 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000206 Reginfo(Reginfo) {
207 this->Entsize = sizeof(Elf_Mips_RegInfo);
208}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000209
Rui Ueyamab71cae92016-11-22 03:57:08 +0000210template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000211 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000212 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000213 memcpy(Buf, &Reginfo, sizeof(Reginfo));
214}
215
216template <class ELFT>
217MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
218 // Section should be alive for O32 and N32 ABIs only.
219 if (ELFT::Is64Bits)
220 return nullptr;
221
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000222 std::vector<InputSectionBase *> Sections;
223 for (InputSectionBase *Sec : InputSections)
224 if (Sec->Type == SHT_MIPS_REGINFO)
225 Sections.push_back(Sec);
Rui Ueyamab71cae92016-11-22 03:57:08 +0000226
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000227 if (Sections.empty())
228 return nullptr;
229
230 Elf_Mips_RegInfo Reginfo = {};
231 for (InputSectionBase *Sec : Sections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000232 Sec->Live = false;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000233
234 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama25f30882017-10-27 03:25:04 +0000235 error(toString(Sec->File) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000236 return nullptr;
237 }
Rui Ueyamab71cae92016-11-22 03:57:08 +0000238
Simon Atanasyan05600502018-05-08 15:34:06 +0000239 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
Rui Ueyamab71cae92016-11-22 03:57:08 +0000240 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000241 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000242 };
243
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000244 return make<MipsReginfoSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000245}
246
Rui Ueyama3255a522017-02-27 02:32:49 +0000247InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000248 // StringSaver guarantees that the returned string ends with '\0'.
249 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000250 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
251
Rafael Espindolace3b52c2017-12-21 02:11:51 +0000252 auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
253 ".interp");
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000254 Sec->Live = true;
255 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000256}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000257
Peter Collingbournec5391ce2018-03-29 22:32:13 +0000258Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
259 uint64_t Size, InputSectionBase &Section) {
Rafael Espindola1037eef2017-12-19 23:59:35 +0000260 auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
261 Value, Size, &Section);
George Rimar69b17c32017-05-16 10:04:42 +0000262 if (InX::SymTab)
263 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000264 return S;
265}
266
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000267static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000268 switch (Config->BuildId) {
269 case BuildIdKind::Fast:
270 return 8;
271 case BuildIdKind::Md5:
272 case BuildIdKind::Uuid:
273 return 16;
274 case BuildIdKind::Sha1:
275 return 20;
276 case BuildIdKind::Hexstring:
277 return Config->BuildIdVector.size();
278 default:
279 llvm_unreachable("unknown BuildIdKind");
280 }
281}
282
George Rimar6c2949d2017-03-20 16:40:21 +0000283BuildIdSection::BuildIdSection()
Jake Ehrlich1128dc52017-10-30 22:08:11 +0000284 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000285 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000286
George Rimar6c2949d2017-03-20 16:40:21 +0000287void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyama79048e42017-10-27 03:59:34 +0000288 write32(Buf, 4); // Name size
289 write32(Buf + 4, HashSize); // Content size
290 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000291 memcpy(Buf + 12, "GNU", 4); // Name string
292 HashBuf = Buf + 16;
293}
294
Rui Ueyama35e00752016-11-10 00:12:28 +0000295// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000296static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
297 size_t ChunkSize) {
298 std::vector<ArrayRef<uint8_t>> Ret;
299 while (Arr.size() > ChunkSize) {
300 Ret.push_back(Arr.take_front(ChunkSize));
301 Arr = Arr.drop_front(ChunkSize);
302 }
303 if (!Arr.empty())
304 Ret.push_back(Arr);
305 return Ret;
306}
307
Rui Ueyama35e00752016-11-10 00:12:28 +0000308// Computes a hash value of Data using a given hash function.
309// In order to utilize multiple cores, we first split data into 1MB
310// chunks, compute a hash for each chunk, and then compute a hash value
311// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000312void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000313 llvm::ArrayRef<uint8_t> Data,
314 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000315 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000316 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000317
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000318 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000319 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000320 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
321 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000322
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000323 // Write to the final output buffer.
324 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000325}
326
Rui Ueyama732f4e22017-10-04 00:21:17 +0000327BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
328 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Peter Collingbourne6c55a702017-11-06 04:33:58 +0000329 this->Bss = true;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000330 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000331 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000332 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000333}
Peter Smithebfe9942017-02-09 10:27:57 +0000334
George Rimar6c2949d2017-03-20 16:40:21 +0000335void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000336 switch (Config->BuildId) {
337 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000338 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000339 write64le(Dest, xxHash64(toStringRef(Arr)));
340 });
341 break;
342 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000343 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000344 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000345 });
346 break;
347 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000348 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000349 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000350 });
351 break;
352 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000353 if (auto EC = getRandomBytes(HashBuf, HashSize))
354 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000355 break;
356 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000357 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000358 break;
359 default:
360 llvm_unreachable("unknown BuildIdKind");
361 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000362}
363
Rui Ueyama572247f2017-10-27 03:13:39 +0000364EhFrameSection::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000365 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000366
367// Search for an existing CIE record or create a new one.
368// CIE records from input object files are uniquified by their contents
369// and where their relocations point to.
Rui Ueyama572247f2017-10-27 03:13:39 +0000370template <class ELFT, class RelTy>
371CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000372 auto *Sec = cast<EhInputSection>(Cie.Sec);
Fangrui Song0c483022018-03-09 18:03:22 +0000373 if (read32(Cie.data().data() + 4) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000374 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
375
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000376 Symbol *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000377 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000378 if (FirstRelI != (unsigned)-1)
379 Personality =
380 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
381
382 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000383 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000384
385 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000386 if (!Rec) {
387 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000388 Rec->Cie = &Cie;
389 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000390 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000391 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000392}
393
394// There is one FDE per function. Returns true if a given FDE
395// points to a live function.
Rui Ueyama572247f2017-10-27 03:13:39 +0000396template <class ELFT, class RelTy>
397bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000398 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000399 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000400
401 // An FDE should point to some function because FDEs are to describe
402 // functions. That's however not always the case due to an issue of
403 // ld.gold with -r. ld.gold may discard only functions and leave their
404 // corresponding FDEs, which results in creating bad .eh_frame sections.
405 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000406 if (FirstRelI == (unsigned)-1)
407 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000408
Rafael Espindola66b4e212017-02-23 22:06:28 +0000409 const RelTy &Rel = Rels[FirstRelI];
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000410 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000411
412 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +0000413 if (auto *D = dyn_cast<Defined>(&B))
Rafael Espindola13dbf942017-12-13 17:36:53 +0000414 if (SectionBase *Sec = D->Section)
415 return Sec->Live;
Rui Ueyama27a357c2017-09-18 19:15:54 +0000416 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000417}
418
419// .eh_frame is a sequence of CIE or FDE records. In general, there
420// is one CIE record per input object file which is followed by
421// a list of FDEs. This function searches an existing CIE or create a new
422// one and associates FDEs to the CIE.
Rui Ueyama572247f2017-10-27 03:13:39 +0000423template <class ELFT, class RelTy>
424void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
Rafael Espindolabd4d2ac2018-04-27 20:19:28 +0000425 OffsetToCie.clear();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000426 for (EhSectionPiece &Piece : Sec->Pieces) {
427 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000428 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000429 return;
430
431 size_t Offset = Piece.InputOff;
Fangrui Song0c483022018-03-09 18:03:22 +0000432 uint32_t ID = read32(Piece.data().data() + 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000433 if (ID == 0) {
Rui Ueyama572247f2017-10-27 03:13:39 +0000434 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000435 continue;
436 }
437
438 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000439 CieRecord *Rec = OffsetToCie[CieOffset];
440 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000441 fatal(toString(Sec) + ": invalid CIE reference");
442
Rui Ueyama572247f2017-10-27 03:13:39 +0000443 if (!isFdeLive<ELFT>(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000444 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000445 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000446 NumFdes++;
447 }
448}
449
Rui Ueyama572247f2017-10-27 03:13:39 +0000450template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000451 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000452 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000453
454 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000455 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000456
Petr Hosek7b793212017-03-10 20:00:42 +0000457 for (auto *DS : Sec->DependentSections)
458 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000459
Rafael Espindola66b4e212017-02-23 22:06:28 +0000460 if (Sec->Pieces.empty())
461 return;
462
Rui Ueyamabfa84322017-10-26 22:30:25 +0000463 if (Sec->AreRelocsRela)
Rui Ueyama572247f2017-10-27 03:13:39 +0000464 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
Rui Ueyamafaa38022017-09-19 20:28:03 +0000465 else
Rui Ueyama572247f2017-10-27 03:13:39 +0000466 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000467}
468
Rafael Espindola66b4e212017-02-23 22:06:28 +0000469static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
470 memcpy(Buf, D.data(), D.size());
471
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000472 size_t Aligned = alignTo(D.size(), Config->Wordsize);
Andrew Ng6dee7362017-09-07 08:43:56 +0000473
474 // Zero-clear trailing padding if it exists.
475 memset(Buf + D.size(), 0, Aligned - D.size());
476
Rafael Espindola66b4e212017-02-23 22:06:28 +0000477 // Fix the size field. -4 since size does not include the size field itself.
Rui Ueyama79048e42017-10-27 03:59:34 +0000478 write32(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000479}
480
Rui Ueyama572247f2017-10-27 03:13:39 +0000481void EhFrameSection::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000482 if (this->Size)
483 return; // Already finalized.
484
485 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000486 for (CieRecord *Rec : CieRecords) {
487 Rec->Cie->OutputOff = Off;
488 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000489
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000490 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000491 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000492 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000493 }
494 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000495
496 // The LSB standard does not allow a .eh_frame section with zero
Fangrui Song95851512018-05-08 01:19:16 +0000497 // Call Frame Information records. glibc unwind-dw2-fde.c
498 // classify_object_over_fdes expects there is a CIE record length 0 as a
499 // terminator. Thus we add one unconditionally.
500 Off += 4;
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000501
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000502 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000503}
504
Rui Ueyamac0552252017-10-27 03:13:24 +0000505// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
506// to get an FDE from an address to which FDE is applied. This function
507// returns a list of such pairs.
Rui Ueyama572247f2017-10-27 03:13:39 +0000508std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
Rui Ueyamac0552252017-10-27 03:13:24 +0000509 uint8_t *Buf = getParent()->Loc + OutSecOff;
510 std::vector<FdeData> Ret;
511
512 for (CieRecord *Rec : CieRecords) {
Rui Ueyama86297522017-10-27 03:14:09 +0000513 uint8_t Enc = getFdeEncoding(Rec->Cie);
Rui Ueyamac0552252017-10-27 03:13:24 +0000514 for (EhSectionPiece *Fde : Rec->Fdes) {
515 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
516 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
517 Ret.push_back({Pc, FdeVA});
518 }
519 }
520 return Ret;
521}
522
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000523static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000524 switch (Size) {
525 case DW_EH_PE_udata2:
Fangrui Song0c483022018-03-09 18:03:22 +0000526 return read16(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000527 case DW_EH_PE_udata4:
Fangrui Song0c483022018-03-09 18:03:22 +0000528 return read32(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000529 case DW_EH_PE_udata8:
Fangrui Song0c483022018-03-09 18:03:22 +0000530 return read64(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000531 case DW_EH_PE_absptr:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000532 return readUint(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000533 }
534 fatal("unknown FDE size encoding");
535}
536
537// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
538// We need it to create .eh_frame_hdr section.
Rui Ueyama572247f2017-10-27 03:13:39 +0000539uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
540 uint8_t Enc) const {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000541 // The starting address to which this FDE applies is
542 // stored at FDE + 8 byte.
543 size_t Off = FdeOff + 8;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000544 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000545 if ((Enc & 0x70) == DW_EH_PE_absptr)
546 return Addr;
547 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000548 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000549 fatal("unknown FDE size relative encoding");
550}
551
Rui Ueyama572247f2017-10-27 03:13:39 +0000552void EhFrameSection::writeTo(uint8_t *Buf) {
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000553 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000554 for (CieRecord *Rec : CieRecords) {
555 size_t CieOffset = Rec->Cie->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000556 writeCieFde(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000557
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000558 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000559 size_t Off = Fde->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000560 writeCieFde(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000561
562 // FDE's second word should have the offset to an associated CIE.
563 // Write it.
Rui Ueyama79048e42017-10-27 03:59:34 +0000564 write32(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000565 }
566 }
567
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000568 // Apply relocations. .eh_frame section contents are not contiguous
569 // in the output buffer, but relocateAlloc() still works because
570 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000571 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000572 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000573}
574
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000575GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000576 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
Zaara Syedac65ae142018-03-26 17:50:52 +0000577 Target->GotEntrySize, ".got") {
578 // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the
579 // .got. If there are no references to .TOC. in the symbol table,
580 // ElfSym::GlobalOffsetTable will not be defined and we won't need to save
581 // .TOC. in the .got. When it is defined, we increase NumEntries by the number
582 // of entries used to emit ElfSym::GlobalOffsetTable.
583 if (ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt)
584 NumEntries += Target->GotHeaderEntriesNum;
585}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000586
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000587void GotSection::addEntry(Symbol &Sym) {
Zaara Syedac65ae142018-03-26 17:50:52 +0000588 Sym.GotIndex = NumEntries;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000589 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000590}
591
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000592bool GotSection::addDynTlsEntry(Symbol &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000593 if (Sym.GlobalDynIndex != -1U)
594 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000595 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000596 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000597 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000598 return true;
599}
600
601// Reserves TLS entries for a TLS module ID and a TLS block offset.
602// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000603bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000604 if (TlsIndexOff != uint32_t(-1))
605 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000606 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000607 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000608 return true;
609}
610
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000611uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000612 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000613}
614
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000615uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000616 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000617}
618
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000619void GotSection::finalizeContents() {
Zaara Syedac65ae142018-03-26 17:50:52 +0000620 Size = NumEntries * Config->Wordsize;
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000621}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000622
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000623bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000624 // We need to emit a GOT even if it's empty if there's a relocation that is
625 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
Peter Smith3d044f52018-03-19 06:52:51 +0000626 // (i.e. _GLOBAL_OFFSET_TABLE_) that the target defines relative to the .got.
627 return NumEntries == 0 && !HasGotOffRel &&
628 !(ElfSym::GlobalOffsetTable && !Target->GotBaseSymInGotPlt);
George Rimar11992c862016-11-25 08:05:41 +0000629}
630
Igor Kudrin202a9f62017-07-14 08:10:45 +0000631void GotSection::writeTo(uint8_t *Buf) {
632 // Buf points to the start of this section's buffer,
633 // whereas InputSectionBase::relocateAlloc() expects its argument
634 // to point to the start of the output section.
Zaara Syeda52ed6eb2018-03-19 17:40:14 +0000635 Target->writeGotHeader(Buf);
636 Buf += Target->GotHeaderEntriesNum * Target->GotEntrySize;
Igor Kudrin202a9f62017-07-14 08:10:45 +0000637 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
638}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000639
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000640static uint64_t getMipsPageAddr(uint64_t Addr) {
641 return (Addr + 0x8000) & ~0xffff;
642}
643
644static uint64_t getMipsPageCount(uint64_t Size) {
645 return (Size + 0xfffe) / 0xffff + 1;
646}
647
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000648MipsGotSection::MipsGotSection()
649 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
650 ".got") {}
651
652void MipsGotSection::addEntry(InputFile &File, Symbol &Sym, int64_t Addend,
653 RelExpr Expr) {
654 FileGot &G = getGot(File);
655 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
656 if (const OutputSection *OS = Sym.getOutputSection())
657 G.PagesMap.insert({OS, {}});
658 else
659 G.Local16.insert({{nullptr, getMipsPageAddr(Sym.getVA(Addend))}, 0});
660 } else if (Sym.isTls())
661 G.Tls.insert({&Sym, 0});
662 else if (Sym.IsPreemptible && Expr == R_ABS)
663 G.Relocs.insert({&Sym, 0});
664 else if (Sym.IsPreemptible)
665 G.Global.insert({&Sym, 0});
666 else if (Expr == R_MIPS_GOT_OFF32)
667 G.Local32.insert({{&Sym, Addend}, 0});
668 else
669 G.Local16.insert({{&Sym, Addend}, 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000670}
671
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000672void MipsGotSection::addDynTlsEntry(InputFile &File, Symbol &Sym) {
673 getGot(File).DynTlsSymbols.insert({&Sym, 0});
674}
675
676void MipsGotSection::addTlsIndex(InputFile &File) {
677 getGot(File).DynTlsSymbols.insert({nullptr, 0});
678}
679
680size_t MipsGotSection::FileGot::getEntriesNum() const {
681 return getPageEntriesNum() + Local16.size() + Global.size() + Relocs.size() +
682 Tls.size() + DynTlsSymbols.size() * 2;
683}
684
685size_t MipsGotSection::FileGot::getPageEntriesNum() const {
686 size_t Num = 0;
687 for (const std::pair<const OutputSection *, FileGot::PageBlock> &P : PagesMap)
688 Num += P.second.Count;
689 return Num;
690}
691
692size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
693 size_t Count = getPageEntriesNum() + Local16.size() + Global.size();
694 // If there are relocation-only entries in the GOT, TLS entries
695 // are allocated after them. TLS entries should be addressable
696 // by 16-bit index so count both reloc-only and TLS entries.
697 if (!Tls.empty() || !DynTlsSymbols.empty())
698 Count += Relocs.size() + Tls.size() + DynTlsSymbols.size() * 2;
699 return Count;
700}
701
702MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &F) {
703 if (!F.MipsGotIndex.hasValue()) {
704 Gots.emplace_back();
705 Gots.back().File = &F;
706 F.MipsGotIndex = Gots.size() - 1;
707 }
708 return Gots[*F.MipsGotIndex];
709}
710
Simon Atanasyan00d88432018-06-11 08:37:19 +0000711uint64_t MipsGotSection::getPageEntryOffset(const InputFile *F,
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000712 const Symbol &Sym,
713 int64_t Addend) const {
Simon Atanasyan00d88432018-06-11 08:37:19 +0000714 const FileGot &G = Gots[*F->MipsGotIndex];
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000715 uint64_t Index = 0;
716 if (const OutputSection *OutSec = Sym.getOutputSection()) {
717 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
718 uint64_t SymAddr = getMipsPageAddr(Sym.getVA(Addend));
719 Index = G.PagesMap.lookup(OutSec).FirstIndex + (SymAddr - SecAddr) / 0xffff;
720 } else {
721 Index = G.Local16.lookup({nullptr, getMipsPageAddr(Sym.getVA(Addend))});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000722 }
George Rimar14534eb2017-03-20 16:44:28 +0000723 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000724}
725
Simon Atanasyan00d88432018-06-11 08:37:19 +0000726uint64_t MipsGotSection::getSymEntryOffset(const InputFile *F, const Symbol &S,
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000727 int64_t Addend) const {
Simon Atanasyan00d88432018-06-11 08:37:19 +0000728 const FileGot &G = Gots[*F->MipsGotIndex];
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000729 Symbol *Sym = const_cast<Symbol *>(&S);
730 if (Sym->isTls())
731 return G.Tls.find(Sym)->second * Config->Wordsize;
732 if (Sym->IsPreemptible)
733 return G.Global.find(Sym)->second * Config->Wordsize;
734 return G.Local16.find({Sym, Addend})->second * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000735}
736
Simon Atanasyan00d88432018-06-11 08:37:19 +0000737uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *F) const {
738 const FileGot &G = Gots[*F->MipsGotIndex];
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000739 return G.DynTlsSymbols.find(nullptr)->second * Config->Wordsize;
740}
741
Simon Atanasyan00d88432018-06-11 08:37:19 +0000742uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *F,
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000743 const Symbol &S) const {
Simon Atanasyan00d88432018-06-11 08:37:19 +0000744 const FileGot &G = Gots[*F->MipsGotIndex];
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000745 Symbol *Sym = const_cast<Symbol *>(&S);
746 return G.DynTlsSymbols.find(Sym)->second * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000747}
748
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000749const Symbol *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000750 if (Gots.empty())
751 return nullptr;
752 const FileGot &PrimGot = Gots.front();
753 if (!PrimGot.Global.empty())
754 return PrimGot.Global.front().first;
755 if (!PrimGot.Relocs.empty())
756 return PrimGot.Relocs.front().first;
757 return nullptr;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000758}
759
George Rimar14534eb2017-03-20 16:44:28 +0000760unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000761 if (Gots.empty())
762 return HeaderEntriesNum;
763 return HeaderEntriesNum + Gots.front().getPageEntriesNum() +
764 Gots.front().Local16.size();
765}
766
767bool MipsGotSection::tryMergeGots(FileGot &Dst, FileGot &Src, bool IsPrimary) {
768 FileGot Tmp = Dst;
769 set_union(Tmp.PagesMap, Src.PagesMap);
770 set_union(Tmp.Local16, Src.Local16);
771 set_union(Tmp.Global, Src.Global);
772 set_union(Tmp.Relocs, Src.Relocs);
773 set_union(Tmp.Tls, Src.Tls);
774 set_union(Tmp.DynTlsSymbols, Src.DynTlsSymbols);
775
776 size_t Count = IsPrimary ? HeaderEntriesNum : 0;
777 Count += Tmp.getIndexedEntriesNum();
778
779 if (Count * Config->Wordsize > Config->MipsGotSize)
780 return false;
781
782 std::swap(Tmp, Dst);
783 return true;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000784}
785
George Rimar67c60722017-07-18 11:55:35 +0000786void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000787
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000788bool MipsGotSection::updateAllocSize() {
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000789 Size = HeaderEntriesNum * Config->Wordsize;
790 for (const FileGot &G : Gots)
791 Size += G.getEntriesNum() * Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000792 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000793}
794
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000795template <class ELFT> void MipsGotSection::build() {
796 if (Gots.empty())
797 return;
798
799 std::vector<FileGot> MergedGots(1);
800
801 // For each GOT move non-preemptible symbols from the `Global`
802 // to `Local16` list. Preemptible symbol might become non-preemptible
803 // one if, for example, it gets a related copy relocation.
804 for (FileGot &Got : Gots) {
805 for (auto &P: Got.Global)
806 if (!P.first->IsPreemptible)
807 Got.Local16.insert({{P.first, 0}, 0});
808 Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
809 return !P.first->IsPreemptible;
810 });
811 }
812
813 // For each GOT remove "reloc-only" entry if there is "global"
814 // entry for the same symbol. And add local entries which indexed
815 // using 32-bit value at the end of 16-bit entries.
816 for (FileGot &Got : Gots) {
817 Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
818 return Got.Global.count(P.first);
819 });
820 set_union(Got.Local16, Got.Local32);
821 Got.Local32.clear();
822 }
823
824 // Evaluate number of "reloc-only" entries in the resulting GOT.
825 // To do that put all unique "reloc-only" and "global" entries
826 // from all GOTs to the future primary GOT.
827 FileGot *PrimGot = &MergedGots.front();
828 for (FileGot &Got : Gots) {
829 set_union(PrimGot->Relocs, Got.Global);
830 set_union(PrimGot->Relocs, Got.Relocs);
831 Got.Relocs.clear();
832 }
833
834 // Evaluate number of "page" entries in each GOT.
835 for (FileGot &Got : Gots) {
836 for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
837 Got.PagesMap) {
838 const OutputSection *OS = P.first;
839 uint64_t SecSize = 0;
840 for (BaseCommand *Cmd : OS->SectionCommands) {
841 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
842 for (InputSection *IS : ISD->Sections) {
843 uint64_t Off = alignTo(SecSize, IS->Alignment);
844 SecSize = Off + IS->getSize();
845 }
846 }
847 P.second.Count = getMipsPageCount(SecSize);
848 }
849 }
850
851 // Merge GOTs. Try to join as much as possible GOTs but do not
852 // exceed maximum GOT size. In case of overflow create new GOT
853 // and continue merging.
854 for (FileGot &SrcGot : Gots) {
855 FileGot &DstGot = MergedGots.back();
856 InputFile *File = SrcGot.File;
857 if (!tryMergeGots(DstGot, SrcGot, &DstGot == PrimGot)) {
858 MergedGots.emplace_back();
859 std::swap(MergedGots.back(), SrcGot);
860 }
861 File->MipsGotIndex = MergedGots.size() - 1;
862 }
863 std::swap(Gots, MergedGots);
864
865 // Reduce number of "reloc-only" entries in the primary GOT
866 // by substracting "global" entries exist in the primary GOT.
867 PrimGot = &Gots.front();
868 PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
869 return PrimGot->Global.count(P.first);
870 });
871
872 // Calculate indexes for each GOT entry.
873 size_t Index = HeaderEntriesNum;
874 for (FileGot &Got : Gots) {
875 Got.StartIndex = &Got == PrimGot ? 0 : Index;
876 for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
877 Got.PagesMap) {
878 // For each output section referenced by GOT page relocations calculate
879 // and save into PagesMap an upper bound of MIPS GOT entries required
880 // to store page addresses of local symbols. We assume the worst case -
881 // each 64kb page of the output section has at least one GOT relocation
882 // against it. And take in account the case when the section intersects
883 // page boundaries.
884 P.second.FirstIndex = Index;
885 Index += P.second.Count;
886 }
887 for (auto &P: Got.Local16)
888 P.second = Index++;
889 for (auto &P: Got.Global)
890 P.second = Index++;
891 for (auto &P: Got.Relocs)
892 P.second = Index++;
893 for (auto &P: Got.Tls)
894 P.second = Index++;
895 for (auto &P: Got.DynTlsSymbols) {
896 P.second = Index;
897 Index += 2;
898 }
899 }
900
901 // Update Symbol::GotIndex field to use this
902 // value later in the `sortMipsSymbols` function.
903 for (auto &P : PrimGot->Global)
904 P.first->GotIndex = P.second;
905 for (auto &P : PrimGot->Relocs)
906 P.first->GotIndex = P.second;
907
908 // Create dynamic relocations.
909 for (FileGot &Got : Gots) {
910 // Create dynamic relocations for TLS entries.
911 for (std::pair<Symbol *, size_t> &P : Got.Tls) {
912 Symbol *S = P.first;
913 uint64_t Offset = P.second * Config->Wordsize;
914 if (S->IsPreemptible)
915 InX::RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
916 }
917 for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
918 Symbol *S = P.first;
919 uint64_t Offset = P.second * Config->Wordsize;
920 if (S == nullptr) {
921 if (!Config->Pic)
922 continue;
923 InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
924 } else {
925 if (!P.first->IsPreemptible)
926 continue;
927 InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
928 Offset += Config->Wordsize;
929 InX::RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
930 }
931 }
932
933 // Do not create dynamic relocations for non-TLS
934 // entries in the primary GOT.
935 if (&Got == PrimGot)
936 continue;
937
938 // Dynamic relocations for "global" entries.
939 for (const std::pair<Symbol *, size_t> &P : Got.Global) {
940 uint64_t Offset = P.second * Config->Wordsize;
941 InX::RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
942 }
943 if (!Config->Pic)
944 continue;
945 // Dynamic relocations for "local" entries in case of PIC.
946 for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
947 Got.PagesMap) {
948 size_t PageCount = L.second.Count;
949 for (size_t PI = 0; PI < PageCount; ++PI) {
950 uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
951 InX::RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
952 int64_t(PI * 0x10000)});
953 }
954 }
955 for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
956 uint64_t Offset = P.second * Config->Wordsize;
957 InX::RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
958 P.first.first, P.first.second});
959 }
960 }
961}
962
George Rimar14534eb2017-03-20 16:44:28 +0000963bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000964 // We add the .got section to the result for dynamic MIPS target because
965 // its address and properties are mentioned in the .dynamic section.
966 return Config->Relocatable;
967}
968
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000969uint64_t MipsGotSection::getGp(const InputFile *F) const {
970 // For files without related GOT or files refer a primary GOT
971 // returns "common" _gp value. For secondary GOTs calculate
972 // individual _gp values.
973 if (!F || !F->MipsGotIndex.hasValue() || *F->MipsGotIndex == 0)
974 return ElfSym::MipsGp->getVA(0);
975 return getVA() + Gots[*F->MipsGotIndex].StartIndex * Config->Wordsize +
976 0x7ff0;
977}
Simon Atanasyan8469b882016-11-23 22:22:16 +0000978
George Rimar14534eb2017-03-20 16:44:28 +0000979void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000980 // Set the MSB of the second GOT slot. This is not required by any
981 // MIPS ABI documentation, though.
982 //
983 // There is a comment in glibc saying that "The MSB of got[1] of a
984 // gnu object is set to identify gnu objects," and in GNU gold it
985 // says "the second entry will be used by some runtime loaders".
986 // But how this field is being used is unclear.
987 //
988 // We are not really willing to mimic other linkers behaviors
989 // without understanding why they do that, but because all files
990 // generated by GNU tools have this special GOT value, and because
991 // we've been doing this for years, it is probably a safe bet to
992 // keep doing this for now. We really need to revisit this to see
993 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000994 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
Simon Atanasyaned9ee692018-06-11 07:24:31 +0000995 for (const FileGot &G : Gots) {
996 auto Write = [&](size_t I, const Symbol *S, int64_t A) {
997 uint64_t VA = A;
998 if (S) {
999 VA = S->getVA(A);
1000 if (S->StOther & STO_MIPS_MICROMIPS)
1001 VA |= 1;
1002 }
1003 writeUint(Buf + I * Config->Wordsize, VA);
1004 };
1005 // Write 'page address' entries to the local part of the GOT.
1006 for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
1007 G.PagesMap) {
1008 size_t PageCount = L.second.Count;
1009 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
1010 for (size_t PI = 0; PI < PageCount; ++PI)
1011 Write(L.second.FirstIndex + PI, nullptr, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +00001012 }
Simon Atanasyaned9ee692018-06-11 07:24:31 +00001013 // Local, global, TLS, reloc-only entries.
1014 // If TLS entry has a corresponding dynamic relocations, leave it
1015 // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1016 // To calculate the adjustments use offsets for thread-local storage.
1017 // https://www.linux-mips.org/wiki/NPTL
1018 for (const std::pair<GotEntry, size_t> &P : G.Local16)
1019 Write(P.second, P.first.first, P.first.second);
1020 // Write VA to the primary GOT only. For secondary GOTs that
1021 // will be done by REL32 dynamic relocations.
1022 if (&G == &Gots.front())
1023 for (const std::pair<const Symbol *, size_t> &P : G.Global)
1024 Write(P.second, P.first, 0);
1025 for (const std::pair<Symbol *, size_t> &P : G.Relocs)
1026 Write(P.second, P.first, 0);
1027 for (const std::pair<Symbol *, size_t> &P : G.Tls)
1028 Write(P.second, P.first, P.first->IsPreemptible ? 0 : -0x7000);
1029 for (const std::pair<Symbol *, size_t> &P : G.DynTlsSymbols) {
1030 if (P.first == nullptr && !Config->Pic)
1031 Write(P.second, nullptr, 1);
1032 else if (P.first && !P.first->IsPreemptible) {
1033 Write(P.second, nullptr, 1);
1034 Write(P.second + 1, P.first, -0x8000);
1035 }
Eugene Leviantad4439e2016-11-11 11:33:32 +00001036 }
1037 }
1038}
1039
Sean Fertile49914cc2018-05-09 02:07:53 +00001040// On PowerPC the .plt section is used to hold the table of function addresses
1041// instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1042// section. I don't know why we have a BSS style type for the section but it is
1043// consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
George Rimar10f74fc2017-03-15 09:12:56 +00001044GotPltSection::GotPltSection()
Sean Fertile49914cc2018-05-09 02:07:53 +00001045 : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1046 Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1047 Target->GotPltEntrySize,
1048 Config->EMachine == EM_PPC64 ? ".plt" : ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +00001049
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001050void GotPltSection::addEntry(Symbol &Sym) {
Rafael Espindolaf4a9d562018-04-26 16:09:30 +00001051 assert(Sym.PltIndex == Entries.size());
Eugene Leviant41ca3272016-11-10 09:48:29 +00001052 Entries.push_back(&Sym);
1053}
1054
George Rimar10f74fc2017-03-15 09:12:56 +00001055size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +00001056 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
1057 Target->GotPltEntrySize;
1058}
1059
George Rimar10f74fc2017-03-15 09:12:56 +00001060void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +00001061 Target->writeGotPltHeader(Buf);
1062 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001063 for (const Symbol *B : Entries) {
Eugene Leviant41ca3272016-11-10 09:48:29 +00001064 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001065 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +00001066 }
1067}
1068
Peter Smith3d044f52018-03-19 06:52:51 +00001069bool GotPltSection::empty() const {
1070 // We need to emit a GOT.PLT even if it's empty if there's a symbol that
1071 // references the _GLOBAL_OFFSET_TABLE_ and the Target defines the symbol
1072 // relative to the .got.plt section.
1073 return Entries.empty() &&
1074 !(ElfSym::GlobalOffsetTable && Target->GotBaseSymInGotPlt);
1075}
1076
Sean Fertile49914cc2018-05-09 02:07:53 +00001077static StringRef getIgotPltName() {
1078 // On ARM the IgotPltSection is part of the GotSection.
1079 if (Config->EMachine == EM_ARM)
1080 return ".got";
1081
1082 // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1083 // needs to be named the same.
1084 if (Config->EMachine == EM_PPC64)
1085 return ".plt";
1086
1087 return ".got.plt";
1088}
1089
1090// On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1091// with the IgotPltSection.
George Rimar10f74fc2017-03-15 09:12:56 +00001092IgotPltSection::IgotPltSection()
Sean Fertile49914cc2018-05-09 02:07:53 +00001093 : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1094 Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1095 Target->GotPltEntrySize, getIgotPltName()) {}
Peter Smithbaffdb82016-12-08 12:58:55 +00001096
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001097void IgotPltSection::addEntry(Symbol &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +00001098 Sym.IsInIgot = true;
Rafael Espindolaf4a9d562018-04-26 16:09:30 +00001099 assert(Sym.PltIndex == Entries.size());
Peter Smithbaffdb82016-12-08 12:58:55 +00001100 Entries.push_back(&Sym);
1101}
1102
George Rimar10f74fc2017-03-15 09:12:56 +00001103size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +00001104 return Entries.size() * Target->GotPltEntrySize;
1105}
1106
George Rimar10f74fc2017-03-15 09:12:56 +00001107void IgotPltSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001108 for (const Symbol *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +00001109 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001110 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +00001111 }
1112}
1113
George Rimar49648002017-03-15 09:32:36 +00001114StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
1115 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +00001116 Dynamic(Dynamic) {
1117 // ELF string tables start with a NUL byte.
1118 addString("");
1119}
Eugene Leviant22eb0262016-11-14 09:16:00 +00001120
1121// Adds a string to the string table. If HashIt is true we hash and check for
1122// duplicates. It is optional because the name of global symbols are already
1123// uniqued and hashing them again has a big cost for a small value: uniquing
1124// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +00001125unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001126 if (HashIt) {
1127 auto R = StringMap.insert(std::make_pair(S, this->Size));
1128 if (!R.second)
1129 return R.first->second;
1130 }
1131 unsigned Ret = this->Size;
1132 this->Size = this->Size + S.size() + 1;
1133 Strings.push_back(S);
1134 return Ret;
1135}
1136
George Rimar49648002017-03-15 09:32:36 +00001137void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001138 for (StringRef S : Strings) {
1139 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +00001140 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +00001141 Buf += S.size() + 1;
1142 }
1143}
1144
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001145// Returns the number of version definition entries. Because the first entry
1146// is for the version definition itself, it is the number of versioned symbols
1147// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001148static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1149
1150template <class ELFT>
1151DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001152 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001153 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001154 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001155
Petr Hosekffa786f2017-05-26 19:12:38 +00001156 // .dynamic section is not writable on MIPS and on Fuchsia OS
1157 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001158 // See "Special Section" in Chapter 4 in the following document:
1159 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001160 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001161 this->Flags = SHF_ALLOC;
1162
Rui Ueyama22e55512017-12-15 19:39:59 +00001163 // Add strings to .dynstr early so that .dynstr's size will be
1164 // fixed early.
1165 for (StringRef S : Config->FilterList)
1166 addInt(DT_FILTER, InX::DynStrTab->addString(S));
1167 for (StringRef S : Config->AuxiliaryList)
1168 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
1169
1170 if (!Config->Rpath.empty())
1171 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1172 InX::DynStrTab->addString(Config->Rpath));
1173
1174 for (InputFile *File : SharedFiles) {
1175 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1176 if (F->IsNeeded)
1177 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
1178 }
1179 if (!Config->SoName.empty())
1180 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001181}
1182
Rui Ueyama15475e92017-11-24 02:15:51 +00001183template <class ELFT>
1184void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1185 Entries.push_back({Tag, Fn});
1186}
1187
1188template <class ELFT>
1189void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1190 Entries.push_back({Tag, [=] { return Val; }});
1191}
1192
1193template <class ELFT>
1194void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
Rafael Espindola4f058a22018-03-24 00:35:11 +00001195 Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
Rui Ueyama15475e92017-11-24 02:15:51 +00001196}
1197
1198template <class ELFT>
Simon Atanasyan1ba19422018-04-13 08:15:01 +00001199void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1200 size_t TagOffset = Entries.size() * Entsize;
1201 Entries.push_back(
1202 {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1203}
1204
1205template <class ELFT>
Rui Ueyama15475e92017-11-24 02:15:51 +00001206void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1207 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1208}
1209
1210template <class ELFT>
1211void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1212 Entries.push_back({Tag, [=] { return Sec->Size; }});
1213}
1214
1215template <class ELFT>
1216void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1217 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1218}
1219
Rui Ueyama22e55512017-12-15 19:39:59 +00001220// Add remaining entries to complete .dynamic contents.
1221template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1222 if (this->Size)
1223 return; // Already finalized.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001224
1225 // Set DT_FLAGS and DT_FLAGS_1.
1226 uint32_t DtFlags = 0;
1227 uint32_t DtFlags1 = 0;
1228 if (Config->Bsymbolic)
1229 DtFlags |= DF_SYMBOLIC;
1230 if (Config->ZNodelete)
1231 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001232 if (Config->ZNodlopen)
1233 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001234 if (Config->ZNow) {
1235 DtFlags |= DF_BIND_NOW;
1236 DtFlags1 |= DF_1_NOW;
1237 }
1238 if (Config->ZOrigin) {
1239 DtFlags |= DF_ORIGIN;
1240 DtFlags1 |= DF_1_ORIGIN;
1241 }
Rui Ueyama7c18abf2018-03-01 22:56:52 +00001242 if (!Config->ZText)
1243 DtFlags |= DF_TEXTREL;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001244
1245 if (DtFlags)
Rui Ueyama15475e92017-11-24 02:15:51 +00001246 addInt(DT_FLAGS, DtFlags);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001247 if (DtFlags1)
Rui Ueyama15475e92017-11-24 02:15:51 +00001248 addInt(DT_FLAGS_1, DtFlags1);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001249
Petr Hosekffa786f2017-05-26 19:12:38 +00001250 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1251 // need it for each process, so we don't write it for DSOs. The loader writes
1252 // the pointer into this entry.
1253 //
1254 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1255 // systems (currently only Fuchsia OS) provide other means to give the
1256 // debugger this information. Such systems may choose make .dynamic read-only.
1257 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1258 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
Rui Ueyama15475e92017-11-24 02:15:51 +00001259 addInt(DT_DEBUG, 0);
George Rimarb4081bb2017-05-12 08:04:58 +00001260
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001261 this->Link = InX::DynStrTab->getParent()->SectionIndex;
George Rimar32085882017-12-30 08:40:45 +00001262 if (!InX::RelaDyn->empty()) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001263 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1264 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001265
1266 bool IsRela = Config->IsRela;
Rui Ueyama15475e92017-11-24 02:15:51 +00001267 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1268 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001269
1270 // MIPS dynamic loader does not support RELCOUNT tag.
1271 // The problem is in the tight relation between dynamic
1272 // relocations and GOT. So do not emit this tag on MIPS.
1273 if (Config->EMachine != EM_MIPS) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001274 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001275 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama15475e92017-11-24 02:15:51 +00001276 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001277 }
1278 }
George Rimaredb61162017-12-31 07:42:54 +00001279 // .rel[a].plt section usually consists of two parts, containing plt and
1280 // iplt relocations. It is possible to have only iplt relocations in the
1281 // output. In that case RelaPlt is empty and have zero offset, the same offset
1282 // as RelaIplt have. And we still want to emit proper dynamic tags for that
1283 // case, so here we always use RelaPlt as marker for the begining of
1284 // .rel[a].plt section.
1285 if (InX::RelaPlt->getParent()->Live) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001286 addInSec(DT_JMPREL, InX::RelaPlt);
1287 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
Rui Ueyama0cc14832017-06-28 17:05:39 +00001288 switch (Config->EMachine) {
1289 case EM_MIPS:
Rui Ueyama15475e92017-11-24 02:15:51 +00001290 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001291 break;
1292 case EM_SPARCV9:
Rui Ueyama15475e92017-11-24 02:15:51 +00001293 addInSec(DT_PLTGOT, InX::Plt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001294 break;
1295 default:
Rui Ueyama15475e92017-11-24 02:15:51 +00001296 addInSec(DT_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001297 break;
1298 }
Rui Ueyama15475e92017-11-24 02:15:51 +00001299 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001300 }
1301
Rui Ueyama15475e92017-11-24 02:15:51 +00001302 addInSec(DT_SYMTAB, InX::DynSymTab);
1303 addInt(DT_SYMENT, sizeof(Elf_Sym));
1304 addInSec(DT_STRTAB, InX::DynStrTab);
1305 addInt(DT_STRSZ, InX::DynStrTab->getSize());
George Rimar0a7412f2017-03-09 08:48:34 +00001306 if (!Config->ZText)
Rui Ueyama15475e92017-11-24 02:15:51 +00001307 addInt(DT_TEXTREL, 0);
George Rimar69b17c32017-05-16 10:04:42 +00001308 if (InX::GnuHashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001309 addInSec(DT_GNU_HASH, InX::GnuHashTab);
George Rimaraaf54712017-09-27 09:14:59 +00001310 if (InX::HashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001311 addInSec(DT_HASH, InX::HashTab);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001312
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001313 if (Out::PreinitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001314 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1315 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001316 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001317 if (Out::InitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001318 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1319 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001320 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001321 if (Out::FiniArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001322 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1323 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001324 }
1325
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001326 if (Symbol *B = Symtab->find(Config->Init))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001327 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001328 addSym(DT_INIT, B);
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001329 if (Symbol *B = Symtab->find(Config->Fini))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001330 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001331 addSym(DT_FINI, B);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001332
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001333 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1334 if (HasVerNeed || In<ELFT>::VerDef)
Rui Ueyama15475e92017-11-24 02:15:51 +00001335 addInSec(DT_VERSYM, In<ELFT>::VerSym);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001336 if (In<ELFT>::VerDef) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001337 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1338 addInt(DT_VERDEFNUM, getVerDefNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001339 }
1340 if (HasVerNeed) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001341 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1342 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001343 }
1344
1345 if (Config->EMachine == EM_MIPS) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001346 addInt(DT_MIPS_RLD_VERSION, 1);
1347 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1348 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1349 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
James Hendersonf70c5be2017-11-22 12:04:21 +00001350
Rui Ueyama15475e92017-11-24 02:15:51 +00001351 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
James Hendersonf70c5be2017-11-22 12:04:21 +00001352
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001353 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama15475e92017-11-24 02:15:51 +00001354 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001355 else
Rui Ueyama15475e92017-11-24 02:15:51 +00001356 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1357 addInSec(DT_PLTGOT, InX::MipsGot);
Simon Atanasyan1ba19422018-04-13 08:15:01 +00001358 if (InX::MipsRldMap) {
1359 if (!Config->Pie)
1360 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1361 // Store the offset to the .rld_map section
1362 // relative to the address of the tag.
1363 addInSecRelative(DT_MIPS_RLD_MAP_REL, InX::MipsRldMap);
1364 }
Eugene Leviant6380ce22016-11-15 12:26:55 +00001365 }
1366
Sean Fertile49914cc2018-05-09 02:07:53 +00001367 // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1368 if (Config->EMachine == EM_PPC64 && !InX::Plt->empty()) {
1369 // The Glink tag points to 32 bytes before the first lazy symbol resolution
1370 // stub, which starts directly after the header.
1371 Entries.push_back({DT_PPC64_GLINK, [=] {
1372 unsigned Offset = Target->PltHeaderSize - 32;
1373 return InX::Plt->getVA(0) + Offset;
1374 }});
1375 }
1376
Rui Ueyama15475e92017-11-24 02:15:51 +00001377 addInt(DT_NULL, 0);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001378
George Rimar8f3a6c82017-10-06 10:06:13 +00001379 getParent()->Link = this->Link;
1380 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001381}
1382
1383template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1384 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1385
Rui Ueyama15475e92017-11-24 02:15:51 +00001386 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1387 P->d_tag = KV.first;
1388 P->d_un.d_val = KV.second();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001389 ++P;
1390 }
1391}
1392
George Rimar97def8c2017-03-17 12:07:44 +00001393uint64_t DynamicReloc::getOffset() const {
Rafael Espindola4f058a22018-03-24 00:35:11 +00001394 return InputSec->getVA(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001395}
1396
Alexander Richardson048e2502018-02-19 11:00:15 +00001397int64_t DynamicReloc::computeAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001398 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001399 return Sym->getVA(Addend);
Simon Atanasyaned9ee692018-06-11 07:24:31 +00001400 if (!OutputSec)
1401 return Addend;
1402 // See the comment in the DynamicReloc ctor.
1403 return getMipsPageAddr(OutputSec->Addr) + Addend;
Eugene Levianta96d9022016-11-16 10:02:27 +00001404}
1405
George Rimar97def8c2017-03-17 12:07:44 +00001406uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001407 if (Sym && !UseSymVA)
1408 return Sym->DynsymIndex;
1409 return 0;
1410}
1411
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001412RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1413 int32_t DynamicTag,
1414 int32_t SizeDynamicTag)
1415 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1416 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001417
Rafael Espindolad49866e2018-02-13 16:06:11 +00001418void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
Rafael Espindola35cf8bb2018-02-13 16:03:52 +00001419 uint64_t OffsetInSec, Symbol *Sym) {
1420 addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1421}
1422
Rafael Espindolad49866e2018-02-13 16:06:11 +00001423void RelocationBaseSection::addReloc(RelType DynType,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001424 InputSectionBase *InputSec,
Rafael Espindolab9603252018-02-16 16:53:04 +00001425 uint64_t OffsetInSec, Symbol *Sym,
1426 int64_t Addend, RelExpr Expr,
Rafael Espindola73584cb2018-01-05 20:08:38 +00001427 RelType Type) {
Alexander Richardsoncfb60932018-02-16 10:01:17 +00001428 // Write the addends to the relocated address if required. We skip
1429 // it if the written value would be zero.
Rafael Espindolab9603252018-02-16 16:53:04 +00001430 if (Config->WriteAddends && (Expr != R_ADDEND || Addend != 0))
Rafael Espindola73584cb2018-01-05 20:08:38 +00001431 InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
Rafael Espindolab9603252018-02-16 16:53:04 +00001432 addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
Rafael Espindola73584cb2018-01-05 20:08:38 +00001433}
1434
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001435void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001436 if (Reloc.Type == Target->RelativeRel)
1437 ++NumRelativeRelocs;
1438 Relocs.push_back(Reloc);
1439}
1440
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001441void RelocationBaseSection::finalizeContents() {
1442 // If all relocations are R_*_RELATIVE they don't refer to any
1443 // dynamic symbol and we don't need a dynamic symbol table. If that
1444 // is the case, just use 0 as the link.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001445 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001446
1447 // Set required output section properties.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001448 getParent()->Link = Link;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001449}
1450
1451template <class ELFT>
1452static void encodeDynamicReloc(typename ELFT::Rela *P,
1453 const DynamicReloc &Rel) {
1454 if (Config->IsRela)
Alexander Richardson048e2502018-02-19 11:00:15 +00001455 P->r_addend = Rel.computeAddend();
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001456 P->r_offset = Rel.getOffset();
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001457 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1458}
1459
1460template <class ELFT>
1461RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1462 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1463 Config->IsRela ? DT_RELA : DT_REL,
1464 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1465 Sort(Sort) {
1466 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1467}
1468
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001469static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) {
1470 bool AIsRel = A.Type == Target->RelativeRel;
1471 bool BIsRel = B.Type == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001472 if (AIsRel != BIsRel)
1473 return AIsRel;
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001474 return A.getSymIndex() < B.getSymIndex();
Eugene Levianta96d9022016-11-16 10:02:27 +00001475}
1476
1477template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola7ce2b4c2018-02-01 03:17:12 +00001478 if (Sort)
1479 std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1480
George Rimar97def8c2017-03-17 12:07:44 +00001481 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001482 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001483 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001484 }
Eugene Levianta96d9022016-11-16 10:02:27 +00001485}
1486
1487template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1488 return this->Entsize * Relocs.size();
1489}
1490
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001491template <class ELFT>
1492AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1493 StringRef Name)
1494 : RelocationBaseSection(
1495 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1496 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1497 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1498 this->Entsize = 1;
1499}
Eugene Levianta96d9022016-11-16 10:02:27 +00001500
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001501template <class ELFT>
1502bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1503 // This function computes the contents of an Android-format packed relocation
1504 // section.
1505 //
1506 // This format compresses relocations by using relocation groups to factor out
1507 // fields that are common between relocations and storing deltas from previous
1508 // relocations in SLEB128 format (which has a short representation for small
1509 // numbers). A good example of a relocation type with common fields is
1510 // R_*_RELATIVE, which is normally used to represent function pointers in
1511 // vtables. In the REL format, each relative relocation has the same r_info
1512 // field, and is only different from other relative relocations in terms of
1513 // the r_offset field. By sorting relocations by offset, grouping them by
1514 // r_info and representing each relocation with only the delta from the
1515 // previous offset, each 8-byte relocation can be compressed to as little as 1
1516 // byte (or less with run-length encoding). This relocation packer was able to
1517 // reduce the size of the relocation section in an Android Chromium DSO from
1518 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1519 //
1520 // A relocation section consists of a header containing the literal bytes
1521 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1522 // elements are the total number of relocations in the section and an initial
1523 // r_offset value. The remaining elements define a sequence of relocation
1524 // groups. Each relocation group starts with a header consisting of the
1525 // following elements:
1526 //
1527 // - the number of relocations in the relocation group
1528 // - flags for the relocation group
1529 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1530 // for each relocation in the group.
1531 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1532 // field for each relocation in the group.
1533 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1534 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1535 // each relocation in the group.
1536 //
1537 // Following the relocation group header are descriptions of each of the
1538 // relocations in the group. They consist of the following elements:
1539 //
1540 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1541 // delta for this relocation.
1542 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1543 // field for this relocation.
1544 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1545 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1546 // this relocation.
1547
1548 size_t OldSize = RelocData.size();
1549
1550 RelocData = {'A', 'P', 'S', '2'};
1551 raw_svector_ostream OS(RelocData);
Rui Ueyama04c821c2017-12-08 02:20:50 +00001552 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001553
1554 // The format header includes the number of relocations and the initial
1555 // offset (we set this to zero because the first relocation group will
1556 // perform the initial adjustment).
Rui Ueyama04c821c2017-12-08 02:20:50 +00001557 Add(Relocs.size());
1558 Add(0);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001559
1560 std::vector<Elf_Rela> Relatives, NonRelatives;
1561
1562 for (const DynamicReloc &Rel : Relocs) {
1563 Elf_Rela R;
1564 encodeDynamicReloc<ELFT>(&R, Rel);
1565
1566 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1567 Relatives.push_back(R);
1568 else
1569 NonRelatives.push_back(R);
1570 }
1571
George Rimarde83cbf2018-04-24 09:55:39 +00001572 llvm::sort(Relatives.begin(), Relatives.end(),
1573 [](const Elf_Rel &A, const Elf_Rel &B) {
1574 return A.r_offset < B.r_offset;
1575 });
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001576
1577 // Try to find groups of relative relocations which are spaced one word
1578 // apart from one another. These generally correspond to vtable entries. The
1579 // format allows these groups to be encoded using a sort of run-length
1580 // encoding, but each group will cost 7 bytes in addition to the offset from
1581 // the previous group, so it is only profitable to do this for groups of
1582 // size 8 or larger.
1583 std::vector<Elf_Rela> UngroupedRelatives;
1584 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1585 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1586 std::vector<Elf_Rela> Group;
1587 do {
1588 Group.push_back(*I++);
1589 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1590
1591 if (Group.size() < 8)
1592 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1593 Group.end());
1594 else
1595 RelativeGroups.emplace_back(std::move(Group));
1596 }
1597
1598 unsigned HasAddendIfRela =
1599 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1600
1601 uint64_t Offset = 0;
1602 uint64_t Addend = 0;
1603
1604 // Emit the run-length encoding for the groups of adjacent relative
1605 // relocations. Each group is represented using two groups in the packed
1606 // format. The first is used to set the current offset to the start of the
1607 // group (and also encodes the first relocation), and the second encodes the
1608 // remaining relocations.
1609 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1610 // The first relocation in the group.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001611 Add(1);
1612 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1613 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1614 Add(G[0].r_offset - Offset);
1615 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001616 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001617 Add(G[0].r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001618 Addend = G[0].r_addend;
1619 }
1620
1621 // The remaining relocations.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001622 Add(G.size() - 1);
1623 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1624 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1625 Add(Config->Wordsize);
1626 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001627 if (Config->IsRela) {
1628 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001629 Add(I->r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001630 Addend = I->r_addend;
1631 }
1632 }
1633
1634 Offset = G.back().r_offset;
1635 }
1636
1637 // Now the ungrouped relatives.
1638 if (!UngroupedRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001639 Add(UngroupedRelatives.size());
1640 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1641 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001642 for (Elf_Rela &R : UngroupedRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001643 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001644 Offset = R.r_offset;
1645 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001646 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001647 Addend = R.r_addend;
1648 }
1649 }
1650 }
1651
1652 // Finally the non-relative relocations.
George Rimarde83cbf2018-04-24 09:55:39 +00001653 llvm::sort(NonRelatives.begin(), NonRelatives.end(),
1654 [](const Elf_Rela &A, const Elf_Rela &B) {
1655 return A.r_offset < B.r_offset;
1656 });
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001657 if (!NonRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001658 Add(NonRelatives.size());
1659 Add(HasAddendIfRela);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001660 for (Elf_Rela &R : NonRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001661 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001662 Offset = R.r_offset;
Rui Ueyama04c821c2017-12-08 02:20:50 +00001663 Add(R.r_info);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001664 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001665 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001666 Addend = R.r_addend;
1667 }
1668 }
1669 }
1670
1671 // Returns whether the section size changed. We need to keep recomputing both
1672 // section layout and the contents of this section until the size converges
1673 // because changing this section's size can affect section layout, which in
1674 // turn can affect the sizes of the LEB-encoded integers stored in this
1675 // section.
1676 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001677}
1678
George Rimarf45f6812017-05-16 08:53:30 +00001679SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001680 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001681 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001682 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001683 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001684 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001685
1686// Orders symbols according to their positions in the GOT,
1687// in compliance with MIPS ABI rules.
1688// See "Global Offset Table" in Chapter 5 in the following document
1689// for detailed description:
1690// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001691static bool sortMipsSymbols(const SymbolTableEntry &L,
1692 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001693 // Sort entries related to non-local preemptible symbols by GOT indexes.
1694 // All other entries go to the first part of GOT in arbitrary order.
Simon Atanasyaned9ee692018-06-11 07:24:31 +00001695 if (!L.Sym->isInGot() || !R.Sym->isInGot())
1696 return !L.Sym->isInGot();
Zachary Turnera104d552017-11-03 22:33:49 +00001697 return L.Sym->GotIndex < R.Sym->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001698}
1699
George Rimarf45f6812017-05-16 08:53:30 +00001700void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001701 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001702
George Rimar55d71782018-04-04 12:36:21 +00001703 if (this->Type != SHT_DYNSYM)
1704 return;
1705
Rui Ueyama6e967342017-02-28 03:29:12 +00001706 // If it is a .dynsym, there should be no local symbols, but we need
1707 // to do a few things for the dynamic linker.
Rui Ueyama6e967342017-02-28 03:29:12 +00001708
George Rimar55d71782018-04-04 12:36:21 +00001709 // Section's Info field has the index of the first non-local symbol.
1710 // Because the first symbol entry is a null entry, 1 is the first.
1711 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001712
George Rimar55d71782018-04-04 12:36:21 +00001713 if (InX::GnuHashTab) {
1714 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1715 InX::GnuHashTab->addSymbols(Symbols);
1716 } else if (Config->EMachine == EM_MIPS) {
1717 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Peter Smith55865432017-02-20 11:12:33 +00001718 }
George Rimar55d71782018-04-04 12:36:21 +00001719
1720 size_t I = 0;
1721 for (const SymbolTableEntry &S : Symbols)
1722 S.Sym->DynsymIndex = ++I;
Peter Smith1ec42d92017-03-08 14:06:24 +00001723}
Peter Smith55865432017-02-20 11:12:33 +00001724
George Rimar0d6f30e2017-10-18 13:06:18 +00001725// The ELF spec requires that all local symbols precede global symbols, so we
1726// sort symbol entries in this function. (For .dynsym, we don't do that because
1727// symbols for dynamic linking are inherently all globals.)
George Rimarc5526192018-04-11 09:24:27 +00001728//
1729// Aside from above, we put local symbols in groups starting with the STT_FILE
1730// symbol. That is convenient for purpose of identifying where are local symbols
1731// coming from.
George Rimarf45f6812017-05-16 08:53:30 +00001732void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001733 if (this->Type == SHT_DYNSYM)
1734 return;
George Rimarc5526192018-04-11 09:24:27 +00001735
1736 // Move all local symbols before global symbols.
1737 auto E = std::stable_partition(
Rui Ueyama6e967342017-02-28 03:29:12 +00001738 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
Zachary Turnera104d552017-11-03 22:33:49 +00001739 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
Rui Ueyama6e967342017-02-28 03:29:12 +00001740 });
George Rimarc5526192018-04-11 09:24:27 +00001741 size_t NumLocals = E - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001742 getParent()->Info = NumLocals + 1;
George Rimarc5526192018-04-11 09:24:27 +00001743
1744 // Assign the growing unique ID for each local symbol's file.
1745 DenseMap<InputFile *, unsigned> FileIDs;
1746 for (auto I = Symbols.begin(); I != E; ++I)
1747 FileIDs.insert({I->Sym->File, FileIDs.size()});
1748
1749 // Sort the local symbols to group them by file. We do not need to care about
1750 // the STT_FILE symbols, they are already naturally placed first in each group.
1751 // That happens because STT_FILE is always the first symbol in the object and
1752 // hence precede all other local symbols we add for a file.
1753 std::stable_sort(Symbols.begin(), E,
1754 [&](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1755 return FileIDs[L.Sym->File] < FileIDs[R.Sym->File];
1756 });
Eugene Leviant9230db92016-11-17 09:16:34 +00001757}
1758
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001759void SymbolTableBaseSection::addSymbol(Symbol *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001760 // Adding a local symbol to a .dynsym is a bug.
1761 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001762
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001763 bool HashIt = B->isLocal();
1764 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001765}
1766
Rui Ueyama48882242017-11-04 00:31:04 +00001767size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
George Rimar5d6efd12017-09-27 09:08:53 +00001768 // Initializes symbol lookup tables lazily. This is used only
1769 // for -r or -emit-relocs.
1770 llvm::call_once(OnceFlag, [&] {
1771 SymbolIndexMap.reserve(Symbols.size());
1772 size_t I = 0;
1773 for (const SymbolTableEntry &E : Symbols) {
Zachary Turnera104d552017-11-03 22:33:49 +00001774 if (E.Sym->Type == STT_SECTION)
1775 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001776 else
Zachary Turnera104d552017-11-03 22:33:49 +00001777 SymbolIndexMap[E.Sym] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001778 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001779 });
George Rimar5d6efd12017-09-27 09:08:53 +00001780
1781 // Section symbols are mapped based on their output sections
1782 // to maintain their semantics.
Rui Ueyama48882242017-11-04 00:31:04 +00001783 if (Sym->Type == STT_SECTION)
1784 return SectionIndexMap.lookup(Sym->getOutputSection());
1785 return SymbolIndexMap.lookup(Sym);
George Rimar190bac52017-01-23 14:07:23 +00001786}
1787
George Rimarf45f6812017-05-16 08:53:30 +00001788template <class ELFT>
1789SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1790 : SymbolTableBaseSection(StrTabSec) {
1791 this->Entsize = sizeof(Elf_Sym);
1792}
1793
Rui Ueyama1f032532017-02-28 01:56:36 +00001794// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001795template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001796 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001797 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001798 Buf += sizeof(Elf_Sym);
1799
Eugene Leviant9230db92016-11-17 09:16:34 +00001800 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001801
Rui Ueyama1f032532017-02-28 01:56:36 +00001802 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001803 Symbol *Sym = Ent.Sym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001804
Rui Ueyama1b003182017-02-28 19:22:09 +00001805 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001806 ESym->st_other = 0;
Rui Ueyama48882242017-11-04 00:31:04 +00001807 if (Sym->isLocal()) {
1808 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
Rui Ueyama1f032532017-02-28 01:56:36 +00001809 } else {
Rui Ueyama48882242017-11-04 00:31:04 +00001810 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1811 ESym->setVisibility(Sym->Visibility);
Rui Ueyama1f032532017-02-28 01:56:36 +00001812 }
1813
1814 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001815
Rui Ueyama1b003182017-02-28 19:22:09 +00001816 // Set a section index.
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001817 BssSection *CommonSec = nullptr;
1818 if (!Config->DefineCommon)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001819 if (auto *D = dyn_cast<Defined>(Sym))
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001820 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1821 if (CommonSec)
1822 ESym->st_shndx = SHN_COMMON;
Rafael Espindolaab0cce52018-04-26 17:58:58 +00001823 else if (Sym->NeedsPltAddr)
1824 ESym->st_shndx = SHN_UNDEF;
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001825 else if (const OutputSection *OutSec = Sym->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001826 ESym->st_shndx = OutSec->SectionIndex;
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001827 else if (isa<Defined>(Sym))
Eugene Leviant9230db92016-11-17 09:16:34 +00001828 ESym->st_shndx = SHN_ABS;
George Rimar2727ce22017-10-06 09:56:24 +00001829 else
1830 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001831
George Rimardbe843d2017-06-28 09:51:33 +00001832 // Copy symbol size if it is a defined symbol. st_size is not significant
1833 // for undefined symbols, so whether copying it or not is up to us if that's
1834 // the case. We'll leave it as zero because by not setting a value, we can
1835 // get the exact same outputs for two sets of input files that differ only
1836 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001837 if (ESym->st_shndx == SHN_UNDEF)
1838 ESym->st_size = 0;
1839 else
Rui Ueyama48882242017-11-04 00:31:04 +00001840 ESym->st_size = Sym->getSize();
George Rimardbe843d2017-06-28 09:51:33 +00001841
Rui Ueyama1b003182017-02-28 19:22:09 +00001842 // st_value is usually an address of a symbol, but that has a
1843 // special meaining for uninstantiated common symbols (this can
1844 // occur if -r is given).
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001845 if (CommonSec)
1846 ESym->st_value = CommonSec->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001847 else
Rui Ueyama48882242017-11-04 00:31:04 +00001848 ESym->st_value = Sym->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001849
Rui Ueyama1f032532017-02-28 01:56:36 +00001850 ++ESym;
1851 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001852
Rui Ueyama1f032532017-02-28 01:56:36 +00001853 // On MIPS we need to mark symbol which has a PLT entry and requires
1854 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1855 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1856 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1857 if (Config->EMachine == EM_MIPS) {
1858 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1859
1860 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001861 Symbol *Sym = Ent.Sym;
1862 if (Sym->isInPlt() && Sym->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001863 ESym->st_other |= STO_MIPS_PLT;
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001864 if (isMicroMips()) {
1865 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
Simon Atanasyan86a12192018-05-04 20:48:47 +00001866 // a defined microMIPS symbol and symbol should point to its
1867 // PLT entry (in case of microMIPS, PLT entries always contain
1868 // microMIPS code).
1869 if (Sym->isDefined() &&
1870 ((Sym->StOther & STO_MIPS_MICROMIPS) || Sym->NeedsPltAddr)) {
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001871 if (StrTabSec.isDynamic())
1872 ESym->st_value |= 1;
1873 ESym->st_other |= STO_MIPS_MICROMIPS;
1874 }
1875 }
Rui Ueyama1f032532017-02-28 01:56:36 +00001876 if (Config->Relocatable)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001877 if (auto *D = dyn_cast<Defined>(Sym))
Rui Ueyama7957b082017-11-07 00:04:22 +00001878 if (isMipsPIC<ELFT>(D))
Rui Ueyama1f032532017-02-28 01:56:36 +00001879 ESym->st_other |= STO_MIPS_PIC;
1880 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001881 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001882 }
1883}
1884
Rui Ueyamae4120632017-02-28 22:05:13 +00001885// .hash and .gnu.hash sections contain on-disk hash tables that map
1886// symbol names to their dynamic symbol table indices. Their purpose
1887// is to help the dynamic linker resolve symbols quickly. If ELF files
1888// don't have them, the dynamic linker has to do linear search on all
1889// dynamic symbols, which makes programs slower. Therefore, a .hash
1890// section is added to a DSO by default. A .gnu.hash is added if you
1891// give the -hash-style=gnu or -hash-style=both option.
1892//
1893// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1894// Each ELF file has a list of DSOs that the ELF file depends on and a
1895// list of dynamic symbols that need to be resolved from any of the
1896// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1897// where m is the number of DSOs and n is the number of dynamic
1898// symbols. For modern large programs, both m and n are large. So
1899// making each step faster by using hash tables substiantially
1900// improves time to load programs.
1901//
1902// (Note that this is not the only way to design the shared library.
1903// For instance, the Windows DLL takes a different approach. On
1904// Windows, each dynamic symbol has a name of DLL from which the symbol
1905// has to be resolved. That makes the cost of symbol resolution O(n).
1906// This disables some hacky techniques you can use on Unix such as
1907// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1908//
1909// Due to historical reasons, we have two different hash tables, .hash
1910// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1911// and better version of .hash. .hash is just an on-disk hash table, but
1912// .gnu.hash has a bloom filter in addition to a hash table to skip
1913// DSOs very quickly. If you are sure that your dynamic linker knows
1914// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1915// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001916GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001917 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1918}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001919
George Rimarf45f6812017-05-16 08:53:30 +00001920void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001921 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001922
Rui Ueyama517366c2018-01-19 23:54:31 +00001923 // Computes bloom filter size in word size. We want to allocate 12
Rui Ueyamae13373b2017-03-01 02:51:42 +00001924 // bits for each symbol. It must be a power of two.
Rui Ueyama517366c2018-01-19 23:54:31 +00001925 if (Symbols.empty()) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001926 MaskWords = 1;
Rui Ueyama517366c2018-01-19 23:54:31 +00001927 } else {
1928 uint64_t NumBits = Symbols.size() * 12;
1929 MaskWords = NextPowerOf2(NumBits / (Config->Wordsize * 8));
1930 }
Rui Ueyamae13373b2017-03-01 02:51:42 +00001931
George Rimar5f73bc92017-03-29 15:23:28 +00001932 Size = 16; // Header
1933 Size += Config->Wordsize * MaskWords; // Bloom filter
1934 Size += NBuckets * 4; // Hash buckets
1935 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001936}
1937
George Rimarf45f6812017-05-16 08:53:30 +00001938void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamac4e50bf2017-12-06 00:49:48 +00001939 // The output buffer is not guaranteed to be zero-cleared because we pre-
1940 // fill executable sections with trap instructions. This is a precaution
1941 // for that case, which happens only when -no-rosegment is given.
1942 memset(Buf, 0, Size);
1943
Rui Ueyamae13373b2017-03-01 02:51:42 +00001944 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001945 write32(Buf, NBuckets);
1946 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1947 write32(Buf + 8, MaskWords);
Rui Ueyamaba32e732018-03-19 23:04:13 +00001948 write32(Buf + 12, Shift2);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001949 Buf += 16;
1950
Rui Ueyama7986b452017-03-01 18:09:09 +00001951 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001952 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001953 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001954 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001955}
1956
Rui Ueyama7986b452017-03-01 18:09:09 +00001957// This function writes a 2-bit bloom filter. This bloom filter alone
1958// usually filters out 80% or more of all symbol lookups [1].
1959// The dynamic linker uses the hash table only when a symbol is not
1960// filtered out by a bloom filter.
1961//
1962// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1963// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001964void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
Rui Ueyama2f8af792018-01-20 00:14:16 +00001965 unsigned C = Config->Is64 ? 64 : 32;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001966 for (const Entry &Sym : Symbols) {
1967 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001968 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1969 Val |= uint64_t(1) << (Sym.Hash % C);
Rui Ueyamaba32e732018-03-19 23:04:13 +00001970 Val |= uint64_t(1) << ((Sym.Hash >> Shift2) % C);
George Rimar5f73bc92017-03-29 15:23:28 +00001971 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001972 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001973}
1974
George Rimarf45f6812017-05-16 08:53:30 +00001975void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001976 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rafael Espindolaf9f2abe2017-12-07 18:51:19 +00001977 uint32_t OldBucket = -1;
George Rimar5f73bc92017-03-29 15:23:28 +00001978 uint32_t *Values = Buckets + NBuckets;
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001979 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001980 // Write a hash value. It represents a sequence of chains that share the
1981 // same hash modulo value. The last element of each chain is terminated by
1982 // LSB 1.
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001983 uint32_t Hash = I->Hash;
1984 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
1985 Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
1986 write32(Values++, Hash);
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001987
1988 if (I->BucketIdx == OldBucket)
1989 continue;
1990 // Write a hash bucket. Hash buckets contain indices in the following hash
1991 // value table.
1992 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1993 OldBucket = I->BucketIdx;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001994 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001995}
1996
1997static uint32_t hashGnu(StringRef Name) {
1998 uint32_t H = 5381;
1999 for (uint8_t C : Name)
2000 H = (H << 5) + H + C;
2001 return H;
2002}
2003
2004// Add symbols to this symbol hash table. Note that this function
2005// destructively sort a given vector -- which is needed because
2006// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00002007void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00002008 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
2009 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00002010 std::vector<SymbolTableEntry>::iterator Mid =
2011 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Peter Collingbourneb472aa02017-11-06 04:39:07 +00002012 return !S.Sym->isDefined();
Eugene Leviantbe809a72016-11-18 06:44:18 +00002013 });
George Rimar2ab93622018-03-14 08:52:39 +00002014
Rui Ueyama4e6b8222018-03-14 19:01:00 +00002015 // We chose load factor 4 for the on-disk hash table. For each hash
2016 // collision, the dynamic linker will compare a uint32_t hash value.
2017 // Since the integer comparison is quite fast, we believe we can
2018 // make the load factor even larger. 4 is just a conservative choice.
2019 //
2020 // Note that we don't want to create a zero-sized hash table because
2021 // Android loader as of 2018 doesn't like a .gnu.hash containing such
2022 // table. If that's the case, we create a hash table with one unused
2023 // dummy slot.
George Rimar2ab93622018-03-14 08:52:39 +00002024 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
2025
Eugene Leviantbe809a72016-11-18 06:44:18 +00002026 if (Mid == V.end())
2027 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00002028
Rui Ueyama22788262017-12-02 00:37:13 +00002029 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
2030 Symbol *B = Ent.Sym;
2031 uint32_t Hash = hashGnu(B->getName());
2032 uint32_t BucketIdx = Hash % NBuckets;
2033 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
2034 }
2035
2036 std::stable_sort(
2037 Symbols.begin(), Symbols.end(),
2038 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
Eugene Leviantbe809a72016-11-18 06:44:18 +00002039
2040 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00002041 for (const Entry &Ent : Symbols)
Rui Ueyama48882242017-11-04 00:31:04 +00002042 V.push_back({Ent.Sym, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00002043}
2044
George Rimaraaf54712017-09-27 09:14:59 +00002045HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00002046 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
2047 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002048}
2049
George Rimaraaf54712017-09-27 09:14:59 +00002050void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002051 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002052
George Rimar67c60722017-07-18 11:55:35 +00002053 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00002054 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00002055
2056 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00002057 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00002058 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002059}
2060
George Rimaraaf54712017-09-27 09:14:59 +00002061void HashTableSection::writeTo(uint8_t *Buf) {
Shoaib Meenaid79bbf42018-01-11 06:57:01 +00002062 // See comment in GnuHashTableSection::writeTo.
2063 memset(Buf, 0, Size);
2064
George Rimar69b17c32017-05-16 10:04:42 +00002065 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00002066
George Rimaraaf54712017-09-27 09:14:59 +00002067 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00002068 write32(P++, NumSymbols); // nbucket
2069 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00002070
George Rimaraaf54712017-09-27 09:14:59 +00002071 uint32_t *Buckets = P;
2072 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002073
George Rimar69b17c32017-05-16 10:04:42 +00002074 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Rui Ueyama48882242017-11-04 00:31:04 +00002075 Symbol *Sym = S.Sym;
2076 StringRef Name = Sym->getName();
2077 unsigned I = Sym->DynsymIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00002078 uint32_t Hash = hashSysV(Name) % NumSymbols;
2079 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00002080 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00002081 }
2082}
2083
Sean Fertile49914cc2018-05-09 02:07:53 +00002084// On PowerPC64 the lazy symbol resolvers go into the `global linkage table`
2085// in the .glink section, rather then the typical .plt section.
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00002086PltSection::PltSection(bool IsIplt)
Sean Fertile49914cc2018-05-09 02:07:53 +00002087 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16,
2088 Config->EMachine == EM_PPC64 ? ".glink" : ".plt"),
Rui Ueyamae2dfdbf2018-01-12 22:29:29 +00002089 HeaderSize(IsIplt ? 0 : Target->PltHeaderSize), IsIplt(IsIplt) {
Rui Ueyama0cc14832017-06-28 17:05:39 +00002090 // The PLT needs to be writable on SPARC as the dynamic linker will
2091 // modify the instructions in the PLT entries.
2092 if (Config->EMachine == EM_SPARCV9)
2093 this->Flags |= SHF_WRITE;
2094}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002095
George Rimardfc020e2017-03-17 11:01:57 +00002096void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00002097 // At beginning of PLT but not the IPLT, we have code to call the dynamic
2098 // linker to resolve dynsyms at runtime. Write such code.
George Rimar9fc2c642018-01-12 09:35:57 +00002099 if (!IsIplt)
Peter Smithf09245a2017-02-09 10:56:15 +00002100 Target->writePltHeader(Buf);
2101 size_t Off = HeaderSize;
2102 // The IPlt is immediately after the Plt, account for this in RelOff
2103 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002104
2105 for (auto &I : Entries) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002106 const Symbol *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00002107 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00002108 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002109 uint64_t Plt = this->getVA() + Off;
2110 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
2111 Off += Target->PltEntrySize;
2112 }
2113}
2114
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002115template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002116 Sym.PltIndex = Entries.size();
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002117 RelocationBaseSection *PltRelocSection = InX::RelaPlt;
George Rimar9fc2c642018-01-12 09:35:57 +00002118 if (IsIplt) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002119 PltRelocSection = InX::RelaIplt;
Peter Smithf09245a2017-02-09 10:56:15 +00002120 Sym.IsInIplt = true;
2121 }
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002122 unsigned RelOff =
2123 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002124 Entries.push_back(std::make_pair(&Sym, RelOff));
2125}
2126
George Rimardfc020e2017-03-17 11:01:57 +00002127size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00002128 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002129}
2130
Peter Smith96943762017-01-25 10:31:16 +00002131// Some architectures such as additional symbols in the PLT section. For
2132// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00002133void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00002134 // The PLT may have symbols defined for the Header, the IPLT has no header
George Rimar9fc2c642018-01-12 09:35:57 +00002135 if (!IsIplt)
Rafael Espindola1037eef2017-12-19 23:59:35 +00002136 Target->addPltHeaderSymbols(*this);
Peter Smithf09245a2017-02-09 10:56:15 +00002137 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00002138 for (size_t I = 0; I < Entries.size(); ++I) {
Rafael Espindola1037eef2017-12-19 23:59:35 +00002139 Target->addPltSymbols(*this, Off);
Peter Smith96943762017-01-25 10:31:16 +00002140 Off += Target->PltEntrySize;
2141 }
2142}
2143
George Rimardfc020e2017-03-17 11:01:57 +00002144unsigned PltSection::getPltRelocOff() const {
George Rimar9fc2c642018-01-12 09:35:57 +00002145 return IsIplt ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00002146}
2147
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002148// The string hash function for .gdb_index.
2149static uint32_t computeGdbHash(StringRef S) {
2150 uint32_t H = 0;
2151 for (uint8_t C : S)
2152 H = H * 67 + tolower(C) - 113;
2153 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00002154}
2155
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002156static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
2157 std::vector<GdbIndexChunk::CuEntry> Ret;
2158 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
2159 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002160 return Ret;
2161}
2162
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002163static std::vector<GdbIndexChunk::AddressEntry>
2164readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
2165 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002166
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002167 uint32_t CuIdx = 0;
2168 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002169 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002170 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002171
George Rimar35e846e2017-03-21 08:19:34 +00002172 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00002173 for (DWARFAddressRange &R : Ranges) {
2174 InputSectionBase *S = Sections[R.SectionIndex];
2175 if (!S || S == &InputSection::Discarded || !S->Live)
2176 continue;
2177 // Range list with zero size has no effect.
2178 if (R.LowPC == R.HighPC)
2179 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00002180 auto *IS = cast<InputSection>(S);
2181 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002182 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00002183 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002184 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002185 }
2186 return Ret;
2187}
2188
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002189static std::vector<GdbIndexChunk::NameTypeEntry>
2190readPubNamesAndTypes(DWARFContext &Dwarf) {
2191 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
2192 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002193
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002194 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
2195 for (StringRef Sec : {Sec1, Sec2}) {
2196 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00002197 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
2198 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
2199 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
2200 Ret.push_back({S, Ent.Descriptor.toBits()});
2201 }
2202 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00002203 }
2204 return Ret;
2205}
2206
George Rimar86665622017-06-07 16:59:11 +00002207static std::vector<InputSection *> getDebugInfoSections() {
2208 std::vector<InputSection *> Ret;
2209 for (InputSectionBase *S : InputSections)
2210 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00002211 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00002212 Ret.push_back(IS);
2213 return Ret;
2214}
2215
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002216void GdbIndexSection::fixCuIndex() {
2217 uint32_t Idx = 0;
2218 for (GdbIndexChunk &Chunk : Chunks) {
2219 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
2220 Ent.CuIndex += Idx;
2221 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00002222 }
2223}
2224
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002225std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2226 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002227 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002228 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002229
2230 for (GdbIndexChunk &Chunk : Chunks) {
2231 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002232 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002233 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002234 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2235 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002236 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002237 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002238
2239 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2240 // duplicate entries, so we want to dedup them.
2241 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2242 uint32_t Val = (Ent.Type << 24) | Idx;
2243 if (Vec.empty() || Vec.back() != Val)
2244 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002245 }
2246 Idx += Chunk.CompilationUnits.size();
2247 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002248
2249 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002250 return Ret;
2251}
George Rimar8b547392016-12-15 09:08:13 +00002252
Rafael Espindola300b3862017-07-12 23:56:53 +00002253template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002254 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002255 std::vector<InputSection *> Sections = getDebugInfoSections();
2256 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002257
George Rimar2d23da02017-08-01 14:57:13 +00002258 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002259 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2260 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2261
2262 Chunks[I].DebugInfoSec = Sections[I];
2263 Chunks[I].CompilationUnits = readCuList(Dwarf);
2264 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2265 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002266 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002267
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002268 // .debug_gnu_pub{names,types} are useless in executables.
2269 // They are present in input object files solely for creating
2270 // a .gdb_index. So we can remove it from the output.
2271 for (InputSectionBase *S : InputSections)
2272 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2273 S->Live = false;
2274
2275 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002276 return make<GdbIndexSection>(std::move(Chunks));
2277}
2278
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002279static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002280 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002281 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002282 Ret += D.CompilationUnits.size();
2283 return Ret;
2284}
George Rimarec02b8d2016-12-15 12:07:53 +00002285
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002286static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002287 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002288 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002289 Ret += D.AddressAreas.size();
2290 return Ret;
2291}
2292
2293std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002294 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2295 if (Size < 1024)
2296 Size = 1024;
2297
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002298 uint32_t Mask = Size - 1;
2299 std::vector<GdbSymbol *> Ret(Size);
2300
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002301 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002302 GdbSymbol *Sym = KV.second;
2303 uint32_t I = Sym->NameHash & Mask;
2304 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2305
2306 while (Ret[I])
2307 I = (I + Step) & Mask;
2308 Ret[I] = Sym;
2309 }
George Rimar86665622017-06-07 16:59:11 +00002310 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002311}
2312
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002313GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002314 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002315 fixCuIndex();
2316 CuVectors = createCuVectors();
2317 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002318
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002319 // Compute offsets early to know the section size.
2320 // Each chunk size needs to be in sync with what we write in writeTo.
2321 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2322 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2323 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002324
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002325 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002326 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002327 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002328 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002329 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002330 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002331}
2332
George Rimar35e846e2017-03-21 08:19:34 +00002333size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002334 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002335}
2336
George Rimar35e846e2017-03-21 08:19:34 +00002337void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002338 // Write the section header.
2339 write32le(Buf, 7);
2340 write32le(Buf + 4, CuListOffset);
2341 write32le(Buf + 8, CuTypesOffset);
2342 write32le(Buf + 12, CuTypesOffset);
2343 write32le(Buf + 16, SymtabOffset);
2344 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002345 Buf += 24;
2346
2347 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002348 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002349 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002350 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002351 write64le(Buf + 8, Cu.CuLength);
2352 Buf += 16;
2353 }
Eugene Levianta113a412016-11-21 09:24:43 +00002354 }
George Rimar8b547392016-12-15 09:08:13 +00002355
2356 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002357 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002358 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
Rafael Espindola4f058a22018-03-24 00:35:11 +00002359 uint64_t BaseAddr = E.Section->getVA(0);
George Rimar86665622017-06-07 16:59:11 +00002360 write64le(Buf, BaseAddr + E.LowAddress);
2361 write64le(Buf + 8, BaseAddr + E.HighAddress);
2362 write32le(Buf + 16, E.CuIndex);
2363 Buf += 20;
2364 }
George Rimar8b547392016-12-15 09:08:13 +00002365 }
George Rimarec02b8d2016-12-15 12:07:53 +00002366
2367 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002368 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002369 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002370 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2371 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002372 }
2373 Buf += 8;
2374 }
2375
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002376 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002377 for (ArrayRef<uint32_t> Vec : CuVectors) {
2378 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002379 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002380 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002381 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002382 Buf += 4;
2383 }
2384 }
2385
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002386 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002387 for (auto &KV : Symbols) {
2388 CachedHashStringRef S = KV.first;
2389 GdbSymbol *Sym = KV.second;
2390 size_t Off = Sym->NameOffset;
2391 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002392 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002393 }
Eugene Levianta113a412016-11-21 09:24:43 +00002394}
2395
George Rimar67c60722017-07-18 11:55:35 +00002396bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002397
Rui Ueyama02551ab2017-10-27 03:14:24 +00002398EhFrameHeader::EhFrameHeader()
Rafael Espindola6b2b4502018-01-23 05:23:23 +00002399 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 4, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002400
2401// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2402// Each entry of the search table consists of two values,
2403// the starting PC from where FDEs covers, and the FDE's address.
2404// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002405void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002406 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002407
Rui Ueyama02551ab2017-10-27 03:14:24 +00002408 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002409
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002410 // Sort the FDE list by their PC and uniqueify. Usually there is only
2411 // one FDE for a PC (i.e. function), but if ICF merges two functions
2412 // into one, there can be more than one FDEs pointing to the address.
2413 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2414 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2415 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2416 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2417
2418 Buf[0] = 1;
2419 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2420 Buf[2] = DW_EH_PE_udata4;
2421 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002422 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2423 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002424 Buf += 12;
2425
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002426 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002427 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002428 write32(Buf, Fde.Pc - VA);
2429 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002430 Buf += 8;
2431 }
2432}
2433
Rui Ueyama02551ab2017-10-27 03:14:24 +00002434size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002435 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002436 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002437}
2438
Rui Ueyama02551ab2017-10-27 03:14:24 +00002439bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002440
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002441template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002442VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002443 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2444 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002445
2446static StringRef getFileDefName() {
2447 if (!Config->SoName.empty())
2448 return Config->SoName;
2449 return Config->OutputFile;
2450}
2451
Rui Ueyama945055a2017-02-27 03:07:41 +00002452template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002453 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002454 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002455 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002456
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002457 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002458
2459 // sh_info should be set to the number of definitions. This fact is missed in
2460 // documentation, but confirmed by binutils community:
2461 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002462 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002463}
2464
2465template <class ELFT>
2466void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2467 StringRef Name, size_t NameOff) {
2468 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2469 Verdef->vd_version = 1;
2470 Verdef->vd_cnt = 1;
2471 Verdef->vd_aux = sizeof(Elf_Verdef);
2472 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2473 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2474 Verdef->vd_ndx = Index;
2475 Verdef->vd_hash = hashSysV(Name);
2476
2477 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2478 Verdaux->vda_name = NameOff;
2479 Verdaux->vda_next = 0;
2480}
2481
2482template <class ELFT>
2483void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2484 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2485
2486 for (VersionDefinition &V : Config->VersionDefinitions) {
2487 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2488 writeOne(Buf, V.Id, V.Name, V.NameOff);
2489 }
2490
2491 // Need to terminate the last version definition.
2492 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2493 Verdef->vd_next = 0;
2494}
2495
2496template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2497 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2498}
2499
2500template <class ELFT>
2501VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002502 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002503 ".gnu.version") {
2504 this->Entsize = sizeof(Elf_Versym);
2505}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002506
Rui Ueyama945055a2017-02-27 03:07:41 +00002507template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002508 // At the moment of june 2016 GNU docs does not mention that sh_link field
2509 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002510 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002511}
2512
2513template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002514 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002515}
2516
2517template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2518 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002519 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Zachary Turnera104d552017-11-03 22:33:49 +00002520 OutVersym->vs_index = S.Sym->VersionId;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002521 ++OutVersym;
2522 }
2523}
2524
George Rimar11992c862016-11-25 08:05:41 +00002525template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2526 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2527}
2528
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002529template <class ELFT>
2530VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002531 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2532 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002533 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2534 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2535 // First identifiers are reserved by verdef section if it exist.
2536 NextIndex = getVerDefNum() + 1;
2537}
2538
Rafael Espindolaab0cce52018-04-26 17:58:58 +00002539template <class ELFT> void VersionNeedSection<ELFT>::addSymbol(Symbol *SS) {
2540 auto &File = cast<SharedFile<ELFT>>(*SS->File);
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002541 if (SS->VerdefIndex == VER_NDX_GLOBAL) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002542 SS->VersionId = VER_NDX_GLOBAL;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002543 return;
2544 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002545
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002546 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2547 // to create one by adding it to our needed list and creating a dynstr entry
2548 // for the soname.
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002549 if (File.VerdefMap.empty())
2550 Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)});
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002551 const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex];
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002552 typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver];
Rui Ueyamad37c33a2018-03-24 00:25:24 +00002553
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002554 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2555 // prepare to create one by allocating a version identifier and creating a
2556 // dynstr entry for the version name.
2557 if (NV.Index == 0) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002558 NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() +
Rafael Espindola895aea62017-05-11 22:02:41 +00002559 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002560 NV.Index = NextIndex++;
2561 }
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002562 SS->VersionId = NV.Index;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002563}
2564
2565template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2566 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2567 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2568 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2569
2570 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2571 // Create an Elf_Verneed for this DSO.
2572 Verneed->vn_version = 1;
2573 Verneed->vn_cnt = P.first->VerdefMap.size();
2574 Verneed->vn_file = P.second;
2575 Verneed->vn_aux =
2576 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2577 Verneed->vn_next = sizeof(Elf_Verneed);
2578 ++Verneed;
2579
2580 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2581 // VerdefMap, which will only contain references to needed version
2582 // definitions. Each Elf_Vernaux is based on the information contained in
2583 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2584 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2585 // data structures within a single input file.
2586 for (auto &NV : P.first->VerdefMap) {
2587 Vernaux->vna_hash = NV.first->vd_hash;
2588 Vernaux->vna_flags = 0;
2589 Vernaux->vna_other = NV.second.Index;
2590 Vernaux->vna_name = NV.second.StrTab;
2591 Vernaux->vna_next = sizeof(Elf_Vernaux);
2592 ++Vernaux;
2593 }
2594
2595 Vernaux[-1].vna_next = 0;
2596 }
2597 Verneed[-1].vn_next = 0;
2598}
2599
Rui Ueyama945055a2017-02-27 03:07:41 +00002600template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002601 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2602 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002603}
2604
2605template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2606 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2607 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2608 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2609 return Size;
2610}
2611
George Rimar11992c862016-11-25 08:05:41 +00002612template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2613 return getNeedNum() == 0;
2614}
2615
Rafael Espindola6119b862017-03-06 20:23:56 +00002616void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002617 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002618 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002619}
2620
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002621MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2622 uint64_t Flags, uint32_t Alignment)
2623 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2624 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002625
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002626size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2627
2628void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002629
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002630void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002631 // Add all string pieces to the string table builder to create section
2632 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002633 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002634 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2635 if (Sec->Pieces[I].Live)
2636 Builder.add(Sec->getData(I));
2637
2638 // Fix the string table content. After this, the contents will never change.
2639 Builder.finalize();
2640
2641 // finalize() fixed tail-optimized strings, so we can now get
2642 // offsets of strings. Get an offset for each string and save it
2643 // to a corresponding StringPiece for easy access.
Rafael Espindola7bd45502018-04-05 00:01:57 +00002644 for (MergeInputSection *Sec : Sections)
2645 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2646 if (Sec->Pieces[I].Live)
2647 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002648}
2649
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002650void MergeNoTailSection::writeTo(uint8_t *Buf) {
2651 for (size_t I = 0; I < NumShards; ++I)
2652 Shards[I].write(Buf + ShardOffsets[I]);
2653}
2654
2655// This function is very hot (i.e. it can take several seconds to finish)
2656// because sometimes the number of inputs is in an order of magnitude of
2657// millions. So, we use multi-threading.
2658//
2659// For any strings S and T, we know S is not mergeable with T if S's hash
2660// value is different from T's. If that's the case, we can safely put S and
2661// T into different string builders without worrying about merge misses.
2662// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002663void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002664 // Initializes string table builders.
2665 for (size_t I = 0; I < NumShards; ++I)
2666 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2667
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002668 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2669 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002670 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002671 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002672 Concurrency =
2673 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002674
2675 // Add section pieces to the builders.
2676 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2677 for (MergeInputSection *Sec : Sections) {
2678 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
Rui Ueyama95bf5092017-10-21 23:20:13 +00002679 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Dimitry Andric656714a2018-01-11 08:03:22 +00002680 if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002681 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002682 }
2683 }
2684 });
2685
2686 // Compute an in-section offset for each shard.
2687 size_t Off = 0;
2688 for (size_t I = 0; I < NumShards; ++I) {
2689 Shards[I].finalizeInOrder();
2690 if (Shards[I].getSize() > 0)
2691 Off = alignTo(Off, Alignment);
2692 ShardOffsets[I] = Off;
2693 Off += Shards[I].getSize();
2694 }
2695 Size = Off;
2696
2697 // So far, section pieces have offsets from beginning of shards, but
2698 // we want offsets from beginning of the whole section. Fix them.
2699 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola7bd45502018-04-05 00:01:57 +00002700 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2701 if (Sec->Pieces[I].Live)
2702 Sec->Pieces[I].OutputOff +=
2703 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002704 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002705}
2706
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002707static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2708 uint32_t Type,
2709 uint64_t Flags,
2710 uint32_t Alignment) {
2711 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2712 if (ShouldTailMerge)
2713 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2714 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002715}
2716
Rui Ueyamaac114d22018-02-12 21:56:14 +00002717// Debug sections may be compressed by zlib. Decompress if exists.
Rui Ueyama2b714b52017-10-11 03:12:53 +00002718void elf::decompressSections() {
Rafael Espindola9bf10062018-04-27 16:29:57 +00002719 parallelForEach(InputSections,
2720 [](InputSectionBase *Sec) { Sec->maybeDecompress(); });
2721}
2722
Rafael Espindolaf1652d42018-04-27 18:17:36 +00002723template <class ELFT> void elf::splitSections() {
Rafael Espindola9bf10062018-04-27 16:29:57 +00002724 // splitIntoPieces needs to be called on each MergeInputSection
2725 // before calling finalizeContents().
Rui Ueyama2b714b52017-10-11 03:12:53 +00002726 parallelForEach(InputSections, [](InputSectionBase *Sec) {
Rafael Espindola9bf10062018-04-27 16:29:57 +00002727 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2728 S->splitIntoPieces();
Rafael Espindolaf1652d42018-04-27 18:17:36 +00002729 else if (auto *Eh = dyn_cast<EhInputSection>(Sec))
2730 Eh->split<ELFT>();
Rui Ueyama2b714b52017-10-11 03:12:53 +00002731 });
2732}
2733
2734// This function scans over the inputsections to create mergeable
2735// synthetic sections.
2736//
2737// It removes MergeInputSections from the input section array and adds
2738// new synthetic sections at the location of the first input section
2739// that it replaces. It then finalizes each synthetic section in order
2740// to compute an output offset for each piece of each input section.
2741void elf::mergeSections() {
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002742 std::vector<MergeSyntheticSection *> MergeSections;
2743 for (InputSectionBase *&S : InputSections) {
2744 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2745 if (!MS)
2746 continue;
2747
2748 // We do not want to handle sections that are not alive, so just remove
2749 // them instead of trying to merge.
2750 if (!MS->Live)
2751 continue;
2752
George Rimar78e27e82017-12-01 09:04:52 +00002753 StringRef OutsecName = getOutputSectionName(MS);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002754 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2755
2756 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002757 // While we could create a single synthetic section for two different
2758 // values of Entsize, it is better to take Entsize into consideration.
2759 //
2760 // With a single synthetic section no two pieces with different Entsize
2761 // could be equal, so we may as well have two sections.
2762 //
2763 // Using Entsize in here also allows us to propagate it to the synthetic
2764 // section.
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002765 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002766 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002767 });
2768 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002769 MergeSyntheticSection *Syn =
2770 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002771 MergeSections.push_back(Syn);
2772 I = std::prev(MergeSections.end());
2773 S = Syn;
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002774 Syn->Entsize = MS->Entsize;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002775 } else {
2776 S = nullptr;
2777 }
2778 (*I)->addSection(MS);
2779 }
Rafael Espindola6cd7af52018-04-03 21:38:18 +00002780 for (auto *MS : MergeSections)
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002781 MS->finalizeContents();
2782
2783 std::vector<InputSectionBase *> &V = InputSections;
2784 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2785}
2786
George Rimar42886c42017-03-15 12:02:31 +00002787MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002788 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2789 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002790
George Rimar90a528b2017-03-21 09:01:39 +00002791ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002792 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002793 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002794
2795// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2796// This section will have been sorted last in the .ARM.exidx table.
2797// This table entry will have the form:
2798// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002799// The sentinel must have the PREL31 value of an address higher than any
2800// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002801void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Igor Kudrinf01caab2017-12-14 06:23:50 +00002802 assert(Highest);
Rafael Espindola4f058a22018-03-24 00:35:11 +00002803 uint64_t S = Highest->getVA(Highest->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002804 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002805 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002806 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002807}
2808
Igor Kudrin5966d152017-12-20 08:56:10 +00002809// The sentinel has to be removed if there are no other .ARM.exidx entries.
2810bool ARMExidxSentinelSection::empty() const {
George Rimar563e4f22018-02-22 09:55:28 +00002811 for (InputSection *IS : getInputSections(getParent()))
2812 if (!isa<ARMExidxSentinelSection>(IS))
2813 return false;
Igor Kudrin5966d152017-12-20 08:56:10 +00002814 return true;
2815}
2816
George Rimar7b827042017-03-16 10:40:50 +00002817ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002818 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002819 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002820 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002821 this->OutSecOff = Off;
2822}
2823
George Rimar7b827042017-03-16 10:40:50 +00002824void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002825 Thunks.push_back(T);
2826 T->addSymbols(*this);
Peter Smith3a52eb02017-02-01 10:26:03 +00002827}
2828
George Rimar7b827042017-03-16 10:40:50 +00002829void ThunkSection::writeTo(uint8_t *Buf) {
Peter Collingbournecebab4a2018-03-28 21:33:31 +00002830 for (Thunk *T : Thunks)
2831 T->writeTo(Buf + T->Offset);
Peter Smith3a52eb02017-02-01 10:26:03 +00002832}
2833
George Rimar7b827042017-03-16 10:40:50 +00002834InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002835 if (Thunks.empty())
2836 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002837 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002838 return T->getTargetInputSection();
2839}
2840
Peter Collingbournec5391ce2018-03-29 22:32:13 +00002841bool ThunkSection::assignOffsets() {
2842 uint64_t Off = 0;
2843 for (Thunk *T : Thunks) {
2844 Off = alignTo(Off, T->Alignment);
2845 T->setOffset(Off);
2846 uint32_t Size = T->size();
2847 T->getThunkTargetSym()->Size = Size;
2848 Off += Size;
2849 }
2850 bool Changed = Off != Size;
2851 Size = Off;
2852 return Changed;
2853}
2854
George Rimar9782ca52017-03-15 15:29:29 +00002855InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002856BssSection *InX::Bss;
2857BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002858BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002859EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002860EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002861SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002862StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002863SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002864InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002865GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002866GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002867GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002868GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002869HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002870IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002871MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002872MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002873PltSection *InX::Plt;
2874PltSection *InX::Iplt;
Rafael Espindola58946cd2017-12-10 19:44:42 +00002875RelocationBaseSection *InX::RelaDyn;
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002876RelocationBaseSection *InX::RelaPlt;
2877RelocationBaseSection *InX::RelaIplt;
George Rimar9782ca52017-03-15 15:29:29 +00002878StringTableSection *InX::ShStrTab;
2879StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002880SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002881
Rafael Espindola300b3862017-07-12 23:56:53 +00002882template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2883template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2884template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2885template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2886
Rafael Espindolaf1652d42018-04-27 18:17:36 +00002887template void elf::splitSections<ELF32LE>();
2888template void elf::splitSections<ELF32BE>();
2889template void elf::splitSections<ELF64LE>();
2890template void elf::splitSections<ELF64BE>();
2891
Rui Ueyama572247f2017-10-27 03:13:39 +00002892template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2893template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2894template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2895template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2896
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002897template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2898template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2899template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2900template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
George Rimara9189572017-03-17 16:50:07 +00002901
Simon Atanasyaned9ee692018-06-11 07:24:31 +00002902template void MipsGotSection::build<ELF32LE>();
2903template void MipsGotSection::build<ELF32BE>();
2904template void MipsGotSection::build<ELF64LE>();
2905template void MipsGotSection::build<ELF64BE>();
2906
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002907template class elf::MipsAbiFlagsSection<ELF32LE>;
2908template class elf::MipsAbiFlagsSection<ELF32BE>;
2909template class elf::MipsAbiFlagsSection<ELF64LE>;
2910template class elf::MipsAbiFlagsSection<ELF64BE>;
2911
Simon Atanasyance02cf02016-11-09 21:36:56 +00002912template class elf::MipsOptionsSection<ELF32LE>;
2913template class elf::MipsOptionsSection<ELF32BE>;
2914template class elf::MipsOptionsSection<ELF64LE>;
2915template class elf::MipsOptionsSection<ELF64BE>;
2916
2917template class elf::MipsReginfoSection<ELF32LE>;
2918template class elf::MipsReginfoSection<ELF32BE>;
2919template class elf::MipsReginfoSection<ELF64LE>;
2920template class elf::MipsReginfoSection<ELF64BE>;
2921
Eugene Leviant6380ce22016-11-15 12:26:55 +00002922template class elf::DynamicSection<ELF32LE>;
2923template class elf::DynamicSection<ELF32BE>;
2924template class elf::DynamicSection<ELF64LE>;
2925template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002926
2927template class elf::RelocationSection<ELF32LE>;
2928template class elf::RelocationSection<ELF32BE>;
2929template class elf::RelocationSection<ELF64LE>;
2930template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002931
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002932template class elf::AndroidPackedRelocationSection<ELF32LE>;
2933template class elf::AndroidPackedRelocationSection<ELF32BE>;
2934template class elf::AndroidPackedRelocationSection<ELF64LE>;
2935template class elf::AndroidPackedRelocationSection<ELF64BE>;
2936
Eugene Leviant9230db92016-11-17 09:16:34 +00002937template class elf::SymbolTableSection<ELF32LE>;
2938template class elf::SymbolTableSection<ELF32BE>;
2939template class elf::SymbolTableSection<ELF64LE>;
2940template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002941
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002942template class elf::VersionTableSection<ELF32LE>;
2943template class elf::VersionTableSection<ELF32BE>;
2944template class elf::VersionTableSection<ELF64LE>;
2945template class elf::VersionTableSection<ELF64BE>;
2946
2947template class elf::VersionNeedSection<ELF32LE>;
2948template class elf::VersionNeedSection<ELF32BE>;
2949template class elf::VersionNeedSection<ELF64LE>;
2950template class elf::VersionNeedSection<ELF64BE>;
2951
2952template class elf::VersionDefinitionSection<ELF32LE>;
2953template class elf::VersionDefinitionSection<ELF32BE>;
2954template class elf::VersionDefinitionSection<ELF64LE>;
2955template class elf::VersionDefinitionSection<ELF64BE>;