blob: 79fd0ef298f3320b4e3d3272ff95358e53eccd3c [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"
23#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000024#include "SymbolTable.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"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000029#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000030#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000031#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000032#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000033#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000034#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000035#include "llvm/Support/Endian.h"
Peter Collingbourne5c54f152017-10-27 17:49:40 +000036#include "llvm/Support/LEB128.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000037#include "llvm/Support/MD5.h"
38#include "llvm/Support/RandomNumberGenerator.h"
39#include "llvm/Support/SHA1.h"
40#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000041#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000042#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000043
44using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000045using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000046using namespace llvm::ELF;
47using namespace llvm::object;
48using namespace llvm::support;
49using namespace llvm::support::endian;
50
51using namespace lld;
52using namespace lld::elf;
53
NAKAMURA Takumi70947e22017-09-30 13:40:22 +000054constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000055
Rui Ueyama79048e42017-10-27 03:59:34 +000056static void write32(void *Buf, uint32_t Val) {
57 endian::write32(Buf, Val, Config->Endianness);
58}
59
Rui Ueyama9320cb02017-02-27 02:56:02 +000060uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000061 if (OutputSection *Sec = getParent())
62 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000063 return 0;
64}
65
Rui Ueyama3da3f062016-11-10 20:20:37 +000066// Returns an LLD version string.
67static ArrayRef<uint8_t> getVersion() {
68 // Check LLD_VERSION first for ease of testing.
69 // You can get consitent output by using the environment variable.
70 // This is only for testing.
71 StringRef S = getenv("LLD_VERSION");
72 if (S.empty())
73 S = Saver.save(Twine("Linker: ") + getLLDVersion());
74
75 // +1 to include the terminating '\0'.
76 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000077}
Rui Ueyama3da3f062016-11-10 20:20:37 +000078
79// Creates a .comment section containing LLD version info.
80// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000081// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000082// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +000083template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +000084 typename ELFT::Shdr Hdr = {};
85 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
86 Hdr.sh_type = SHT_PROGBITS;
87 Hdr.sh_entsize = 1;
88 Hdr.sh_addralign = 1;
89
Rafael Espindola6119b862017-03-06 20:23:56 +000090 auto *Ret =
Rui Ueyama709fb2bb12017-07-26 22:13:32 +000091 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +000092 Ret->Data = getVersion();
Rui Ueyama3da3f062016-11-10 20:20:37 +000093 return Ret;
94}
95
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000096// .MIPS.abiflags section.
97template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +000098MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +000099 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000100 Flags(Flags) {
101 this->Entsize = sizeof(Elf_Mips_ABIFlags);
102}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000103
104template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
105 memcpy(Buf, &Flags, sizeof(Flags));
106}
107
108template <class ELFT>
109MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
110 Elf_Mips_ABIFlags Flags = {};
111 bool Create = false;
112
Rui Ueyama536a2672017-02-27 02:32:08 +0000113 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000114 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000115 continue;
116 Sec->Live = false;
117 Create = true;
118
Rui Ueyama25f30882017-10-27 03:25:04 +0000119 std::string Filename = toString(Sec->File);
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000120 const size_t Size = Sec->Data.size();
121 // Older version of BFD (such as the default FreeBSD linker) concatenate
122 // .MIPS.abiflags instead of merging. To allow for this case (or potential
123 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
124 if (Size < sizeof(Elf_Mips_ABIFlags)) {
125 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
126 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000127 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000128 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000129 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000130 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000131 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000132 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000133 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000134 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000135
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000136 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000137 // select the highest number of ISA/Rev/Ext.
138 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
139 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
140 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
141 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
142 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
143 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
144 Flags.ases |= S->ases;
145 Flags.flags1 |= S->flags1;
146 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000147 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000148 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000149
Rui Ueyama12f2da82016-11-22 03:57:06 +0000150 if (Create)
151 return make<MipsAbiFlagsSection<ELFT>>(Flags);
152 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000153}
154
Simon Atanasyance02cf02016-11-09 21:36:56 +0000155// .MIPS.options section.
156template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000157MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000158 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000159 Reginfo(Reginfo) {
160 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
161}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000162
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000163template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
164 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
165 Options->kind = ODK_REGINFO;
166 Options->size = getSize();
167
168 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000169 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000170 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000171}
172
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000173template <class ELFT>
174MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
175 // N64 ABI only.
176 if (!ELFT::Is64Bits)
177 return nullptr;
178
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000179 std::vector<InputSectionBase *> Sections;
180 for (InputSectionBase *Sec : InputSections)
181 if (Sec->Type == SHT_MIPS_OPTIONS)
182 Sections.push_back(Sec);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000183
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000184 if (Sections.empty())
185 return nullptr;
186
187 Elf_Mips_RegInfo Reginfo = {};
188 for (InputSectionBase *Sec : Sections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000189 Sec->Live = false;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000190
Rui Ueyama25f30882017-10-27 03:25:04 +0000191 std::string Filename = toString(Sec->File);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000192 ArrayRef<uint8_t> D = Sec->Data;
193
194 while (!D.empty()) {
195 if (D.size() < sizeof(Elf_Mips_Options)) {
196 error(Filename + ": invalid size of .MIPS.options section");
197 break;
198 }
199
200 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
201 if (Opt->kind == ODK_REGINFO) {
202 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
203 error(Filename + ": unsupported non-zero ri_gp_value");
204 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000205 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000206 break;
207 }
208
209 if (!Opt->size)
210 fatal(Filename + ": zero option descriptor size");
211 D = D.slice(Opt->size);
212 }
213 };
214
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000215 return make<MipsOptionsSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000216}
217
218// MIPS .reginfo section.
219template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000220MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000221 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000222 Reginfo(Reginfo) {
223 this->Entsize = sizeof(Elf_Mips_RegInfo);
224}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000225
Rui Ueyamab71cae92016-11-22 03:57:08 +0000226template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000227 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000228 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000229 memcpy(Buf, &Reginfo, sizeof(Reginfo));
230}
231
232template <class ELFT>
233MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
234 // Section should be alive for O32 and N32 ABIs only.
235 if (ELFT::Is64Bits)
236 return nullptr;
237
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000238 std::vector<InputSectionBase *> Sections;
239 for (InputSectionBase *Sec : InputSections)
240 if (Sec->Type == SHT_MIPS_REGINFO)
241 Sections.push_back(Sec);
Rui Ueyamab71cae92016-11-22 03:57:08 +0000242
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000243 if (Sections.empty())
244 return nullptr;
245
246 Elf_Mips_RegInfo Reginfo = {};
247 for (InputSectionBase *Sec : Sections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000248 Sec->Live = false;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000249
250 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama25f30882017-10-27 03:25:04 +0000251 error(toString(Sec->File) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000252 return nullptr;
253 }
254 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
255 if (Config->Relocatable && R->ri_gp_value)
Rui Ueyama25f30882017-10-27 03:25:04 +0000256 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000257
258 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000259 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000260 };
261
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000262 return make<MipsReginfoSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000263}
264
Rui Ueyama3255a522017-02-27 02:32:49 +0000265InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000266 // StringSaver guarantees that the returned string ends with '\0'.
267 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000268 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
269
270 auto *Sec =
271 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
272 Sec->Live = true;
273 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000274}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000275
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000276Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
277 uint64_t Size, InputSectionBase *Section) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000278 auto *S =
279 make<Defined>(Name, STB_LOCAL, STV_DEFAULT, Type, Value, Size, Section);
George Rimar69b17c32017-05-16 10:04:42 +0000280 if (InX::SymTab)
281 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000282 return S;
283}
284
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000285static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000286 switch (Config->BuildId) {
287 case BuildIdKind::Fast:
288 return 8;
289 case BuildIdKind::Md5:
290 case BuildIdKind::Uuid:
291 return 16;
292 case BuildIdKind::Sha1:
293 return 20;
294 case BuildIdKind::Hexstring:
295 return Config->BuildIdVector.size();
296 default:
297 llvm_unreachable("unknown BuildIdKind");
298 }
299}
300
George Rimar6c2949d2017-03-20 16:40:21 +0000301BuildIdSection::BuildIdSection()
Jake Ehrlich1128dc52017-10-30 22:08:11 +0000302 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000303 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000304
George Rimar6c2949d2017-03-20 16:40:21 +0000305void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyama79048e42017-10-27 03:59:34 +0000306 write32(Buf, 4); // Name size
307 write32(Buf + 4, HashSize); // Content size
308 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000309 memcpy(Buf + 12, "GNU", 4); // Name string
310 HashBuf = Buf + 16;
311}
312
Rui Ueyama35e00752016-11-10 00:12:28 +0000313// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000314static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
315 size_t ChunkSize) {
316 std::vector<ArrayRef<uint8_t>> Ret;
317 while (Arr.size() > ChunkSize) {
318 Ret.push_back(Arr.take_front(ChunkSize));
319 Arr = Arr.drop_front(ChunkSize);
320 }
321 if (!Arr.empty())
322 Ret.push_back(Arr);
323 return Ret;
324}
325
Rui Ueyama35e00752016-11-10 00:12:28 +0000326// Computes a hash value of Data using a given hash function.
327// In order to utilize multiple cores, we first split data into 1MB
328// chunks, compute a hash for each chunk, and then compute a hash value
329// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000330void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000331 llvm::ArrayRef<uint8_t> Data,
332 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000333 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000334 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000335
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000336 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000337 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000338 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
339 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000340
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000341 // Write to the final output buffer.
342 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000343}
344
Rui Ueyama732f4e22017-10-04 00:21:17 +0000345BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
346 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Peter Collingbourne6c55a702017-11-06 04:33:58 +0000347 this->Bss = true;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000348 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000349 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000350 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000351}
Peter Smithebfe9942017-02-09 10:27:57 +0000352
George Rimar6c2949d2017-03-20 16:40:21 +0000353void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000354 switch (Config->BuildId) {
355 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000356 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000357 write64le(Dest, xxHash64(toStringRef(Arr)));
358 });
359 break;
360 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000361 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000362 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000363 });
364 break;
365 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000366 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000367 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000368 });
369 break;
370 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000371 if (auto EC = getRandomBytes(HashBuf, HashSize))
372 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000373 break;
374 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000375 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000376 break;
377 default:
378 llvm_unreachable("unknown BuildIdKind");
379 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000380}
381
Rui Ueyama572247f2017-10-27 03:13:39 +0000382EhFrameSection::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000383 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000384
385// Search for an existing CIE record or create a new one.
386// CIE records from input object files are uniquified by their contents
387// and where their relocations point to.
Rui Ueyama572247f2017-10-27 03:13:39 +0000388template <class ELFT, class RelTy>
389CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000390 auto *Sec = cast<EhInputSection>(Cie.Sec);
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000391 if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000392 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
393
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000394 Symbol *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000395 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000396 if (FirstRelI != (unsigned)-1)
397 Personality =
398 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
399
400 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000401 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000402
403 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000404 if (!Rec) {
405 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000406 Rec->Cie = &Cie;
407 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000408 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000409 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000410}
411
412// There is one FDE per function. Returns true if a given FDE
413// points to a live function.
Rui Ueyama572247f2017-10-27 03:13:39 +0000414template <class ELFT, class RelTy>
415bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000416 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000417 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000418
419 // An FDE should point to some function because FDEs are to describe
420 // functions. That's however not always the case due to an issue of
421 // ld.gold with -r. ld.gold may discard only functions and leave their
422 // corresponding FDEs, which results in creating bad .eh_frame sections.
423 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000424 if (FirstRelI == (unsigned)-1)
425 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000426
Rafael Espindola66b4e212017-02-23 22:06:28 +0000427 const RelTy &Rel = Rels[FirstRelI];
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000428 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000429
430 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +0000431 if (auto *D = dyn_cast<Defined>(&B))
George Rimard605f412017-10-26 09:13:19 +0000432 if (auto *Sec = cast_or_null<InputSectionBase>(D->Section))
433 return Sec->Live && (Sec == Sec->Repl);
Rui Ueyama27a357c2017-09-18 19:15:54 +0000434 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000435}
436
437// .eh_frame is a sequence of CIE or FDE records. In general, there
438// is one CIE record per input object file which is followed by
439// a list of FDEs. This function searches an existing CIE or create a new
440// one and associates FDEs to the CIE.
Rui Ueyama572247f2017-10-27 03:13:39 +0000441template <class ELFT, class RelTy>
442void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000443 DenseMap<size_t, CieRecord *> OffsetToCie;
444 for (EhSectionPiece &Piece : Sec->Pieces) {
445 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000446 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000447 return;
448
449 size_t Offset = Piece.InputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000450 uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000451 if (ID == 0) {
Rui Ueyama572247f2017-10-27 03:13:39 +0000452 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000453 continue;
454 }
455
456 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000457 CieRecord *Rec = OffsetToCie[CieOffset];
458 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000459 fatal(toString(Sec) + ": invalid CIE reference");
460
Rui Ueyama572247f2017-10-27 03:13:39 +0000461 if (!isFdeLive<ELFT>(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000462 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000463 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000464 NumFdes++;
465 }
466}
467
Rui Ueyama572247f2017-10-27 03:13:39 +0000468template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000469 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000470 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000471
472 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000473 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000474
Petr Hosek7b793212017-03-10 20:00:42 +0000475 for (auto *DS : Sec->DependentSections)
476 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000477
478 // .eh_frame is a sequence of CIE or FDE records. This function
479 // splits it into pieces so that we can call
480 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000481 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000482 if (Sec->Pieces.empty())
483 return;
484
Rui Ueyamabfa84322017-10-26 22:30:25 +0000485 if (Sec->AreRelocsRela)
Rui Ueyama572247f2017-10-27 03:13:39 +0000486 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
Rui Ueyamafaa38022017-09-19 20:28:03 +0000487 else
Rui Ueyama572247f2017-10-27 03:13:39 +0000488 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000489}
490
Rafael Espindola66b4e212017-02-23 22:06:28 +0000491static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
492 memcpy(Buf, D.data(), D.size());
493
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000494 size_t Aligned = alignTo(D.size(), Config->Wordsize);
Andrew Ng6dee7362017-09-07 08:43:56 +0000495
496 // Zero-clear trailing padding if it exists.
497 memset(Buf + D.size(), 0, Aligned - D.size());
498
Rafael Espindola66b4e212017-02-23 22:06:28 +0000499 // Fix the size field. -4 since size does not include the size field itself.
Rui Ueyama79048e42017-10-27 03:59:34 +0000500 write32(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000501}
502
Rui Ueyama572247f2017-10-27 03:13:39 +0000503void EhFrameSection::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000504 if (this->Size)
505 return; // Already finalized.
506
507 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000508 for (CieRecord *Rec : CieRecords) {
509 Rec->Cie->OutputOff = Off;
510 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000511
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000512 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000513 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000514 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000515 }
516 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000517
518 // The LSB standard does not allow a .eh_frame section with zero
519 // Call Frame Information records. Therefore add a CIE record length
520 // 0 as a terminator if this .eh_frame section is empty.
521 if (Off == 0)
522 Off = 4;
523
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000524 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000525}
526
Rui Ueyamac0552252017-10-27 03:13:24 +0000527// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
528// to get an FDE from an address to which FDE is applied. This function
529// returns a list of such pairs.
Rui Ueyama572247f2017-10-27 03:13:39 +0000530std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
Rui Ueyamac0552252017-10-27 03:13:24 +0000531 uint8_t *Buf = getParent()->Loc + OutSecOff;
532 std::vector<FdeData> Ret;
533
534 for (CieRecord *Rec : CieRecords) {
Rui Ueyama86297522017-10-27 03:14:09 +0000535 uint8_t Enc = getFdeEncoding(Rec->Cie);
Rui Ueyamac0552252017-10-27 03:13:24 +0000536 for (EhSectionPiece *Fde : Rec->Fdes) {
537 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
538 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
539 Ret.push_back({Pc, FdeVA});
540 }
541 }
542 return Ret;
543}
544
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000545static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000546 switch (Size) {
547 case DW_EH_PE_udata2:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000548 return read16(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000549 case DW_EH_PE_udata4:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000550 return read32(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000551 case DW_EH_PE_udata8:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000552 return read64(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000553 case DW_EH_PE_absptr:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000554 return readUint(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000555 }
556 fatal("unknown FDE size encoding");
557}
558
559// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
560// We need it to create .eh_frame_hdr section.
Rui Ueyama572247f2017-10-27 03:13:39 +0000561uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
562 uint8_t Enc) const {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000563 // The starting address to which this FDE applies is
564 // stored at FDE + 8 byte.
565 size_t Off = FdeOff + 8;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000566 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000567 if ((Enc & 0x70) == DW_EH_PE_absptr)
568 return Addr;
569 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000570 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000571 fatal("unknown FDE size relative encoding");
572}
573
Rui Ueyama572247f2017-10-27 03:13:39 +0000574void EhFrameSection::writeTo(uint8_t *Buf) {
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000575 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000576 for (CieRecord *Rec : CieRecords) {
577 size_t CieOffset = Rec->Cie->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000578 writeCieFde(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000579
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000580 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000581 size_t Off = Fde->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000582 writeCieFde(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000583
584 // FDE's second word should have the offset to an associated CIE.
585 // Write it.
Rui Ueyama79048e42017-10-27 03:59:34 +0000586 write32(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000587 }
588 }
589
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000590 // Apply relocations. .eh_frame section contents are not contiguous
591 // in the output buffer, but relocateAlloc() still works because
592 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000593 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000594 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000595}
596
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000597GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000598 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
599 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000600
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000601void GotSection::addEntry(Symbol &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000602 Sym.GotIndex = NumEntries;
603 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000604}
605
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000606bool GotSection::addDynTlsEntry(Symbol &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000607 if (Sym.GlobalDynIndex != -1U)
608 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000609 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000610 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000611 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000612 return true;
613}
614
615// Reserves TLS entries for a TLS module ID and a TLS block offset.
616// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000617bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000618 if (TlsIndexOff != uint32_t(-1))
619 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000620 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000621 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000622 return true;
623}
624
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000625uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000626 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000627}
628
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000629uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000630 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000631}
632
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000633void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000634
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000635bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000636 // We need to emit a GOT even if it's empty if there's a relocation that is
637 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
638 // (i.e. _GLOBAL_OFFSET_TABLE_).
639 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
George Rimar11992c862016-11-25 08:05:41 +0000640}
641
Igor Kudrin202a9f62017-07-14 08:10:45 +0000642void GotSection::writeTo(uint8_t *Buf) {
643 // Buf points to the start of this section's buffer,
644 // whereas InputSectionBase::relocateAlloc() expects its argument
645 // to point to the start of the output section.
646 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
647}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000648
George Rimar14534eb2017-03-20 16:44:28 +0000649MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000650 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
651 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000652
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000653void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000654 // For "true" local symbols which can be referenced from the same module
655 // only compiler creates two instructions for address loading:
656 //
657 // lw $8, 0($gp) # R_MIPS_GOT16
658 // addi $8, $8, 0 # R_MIPS_LO16
659 //
660 // The first instruction loads high 16 bits of the symbol address while
661 // the second adds an offset. That allows to reduce number of required
662 // GOT entries because only one global offset table entry is necessary
663 // for every 64 KBytes of local data. So for local symbols we need to
664 // allocate number of GOT entries to hold all required "page" addresses.
665 //
666 // All global symbols (hidden and regular) considered by compiler uniformly.
667 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
668 // to load address of the symbol. So for each such symbol we need to
669 // allocate dedicated GOT entry to store its address.
670 //
671 // If a symbol is preemptible we need help of dynamic linker to get its
672 // final address. The corresponding GOT entries are allocated in the
673 // "global" part of GOT. Entries for non preemptible global symbol allocated
674 // in the "local" part of GOT.
675 //
676 // See "Global Offset Table" in Chapter 5:
677 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
678 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
679 // At this point we do not know final symbol value so to reduce number
680 // of allocated GOT entries do the following trick. Save all output
681 // sections referenced by GOT relocations. Then later in the `finalize`
682 // method calculate number of "pages" required to cover all saved output
683 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000684 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000685 return;
686 }
687 if (Sym.isTls()) {
688 // GOT entries created for MIPS TLS relocations behave like
689 // almost GOT entries from other ABIs. They go to the end
690 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000691 Sym.GotIndex = TlsEntries.size();
692 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000693 return;
694 }
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000695 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000696 if (S.isInGot() && !A)
697 return;
698 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000699 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000700 return;
701 Items.emplace_back(&S, A);
702 if (!A)
703 S.GotIndex = NewIndex;
704 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000705 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000706 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000707 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000708 Sym.IsInGlobalMipsGot = true;
709 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000710 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000711 Sym.Is32BitMipsGot = true;
712 } else {
713 // Hold local GOT entries accessed via a 16-bit index separately.
714 // That allows to write them in the beginning of the GOT and keep
715 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000716 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000717 }
718}
719
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000720bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000721 if (Sym.GlobalDynIndex != -1U)
722 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000723 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000724 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000725 TlsEntries.push_back(nullptr);
726 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000727 return true;
728}
729
730// Reserves TLS entries for a TLS module ID and a TLS block offset.
731// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000732bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000733 if (TlsIndexOff != uint32_t(-1))
734 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000735 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000736 TlsEntries.push_back(nullptr);
737 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000738 return true;
739}
740
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000741static uint64_t getMipsPageAddr(uint64_t Addr) {
742 return (Addr + 0x8000) & ~0xffff;
743}
744
745static uint64_t getMipsPageCount(uint64_t Size) {
746 return (Size + 0xfffe) / 0xffff + 1;
747}
748
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000749uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
George Rimar14534eb2017-03-20 16:44:28 +0000750 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000751 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000752 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
753 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
754 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000755 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000756 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000757}
758
Rui Ueyama48882242017-11-04 00:31:04 +0000759uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
760 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000761 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000762 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000763 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000764 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000765 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000766 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000767 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000768 Index += LocalEntries.size();
769 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000770 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000771 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000772 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000773 auto It = EntryIndexMap.find({&B, Addend});
774 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000775 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000776 }
George Rimar14534eb2017-03-20 16:44:28 +0000777 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000778}
779
George Rimar14534eb2017-03-20 16:44:28 +0000780uint64_t MipsGotSection::getTlsOffset() const {
781 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000782}
783
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000784uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
George Rimar14534eb2017-03-20 16:44:28 +0000785 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000786}
787
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000788const Symbol *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000789 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790}
791
George Rimar14534eb2017-03-20 16:44:28 +0000792unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
794 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000795}
796
George Rimar67c60722017-07-18 11:55:35 +0000797void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000798
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000799bool MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000800 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000801 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000802 // For each output section referenced by GOT page relocations calculate
803 // and save into PageIndexMap an upper bound of MIPS GOT entries required
804 // to store page addresses of local symbols. We assume the worst case -
805 // each 64kb page of the output section has at least one GOT relocation
806 // against it. And take in account the case when the section intersects
807 // page boundaries.
808 P.second = PageEntriesNum;
809 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000810 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000811 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000812 Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000813 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000814}
815
George Rimar14534eb2017-03-20 16:44:28 +0000816bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000817 // We add the .got section to the result for dynamic MIPS target because
818 // its address and properties are mentioned in the .dynamic section.
819 return Config->Relocatable;
820}
821
George Rimar67c60722017-07-18 11:55:35 +0000822uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000823
George Rimar14534eb2017-03-20 16:44:28 +0000824void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000825 // Set the MSB of the second GOT slot. This is not required by any
826 // MIPS ABI documentation, though.
827 //
828 // There is a comment in glibc saying that "The MSB of got[1] of a
829 // gnu object is set to identify gnu objects," and in GNU gold it
830 // says "the second entry will be used by some runtime loaders".
831 // But how this field is being used is unclear.
832 //
833 // We are not really willing to mimic other linkers behaviors
834 // without understanding why they do that, but because all files
835 // generated by GNU tools have this special GOT value, and because
836 // we've been doing this for years, it is probably a safe bet to
837 // keep doing this for now. We really need to revisit this to see
838 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000839 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
840 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000841 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000842 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000843 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000844 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000845 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000846 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
847 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000848 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000849 }
George Rimar14534eb2017-03-20 16:44:28 +0000850 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000851 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000852 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000853 Buf += Config->Wordsize;
Rui Ueyama48882242017-11-04 00:31:04 +0000854 const Symbol *Sym = SA.first;
855 uint64_t VA = Sym->getVA(SA.second);
Simon Atanasyan5a4e2132017-11-08 23:34:34 +0000856 if (Sym->StOther & STO_MIPS_MICROMIPS)
857 VA |= 1;
George Rimar14534eb2017-03-20 16:44:28 +0000858 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000859 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000860 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
861 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
862 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000863 // Initialize TLS-related GOT entries. If the entry has a corresponding
864 // dynamic relocations, leave it initialized by zero. Write down adjusted
865 // TLS symbol's values otherwise. To calculate the adjustments use offsets
866 // for thread-local storage.
867 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000868 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000869 writeUint(Buf + TlsIndexOff, 1);
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000870 for (const Symbol *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000871 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000872 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000873 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000874 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000875 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
876 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000877 }
878 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000879 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
880 writeUint(Entry, 1);
881 Entry += Config->Wordsize;
882 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000883 }
884 }
885}
886
George Rimar10f74fc2017-03-15 09:12:56 +0000887GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000888 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
889 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000890
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000891void GotPltSection::addEntry(Symbol &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000892 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
893 Entries.push_back(&Sym);
894}
895
George Rimar10f74fc2017-03-15 09:12:56 +0000896size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000897 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
898 Target->GotPltEntrySize;
899}
900
George Rimar10f74fc2017-03-15 09:12:56 +0000901void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000902 Target->writeGotPltHeader(Buf);
903 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000904 for (const Symbol *B : Entries) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000905 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000906 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000907 }
908}
909
Peter Smithbaffdb82016-12-08 12:58:55 +0000910// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
911// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000912IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000913 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
914 Target->GotPltEntrySize,
915 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000916
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000917void IgotPltSection::addEntry(Symbol &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000918 Sym.IsInIgot = true;
919 Sym.GotPltIndex = Entries.size();
920 Entries.push_back(&Sym);
921}
922
George Rimar10f74fc2017-03-15 09:12:56 +0000923size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000924 return Entries.size() * Target->GotPltEntrySize;
925}
926
George Rimar10f74fc2017-03-15 09:12:56 +0000927void IgotPltSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000928 for (const Symbol *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000929 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000930 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000931 }
932}
933
George Rimar49648002017-03-15 09:32:36 +0000934StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
935 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000936 Dynamic(Dynamic) {
937 // ELF string tables start with a NUL byte.
938 addString("");
939}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000940
941// Adds a string to the string table. If HashIt is true we hash and check for
942// duplicates. It is optional because the name of global symbols are already
943// uniqued and hashing them again has a big cost for a small value: uniquing
944// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000945unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000946 if (HashIt) {
947 auto R = StringMap.insert(std::make_pair(S, this->Size));
948 if (!R.second)
949 return R.first->second;
950 }
951 unsigned Ret = this->Size;
952 this->Size = this->Size + S.size() + 1;
953 Strings.push_back(S);
954 return Ret;
955}
956
George Rimar49648002017-03-15 09:32:36 +0000957void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000958 for (StringRef S : Strings) {
959 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000960 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000961 Buf += S.size() + 1;
962 }
963}
964
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000965// Returns the number of version definition entries. Because the first entry
966// is for the version definition itself, it is the number of versioned symbols
967// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000968static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
969
970template <class ELFT>
971DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000972 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +0000973 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000974 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +0000975
Petr Hosekffa786f2017-05-26 19:12:38 +0000976 // .dynamic section is not writable on MIPS and on Fuchsia OS
977 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000978 // See "Special Section" in Chapter 4 in the following document:
979 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +0000980 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +0000981 this->Flags = SHF_ALLOC;
982
983 addEntries();
984}
985
Rui Ueyama15475e92017-11-24 02:15:51 +0000986template <class ELFT>
987void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
988 Entries.push_back({Tag, Fn});
989}
990
991template <class ELFT>
992void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
993 Entries.push_back({Tag, [=] { return Val; }});
994}
995
996template <class ELFT>
997void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
998 Entries.push_back(
999 {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1000}
1001
1002template <class ELFT>
1003void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1004 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1005}
1006
1007template <class ELFT>
1008void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1009 Entries.push_back({Tag, [=] { return Sec->Size; }});
1010}
1011
1012template <class ELFT>
1013void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1014 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1015}
1016
Eugene Leviant6380ce22016-11-15 12:26:55 +00001017// There are some dynamic entries that don't depend on other sections.
1018// Such entries can be set early.
1019template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1020 // Add strings to .dynstr early so that .dynstr's size will be
1021 // fixed early.
George Rimarf525c922017-07-17 09:43:18 +00001022 for (StringRef S : Config->FilterList)
Rui Ueyama15475e92017-11-24 02:15:51 +00001023 addInt(DT_FILTER, InX::DynStrTab->addString(S));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001024 for (StringRef S : Config->AuxiliaryList)
Rui Ueyama15475e92017-11-24 02:15:51 +00001025 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
1026
Rui Ueyamabd278492017-04-29 23:06:43 +00001027 if (!Config->Rpath.empty())
Rui Ueyama15475e92017-11-24 02:15:51 +00001028 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1029 InX::DynStrTab->addString(Config->Rpath));
1030
George Rimar696a7f92017-09-19 09:20:54 +00001031 for (InputFile *File : SharedFiles) {
1032 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
Rafael Espindolade563432017-11-22 17:50:42 +00001033 if (F->IsNeeded)
Rui Ueyama15475e92017-11-24 02:15:51 +00001034 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
George Rimar696a7f92017-09-19 09:20:54 +00001035 }
Eugene Leviant6380ce22016-11-15 12:26:55 +00001036 if (!Config->SoName.empty())
Rui Ueyama15475e92017-11-24 02:15:51 +00001037 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001038
1039 // Set DT_FLAGS and DT_FLAGS_1.
1040 uint32_t DtFlags = 0;
1041 uint32_t DtFlags1 = 0;
1042 if (Config->Bsymbolic)
1043 DtFlags |= DF_SYMBOLIC;
1044 if (Config->ZNodelete)
1045 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001046 if (Config->ZNodlopen)
1047 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001048 if (Config->ZNow) {
1049 DtFlags |= DF_BIND_NOW;
1050 DtFlags1 |= DF_1_NOW;
1051 }
1052 if (Config->ZOrigin) {
1053 DtFlags |= DF_ORIGIN;
1054 DtFlags1 |= DF_1_ORIGIN;
1055 }
1056
1057 if (DtFlags)
Rui Ueyama15475e92017-11-24 02:15:51 +00001058 addInt(DT_FLAGS, DtFlags);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001059 if (DtFlags1)
Rui Ueyama15475e92017-11-24 02:15:51 +00001060 addInt(DT_FLAGS_1, DtFlags1);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001061
Petr Hosekffa786f2017-05-26 19:12:38 +00001062 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1063 // need it for each process, so we don't write it for DSOs. The loader writes
1064 // the pointer into this entry.
1065 //
1066 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1067 // systems (currently only Fuchsia OS) provide other means to give the
1068 // debugger this information. Such systems may choose make .dynamic read-only.
1069 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1070 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
Rui Ueyama15475e92017-11-24 02:15:51 +00001071 addInt(DT_DEBUG, 0);
George Rimarb4081bb2017-05-12 08:04:58 +00001072}
1073
1074// Add remaining entries to complete .dynamic contents.
1075template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1076 if (this->Size)
1077 return; // Already finalized.
1078
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001079 this->Link = InX::DynStrTab->getParent()->SectionIndex;
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001080 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001081 addInSec(In<ELFT>::RelaDyn->DynamicTag, In<ELFT>::RelaDyn);
1082 addSize(In<ELFT>::RelaDyn->SizeDynamicTag, In<ELFT>::RelaDyn->getParent());
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001083
1084 bool IsRela = Config->IsRela;
Rui Ueyama15475e92017-11-24 02:15:51 +00001085 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1086 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001087
1088 // MIPS dynamic loader does not support RELCOUNT tag.
1089 // The problem is in the tight relation between dynamic
1090 // relocations and GOT. So do not emit this tag on MIPS.
1091 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001092 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001093 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama15475e92017-11-24 02:15:51 +00001094 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001095 }
1096 }
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001097 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001098 addInSec(DT_JMPREL, In<ELFT>::RelaPlt);
1099 addSize(DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent());
Rui Ueyama0cc14832017-06-28 17:05:39 +00001100 switch (Config->EMachine) {
1101 case EM_MIPS:
Rui Ueyama15475e92017-11-24 02:15:51 +00001102 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001103 break;
1104 case EM_SPARCV9:
Rui Ueyama15475e92017-11-24 02:15:51 +00001105 addInSec(DT_PLTGOT, InX::Plt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001106 break;
1107 default:
Rui Ueyama15475e92017-11-24 02:15:51 +00001108 addInSec(DT_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001109 break;
1110 }
Rui Ueyama15475e92017-11-24 02:15:51 +00001111 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001112 }
1113
Rui Ueyama15475e92017-11-24 02:15:51 +00001114 addInSec(DT_SYMTAB, InX::DynSymTab);
1115 addInt(DT_SYMENT, sizeof(Elf_Sym));
1116 addInSec(DT_STRTAB, InX::DynStrTab);
1117 addInt(DT_STRSZ, InX::DynStrTab->getSize());
George Rimar0a7412f2017-03-09 08:48:34 +00001118 if (!Config->ZText)
Rui Ueyama15475e92017-11-24 02:15:51 +00001119 addInt(DT_TEXTREL, 0);
George Rimar69b17c32017-05-16 10:04:42 +00001120 if (InX::GnuHashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001121 addInSec(DT_GNU_HASH, InX::GnuHashTab);
George Rimaraaf54712017-09-27 09:14:59 +00001122 if (InX::HashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001123 addInSec(DT_HASH, InX::HashTab);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001124
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001125 if (Out::PreinitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001126 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1127 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001128 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001129 if (Out::InitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001130 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1131 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001132 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001133 if (Out::FiniArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001134 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1135 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001136 }
1137
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001138 if (Symbol *B = Symtab->find(Config->Init))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001139 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001140 addSym(DT_INIT, B);
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001141 if (Symbol *B = Symtab->find(Config->Fini))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001142 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001143 addSym(DT_FINI, B);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001144
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001145 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1146 if (HasVerNeed || In<ELFT>::VerDef)
Rui Ueyama15475e92017-11-24 02:15:51 +00001147 addInSec(DT_VERSYM, In<ELFT>::VerSym);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001148 if (In<ELFT>::VerDef) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001149 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1150 addInt(DT_VERDEFNUM, getVerDefNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001151 }
1152 if (HasVerNeed) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001153 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1154 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001155 }
1156
1157 if (Config->EMachine == EM_MIPS) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001158 addInt(DT_MIPS_RLD_VERSION, 1);
1159 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1160 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1161 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
James Hendersonf70c5be2017-11-22 12:04:21 +00001162
Rui Ueyama15475e92017-11-24 02:15:51 +00001163 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
James Hendersonf70c5be2017-11-22 12:04:21 +00001164
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001165 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama15475e92017-11-24 02:15:51 +00001166 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001167 else
Rui Ueyama15475e92017-11-24 02:15:51 +00001168 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1169 addInSec(DT_PLTGOT, InX::MipsGot);
Rafael Espindola895aea62017-05-11 22:02:41 +00001170 if (InX::MipsRldMap)
Rui Ueyama15475e92017-11-24 02:15:51 +00001171 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001172 }
1173
Rui Ueyama15475e92017-11-24 02:15:51 +00001174 addInt(DT_NULL, 0);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001175
George Rimar8f3a6c82017-10-06 10:06:13 +00001176 getParent()->Link = this->Link;
1177 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001178}
1179
1180template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1181 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1182
Rui Ueyama15475e92017-11-24 02:15:51 +00001183 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1184 P->d_tag = KV.first;
1185 P->d_un.d_val = KV.second();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001186 ++P;
1187 }
1188}
1189
George Rimar97def8c2017-03-17 12:07:44 +00001190uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001191 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001192}
1193
George Rimar97def8c2017-03-17 12:07:44 +00001194int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001195 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001196 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001197 return Addend;
1198}
1199
George Rimar97def8c2017-03-17 12:07:44 +00001200uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001201 if (Sym && !UseSymVA)
1202 return Sym->DynsymIndex;
1203 return 0;
1204}
1205
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001206RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1207 int32_t DynamicTag,
1208 int32_t SizeDynamicTag)
1209 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1210 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001211
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001212void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001213 if (Reloc.Type == Target->RelativeRel)
1214 ++NumRelativeRelocs;
1215 Relocs.push_back(Reloc);
1216}
1217
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001218void RelocationBaseSection::finalizeContents() {
1219 // If all relocations are R_*_RELATIVE they don't refer to any
1220 // dynamic symbol and we don't need a dynamic symbol table. If that
1221 // is the case, just use 0 as the link.
1222 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
1223
1224 // Set required output section properties.
1225 getParent()->Link = this->Link;
1226}
1227
1228template <class ELFT>
1229static void encodeDynamicReloc(typename ELFT::Rela *P,
1230 const DynamicReloc &Rel) {
1231 if (Config->IsRela)
1232 P->r_addend = Rel.getAddend();
1233 P->r_offset = Rel.getOffset();
1234 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1235 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1236 // entries. These entries are placed after the global and local sections of
1237 // the GOT. At the point when we create these relocations, the size of the
1238 // global and local sections is unknown, so the offset that we store in the
1239 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1240 // the GOT, rather than being relative to the start of the GOT. This line of
1241 // code adds the size of the global and local sections to the virtual
1242 // address computed by getOffset() in order to adjust it into the TLS
1243 // section.
1244 P->r_offset += InX::MipsGot->getTlsOffset();
1245 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1246}
1247
1248template <class ELFT>
1249RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1250 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1251 Config->IsRela ? DT_RELA : DT_REL,
1252 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1253 Sort(Sort) {
1254 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1255}
1256
Eugene Levianta96d9022016-11-16 10:02:27 +00001257template <class ELFT, class RelTy>
1258static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001259 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1260 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001261 if (AIsRel != BIsRel)
1262 return AIsRel;
1263
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001264 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001265}
1266
1267template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1268 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001269 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001270 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001271 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001272 }
1273
1274 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001275 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001276 std::stable_sort((Elf_Rela *)BufBegin,
1277 (Elf_Rela *)BufBegin + Relocs.size(),
1278 compRelocations<ELFT, Elf_Rela>);
1279 else
1280 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1281 compRelocations<ELFT, Elf_Rel>);
1282 }
1283}
1284
1285template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1286 return this->Entsize * Relocs.size();
1287}
1288
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001289template <class ELFT>
1290AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1291 StringRef Name)
1292 : RelocationBaseSection(
1293 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1294 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1295 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1296 this->Entsize = 1;
1297}
Eugene Levianta96d9022016-11-16 10:02:27 +00001298
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001299template <class ELFT>
1300bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1301 // This function computes the contents of an Android-format packed relocation
1302 // section.
1303 //
1304 // This format compresses relocations by using relocation groups to factor out
1305 // fields that are common between relocations and storing deltas from previous
1306 // relocations in SLEB128 format (which has a short representation for small
1307 // numbers). A good example of a relocation type with common fields is
1308 // R_*_RELATIVE, which is normally used to represent function pointers in
1309 // vtables. In the REL format, each relative relocation has the same r_info
1310 // field, and is only different from other relative relocations in terms of
1311 // the r_offset field. By sorting relocations by offset, grouping them by
1312 // r_info and representing each relocation with only the delta from the
1313 // previous offset, each 8-byte relocation can be compressed to as little as 1
1314 // byte (or less with run-length encoding). This relocation packer was able to
1315 // reduce the size of the relocation section in an Android Chromium DSO from
1316 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1317 //
1318 // A relocation section consists of a header containing the literal bytes
1319 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1320 // elements are the total number of relocations in the section and an initial
1321 // r_offset value. The remaining elements define a sequence of relocation
1322 // groups. Each relocation group starts with a header consisting of the
1323 // following elements:
1324 //
1325 // - the number of relocations in the relocation group
1326 // - flags for the relocation group
1327 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1328 // for each relocation in the group.
1329 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1330 // field for each relocation in the group.
1331 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1332 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1333 // each relocation in the group.
1334 //
1335 // Following the relocation group header are descriptions of each of the
1336 // relocations in the group. They consist of the following elements:
1337 //
1338 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1339 // delta for this relocation.
1340 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1341 // field for this relocation.
1342 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1343 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1344 // this relocation.
1345
1346 size_t OldSize = RelocData.size();
1347
1348 RelocData = {'A', 'P', 'S', '2'};
1349 raw_svector_ostream OS(RelocData);
1350
1351 // The format header includes the number of relocations and the initial
1352 // offset (we set this to zero because the first relocation group will
1353 // perform the initial adjustment).
1354 encodeSLEB128(Relocs.size(), OS);
1355 encodeSLEB128(0, OS);
1356
1357 std::vector<Elf_Rela> Relatives, NonRelatives;
1358
1359 for (const DynamicReloc &Rel : Relocs) {
1360 Elf_Rela R;
1361 encodeDynamicReloc<ELFT>(&R, Rel);
1362
1363 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1364 Relatives.push_back(R);
1365 else
1366 NonRelatives.push_back(R);
1367 }
1368
1369 std::sort(Relatives.begin(), Relatives.end(),
1370 [](const Elf_Rel &A, const Elf_Rel &B) {
1371 return A.r_offset < B.r_offset;
1372 });
1373
1374 // Try to find groups of relative relocations which are spaced one word
1375 // apart from one another. These generally correspond to vtable entries. The
1376 // format allows these groups to be encoded using a sort of run-length
1377 // encoding, but each group will cost 7 bytes in addition to the offset from
1378 // the previous group, so it is only profitable to do this for groups of
1379 // size 8 or larger.
1380 std::vector<Elf_Rela> UngroupedRelatives;
1381 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1382 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1383 std::vector<Elf_Rela> Group;
1384 do {
1385 Group.push_back(*I++);
1386 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1387
1388 if (Group.size() < 8)
1389 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1390 Group.end());
1391 else
1392 RelativeGroups.emplace_back(std::move(Group));
1393 }
1394
1395 unsigned HasAddendIfRela =
1396 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1397
1398 uint64_t Offset = 0;
1399 uint64_t Addend = 0;
1400
1401 // Emit the run-length encoding for the groups of adjacent relative
1402 // relocations. Each group is represented using two groups in the packed
1403 // format. The first is used to set the current offset to the start of the
1404 // group (and also encodes the first relocation), and the second encodes the
1405 // remaining relocations.
1406 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1407 // The first relocation in the group.
1408 encodeSLEB128(1, OS);
1409 encodeSLEB128(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1410 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela,
1411 OS);
1412 encodeSLEB128(G[0].r_offset - Offset, OS);
1413 encodeSLEB128(Target->RelativeRel, OS);
1414 if (Config->IsRela) {
1415 encodeSLEB128(G[0].r_addend - Addend, OS);
1416 Addend = G[0].r_addend;
1417 }
1418
1419 // The remaining relocations.
1420 encodeSLEB128(G.size() - 1, OS);
1421 encodeSLEB128(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1422 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela,
1423 OS);
1424 encodeSLEB128(Config->Wordsize, OS);
1425 encodeSLEB128(Target->RelativeRel, OS);
1426 if (Config->IsRela) {
1427 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1428 encodeSLEB128(I->r_addend - Addend, OS);
1429 Addend = I->r_addend;
1430 }
1431 }
1432
1433 Offset = G.back().r_offset;
1434 }
1435
1436 // Now the ungrouped relatives.
1437 if (!UngroupedRelatives.empty()) {
1438 encodeSLEB128(UngroupedRelatives.size(), OS);
1439 encodeSLEB128(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela, OS);
1440 encodeSLEB128(Target->RelativeRel, OS);
1441 for (Elf_Rela &R : UngroupedRelatives) {
1442 encodeSLEB128(R.r_offset - Offset, OS);
1443 Offset = R.r_offset;
1444 if (Config->IsRela) {
1445 encodeSLEB128(R.r_addend - Addend, OS);
1446 Addend = R.r_addend;
1447 }
1448 }
1449 }
1450
1451 // Finally the non-relative relocations.
1452 std::sort(NonRelatives.begin(), NonRelatives.end(),
1453 [](const Elf_Rela &A, const Elf_Rela &B) {
1454 return A.r_offset < B.r_offset;
1455 });
1456 if (!NonRelatives.empty()) {
1457 encodeSLEB128(NonRelatives.size(), OS);
1458 encodeSLEB128(HasAddendIfRela, OS);
1459 for (Elf_Rela &R : NonRelatives) {
1460 encodeSLEB128(R.r_offset - Offset, OS);
1461 Offset = R.r_offset;
1462 encodeSLEB128(R.r_info, OS);
1463 if (Config->IsRela) {
1464 encodeSLEB128(R.r_addend - Addend, OS);
1465 Addend = R.r_addend;
1466 }
1467 }
1468 }
1469
1470 // Returns whether the section size changed. We need to keep recomputing both
1471 // section layout and the contents of this section until the size converges
1472 // because changing this section's size can affect section layout, which in
1473 // turn can affect the sizes of the LEB-encoded integers stored in this
1474 // section.
1475 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001476}
1477
George Rimarf45f6812017-05-16 08:53:30 +00001478SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001479 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001480 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001481 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001482 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001483 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001484
1485// Orders symbols according to their positions in the GOT,
1486// in compliance with MIPS ABI rules.
1487// See "Global Offset Table" in Chapter 5 in the following document
1488// for detailed description:
1489// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001490static bool sortMipsSymbols(const SymbolTableEntry &L,
1491 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001492 // Sort entries related to non-local preemptible symbols by GOT indexes.
1493 // All other entries go to the first part of GOT in arbitrary order.
Zachary Turnera104d552017-11-03 22:33:49 +00001494 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1495 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001496 if (LIsInLocalGot || RIsInLocalGot)
1497 return !RIsInLocalGot;
Zachary Turnera104d552017-11-03 22:33:49 +00001498 return L.Sym->GotIndex < R.Sym->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001499}
1500
George Rimarf45f6812017-05-16 08:53:30 +00001501void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001502 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001503
Rui Ueyama6e967342017-02-28 03:29:12 +00001504 // If it is a .dynsym, there should be no local symbols, but we need
1505 // to do a few things for the dynamic linker.
1506 if (this->Type == SHT_DYNSYM) {
1507 // Section's Info field has the index of the first non-local symbol.
1508 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001509 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001510
George Rimarf45f6812017-05-16 08:53:30 +00001511 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001512 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001513 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001514 } else if (Config->EMachine == EM_MIPS) {
1515 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1516 }
1517
1518 size_t I = 0;
Zachary Turnera104d552017-11-03 22:33:49 +00001519 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001520 return;
Peter Smith55865432017-02-20 11:12:33 +00001521 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001522}
Peter Smith55865432017-02-20 11:12:33 +00001523
George Rimar0d6f30e2017-10-18 13:06:18 +00001524// The ELF spec requires that all local symbols precede global symbols, so we
1525// sort symbol entries in this function. (For .dynsym, we don't do that because
1526// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001527void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001528 if (this->Type == SHT_DYNSYM)
1529 return;
1530 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001531 auto It = std::stable_partition(
1532 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
Zachary Turnera104d552017-11-03 22:33:49 +00001533 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
Rui Ueyama6e967342017-02-28 03:29:12 +00001534 });
1535 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001536 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001537}
1538
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001539void SymbolTableBaseSection::addSymbol(Symbol *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001540 // Adding a local symbol to a .dynsym is a bug.
1541 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001542
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001543 bool HashIt = B->isLocal();
1544 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001545}
1546
Rui Ueyama48882242017-11-04 00:31:04 +00001547size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
George Rimar5d6efd12017-09-27 09:08:53 +00001548 // Initializes symbol lookup tables lazily. This is used only
1549 // for -r or -emit-relocs.
1550 llvm::call_once(OnceFlag, [&] {
1551 SymbolIndexMap.reserve(Symbols.size());
1552 size_t I = 0;
1553 for (const SymbolTableEntry &E : Symbols) {
Zachary Turnera104d552017-11-03 22:33:49 +00001554 if (E.Sym->Type == STT_SECTION)
1555 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001556 else
Zachary Turnera104d552017-11-03 22:33:49 +00001557 SymbolIndexMap[E.Sym] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001558 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001559 });
George Rimar5d6efd12017-09-27 09:08:53 +00001560
1561 // Section symbols are mapped based on their output sections
1562 // to maintain their semantics.
Rui Ueyama48882242017-11-04 00:31:04 +00001563 if (Sym->Type == STT_SECTION)
1564 return SectionIndexMap.lookup(Sym->getOutputSection());
1565 return SymbolIndexMap.lookup(Sym);
George Rimar190bac52017-01-23 14:07:23 +00001566}
1567
George Rimarf45f6812017-05-16 08:53:30 +00001568template <class ELFT>
1569SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1570 : SymbolTableBaseSection(StrTabSec) {
1571 this->Entsize = sizeof(Elf_Sym);
1572}
1573
Rui Ueyama1f032532017-02-28 01:56:36 +00001574// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001575template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001576 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001577 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001578 Buf += sizeof(Elf_Sym);
1579
Eugene Leviant9230db92016-11-17 09:16:34 +00001580 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001581
Rui Ueyama1f032532017-02-28 01:56:36 +00001582 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001583 Symbol *Sym = Ent.Sym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001584
Rui Ueyama1b003182017-02-28 19:22:09 +00001585 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001586 ESym->st_other = 0;
Rui Ueyama48882242017-11-04 00:31:04 +00001587 if (Sym->isLocal()) {
1588 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
Rui Ueyama1f032532017-02-28 01:56:36 +00001589 } else {
Rui Ueyama48882242017-11-04 00:31:04 +00001590 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1591 ESym->setVisibility(Sym->Visibility);
Rui Ueyama1f032532017-02-28 01:56:36 +00001592 }
1593
1594 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001595
Rui Ueyama1b003182017-02-28 19:22:09 +00001596 // Set a section index.
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001597 BssSection *CommonSec = nullptr;
1598 if (!Config->DefineCommon)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001599 if (auto *D = dyn_cast<Defined>(Sym))
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001600 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1601 if (CommonSec)
1602 ESym->st_shndx = SHN_COMMON;
1603 else if (const OutputSection *OutSec = Sym->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001604 ESym->st_shndx = OutSec->SectionIndex;
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001605 else if (isa<Defined>(Sym))
Eugene Leviant9230db92016-11-17 09:16:34 +00001606 ESym->st_shndx = SHN_ABS;
George Rimar2727ce22017-10-06 09:56:24 +00001607 else
1608 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001609
George Rimardbe843d2017-06-28 09:51:33 +00001610 // Copy symbol size if it is a defined symbol. st_size is not significant
1611 // for undefined symbols, so whether copying it or not is up to us if that's
1612 // the case. We'll leave it as zero because by not setting a value, we can
1613 // get the exact same outputs for two sets of input files that differ only
1614 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001615 if (ESym->st_shndx == SHN_UNDEF)
1616 ESym->st_size = 0;
1617 else
Rui Ueyama48882242017-11-04 00:31:04 +00001618 ESym->st_size = Sym->getSize();
George Rimardbe843d2017-06-28 09:51:33 +00001619
Rui Ueyama1b003182017-02-28 19:22:09 +00001620 // st_value is usually an address of a symbol, but that has a
1621 // special meaining for uninstantiated common symbols (this can
1622 // occur if -r is given).
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001623 if (CommonSec)
1624 ESym->st_value = CommonSec->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001625 else
Rui Ueyama48882242017-11-04 00:31:04 +00001626 ESym->st_value = Sym->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001627
Rui Ueyama1f032532017-02-28 01:56:36 +00001628 ++ESym;
1629 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001630
Rui Ueyama1f032532017-02-28 01:56:36 +00001631 // On MIPS we need to mark symbol which has a PLT entry and requires
1632 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1633 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1634 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1635 if (Config->EMachine == EM_MIPS) {
1636 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1637
1638 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001639 Symbol *Sym = Ent.Sym;
1640 if (Sym->isInPlt() && Sym->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001641 ESym->st_other |= STO_MIPS_PLT;
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001642 if (isMicroMips()) {
1643 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1644 // defined microMIPS symbols and shared symbols with PLT record.
1645 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1646 (Sym->isShared() && Sym->NeedsPltAddr)) {
1647 if (StrTabSec.isDynamic())
1648 ESym->st_value |= 1;
1649 ESym->st_other |= STO_MIPS_MICROMIPS;
1650 }
1651 }
Rui Ueyama1f032532017-02-28 01:56:36 +00001652 if (Config->Relocatable)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001653 if (auto *D = dyn_cast<Defined>(Sym))
Rui Ueyama7957b082017-11-07 00:04:22 +00001654 if (isMipsPIC<ELFT>(D))
Rui Ueyama1f032532017-02-28 01:56:36 +00001655 ESym->st_other |= STO_MIPS_PIC;
1656 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001657 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001658 }
1659}
1660
Rui Ueyamae4120632017-02-28 22:05:13 +00001661// .hash and .gnu.hash sections contain on-disk hash tables that map
1662// symbol names to their dynamic symbol table indices. Their purpose
1663// is to help the dynamic linker resolve symbols quickly. If ELF files
1664// don't have them, the dynamic linker has to do linear search on all
1665// dynamic symbols, which makes programs slower. Therefore, a .hash
1666// section is added to a DSO by default. A .gnu.hash is added if you
1667// give the -hash-style=gnu or -hash-style=both option.
1668//
1669// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1670// Each ELF file has a list of DSOs that the ELF file depends on and a
1671// list of dynamic symbols that need to be resolved from any of the
1672// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1673// where m is the number of DSOs and n is the number of dynamic
1674// symbols. For modern large programs, both m and n are large. So
1675// making each step faster by using hash tables substiantially
1676// improves time to load programs.
1677//
1678// (Note that this is not the only way to design the shared library.
1679// For instance, the Windows DLL takes a different approach. On
1680// Windows, each dynamic symbol has a name of DLL from which the symbol
1681// has to be resolved. That makes the cost of symbol resolution O(n).
1682// This disables some hacky techniques you can use on Unix such as
1683// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1684//
1685// Due to historical reasons, we have two different hash tables, .hash
1686// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1687// and better version of .hash. .hash is just an on-disk hash table, but
1688// .gnu.hash has a bloom filter in addition to a hash table to skip
1689// DSOs very quickly. If you are sure that your dynamic linker knows
1690// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1691// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001692GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001693 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1694}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001695
George Rimarf45f6812017-05-16 08:53:30 +00001696void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001697 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001698
1699 // Computes bloom filter size in word size. We want to allocate 8
1700 // bits for each symbol. It must be a power of two.
1701 if (Symbols.empty())
1702 MaskWords = 1;
1703 else
George Rimar5f73bc92017-03-29 15:23:28 +00001704 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001705
George Rimar5f73bc92017-03-29 15:23:28 +00001706 Size = 16; // Header
1707 Size += Config->Wordsize * MaskWords; // Bloom filter
1708 Size += NBuckets * 4; // Hash buckets
1709 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001710}
1711
George Rimarf45f6812017-05-16 08:53:30 +00001712void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001713 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001714 write32(Buf, NBuckets);
1715 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1716 write32(Buf + 8, MaskWords);
1717 write32(Buf + 12, getShift2());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001718 Buf += 16;
1719
Rui Ueyama7986b452017-03-01 18:09:09 +00001720 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001721 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001722 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001723 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001724}
1725
Rui Ueyama7986b452017-03-01 18:09:09 +00001726// This function writes a 2-bit bloom filter. This bloom filter alone
1727// usually filters out 80% or more of all symbol lookups [1].
1728// The dynamic linker uses the hash table only when a symbol is not
1729// filtered out by a bloom filter.
1730//
1731// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1732// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001733void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001734 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001735 for (const Entry &Sym : Symbols) {
1736 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001737 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1738 Val |= uint64_t(1) << (Sym.Hash % C);
1739 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1740 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001741 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001742}
1743
George Rimarf45f6812017-05-16 08:53:30 +00001744void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001745 // Group symbols by hash value.
1746 std::vector<std::vector<Entry>> Syms(NBuckets);
1747 for (const Entry &Ent : Symbols)
1748 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001749
Rui Ueyamae13373b2017-03-01 02:51:42 +00001750 // Write hash buckets. Hash buckets contain indices in the following
1751 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001752 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001753 for (size_t I = 0; I < NBuckets; ++I)
1754 if (!Syms[I].empty())
Rui Ueyama48882242017-11-04 00:31:04 +00001755 write32(Buckets + I, Syms[I][0].Sym->DynsymIndex);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001756
1757 // Write a hash value table. It represents a sequence of chains that
1758 // share the same hash modulo value. The last element of each chain
1759 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001760 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001761 size_t I = 0;
1762 for (std::vector<Entry> &Vec : Syms) {
1763 if (Vec.empty())
1764 continue;
1765 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
Rui Ueyama79048e42017-10-27 03:59:34 +00001766 write32(Values + I++, Ent.Hash & ~1);
1767 write32(Values + I++, Vec.back().Hash | 1);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001768 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001769}
1770
1771static uint32_t hashGnu(StringRef Name) {
1772 uint32_t H = 5381;
1773 for (uint8_t C : Name)
1774 H = (H << 5) + H + C;
1775 return H;
1776}
1777
Rui Ueyamae13373b2017-03-01 02:51:42 +00001778// Returns a number of hash buckets to accomodate given number of elements.
1779// We want to choose a moderate number that is not too small (which
1780// causes too many hash collisions) and not too large (which wastes
1781// disk space.)
1782//
1783// We return a prime number because it (is believed to) achieve good
1784// hash distribution.
1785static size_t getBucketSize(size_t NumSymbols) {
1786 // List of largest prime numbers that are not greater than 2^n + 1.
1787 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1788 251, 127, 61, 31, 13, 7, 3, 1})
1789 if (N <= NumSymbols)
1790 return N;
1791 return 0;
1792}
1793
Eugene Leviantbe809a72016-11-18 06:44:18 +00001794// Add symbols to this symbol hash table. Note that this function
1795// destructively sort a given vector -- which is needed because
1796// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001797void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001798 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1799 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001800 std::vector<SymbolTableEntry>::iterator Mid =
1801 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001802 // Shared symbols that this executable preempts are special. The dynamic
1803 // linker has to look them up, so they have to be in the hash table.
Zachary Turnera104d552017-11-03 22:33:49 +00001804 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001805 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001806 return !S.Sym->isDefined();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001807 });
1808 if (Mid == V.end())
1809 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001810
1811 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
Zachary Turnera104d552017-11-03 22:33:49 +00001812 Symbol *B = Ent.Sym;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001813 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001814 }
1815
Rui Ueyamae13373b2017-03-01 02:51:42 +00001816 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001817 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001818 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001819 return L.Hash % NBuckets < R.Hash % NBuckets;
1820 });
1821
1822 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001823 for (const Entry &Ent : Symbols)
Rui Ueyama48882242017-11-04 00:31:04 +00001824 V.push_back({Ent.Sym, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001825}
1826
George Rimaraaf54712017-09-27 09:14:59 +00001827HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001828 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1829 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001830}
1831
George Rimaraaf54712017-09-27 09:14:59 +00001832void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001833 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001834
George Rimar67c60722017-07-18 11:55:35 +00001835 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001836 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001837
1838 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001839 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001840 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001841}
1842
George Rimaraaf54712017-09-27 09:14:59 +00001843void HashTableSection::writeTo(uint8_t *Buf) {
George Rimar69b17c32017-05-16 10:04:42 +00001844 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001845
George Rimaraaf54712017-09-27 09:14:59 +00001846 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00001847 write32(P++, NumSymbols); // nbucket
1848 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001849
George Rimaraaf54712017-09-27 09:14:59 +00001850 uint32_t *Buckets = P;
1851 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001852
George Rimar69b17c32017-05-16 10:04:42 +00001853 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Rui Ueyama48882242017-11-04 00:31:04 +00001854 Symbol *Sym = S.Sym;
1855 StringRef Name = Sym->getName();
1856 unsigned I = Sym->DynsymIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001857 uint32_t Hash = hashSysV(Name) % NumSymbols;
1858 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00001859 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001860 }
1861}
1862
George Rimardfc020e2017-03-17 11:01:57 +00001863PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001864 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001865 HeaderSize(S) {
1866 // The PLT needs to be writable on SPARC as the dynamic linker will
1867 // modify the instructions in the PLT entries.
1868 if (Config->EMachine == EM_SPARCV9)
1869 this->Flags |= SHF_WRITE;
1870}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001871
George Rimardfc020e2017-03-17 11:01:57 +00001872void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001873 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1874 // linker to resolve dynsyms at runtime. Write such code.
1875 if (HeaderSize != 0)
1876 Target->writePltHeader(Buf);
1877 size_t Off = HeaderSize;
1878 // The IPlt is immediately after the Plt, account for this in RelOff
1879 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001880
1881 for (auto &I : Entries) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001882 const Symbol *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001883 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001884 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001885 uint64_t Plt = this->getVA() + Off;
1886 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1887 Off += Target->PltEntrySize;
1888 }
1889}
1890
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001891template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001892 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001893 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1894 if (HeaderSize == 0) {
1895 PltRelocSection = In<ELFT>::RelaIplt;
1896 Sym.IsInIplt = true;
1897 }
1898 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001899 Entries.push_back(std::make_pair(&Sym, RelOff));
1900}
1901
George Rimardfc020e2017-03-17 11:01:57 +00001902size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001903 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001904}
1905
Peter Smith96943762017-01-25 10:31:16 +00001906// Some architectures such as additional symbols in the PLT section. For
1907// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001908void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001909 // The PLT may have symbols defined for the Header, the IPLT has no header
1910 if (HeaderSize != 0)
1911 Target->addPltHeaderSymbols(this);
1912 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001913 for (size_t I = 0; I < Entries.size(); ++I) {
1914 Target->addPltSymbols(this, Off);
1915 Off += Target->PltEntrySize;
1916 }
1917}
1918
George Rimardfc020e2017-03-17 11:01:57 +00001919unsigned PltSection::getPltRelocOff() const {
1920 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001921}
1922
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001923// The string hash function for .gdb_index.
1924static uint32_t computeGdbHash(StringRef S) {
1925 uint32_t H = 0;
1926 for (uint8_t C : S)
1927 H = H * 67 + tolower(C) - 113;
1928 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001929}
1930
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001931static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1932 std::vector<GdbIndexChunk::CuEntry> Ret;
1933 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1934 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001935 return Ret;
1936}
1937
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001938static std::vector<GdbIndexChunk::AddressEntry>
1939readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1940 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001941
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001942 uint32_t CuIdx = 0;
1943 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001944 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001945 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001946
George Rimar35e846e2017-03-21 08:19:34 +00001947 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001948 for (DWARFAddressRange &R : Ranges) {
1949 InputSectionBase *S = Sections[R.SectionIndex];
1950 if (!S || S == &InputSection::Discarded || !S->Live)
1951 continue;
1952 // Range list with zero size has no effect.
1953 if (R.LowPC == R.HighPC)
1954 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001955 auto *IS = cast<InputSection>(S);
1956 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001957 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001958 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001959 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001960 }
1961 return Ret;
1962}
1963
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001964static std::vector<GdbIndexChunk::NameTypeEntry>
1965readPubNamesAndTypes(DWARFContext &Dwarf) {
1966 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1967 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001968
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001969 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1970 for (StringRef Sec : {Sec1, Sec2}) {
1971 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001972 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1973 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1974 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1975 Ret.push_back({S, Ent.Descriptor.toBits()});
1976 }
1977 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001978 }
1979 return Ret;
1980}
1981
George Rimar86665622017-06-07 16:59:11 +00001982static std::vector<InputSection *> getDebugInfoSections() {
1983 std::vector<InputSection *> Ret;
1984 for (InputSectionBase *S : InputSections)
1985 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001986 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001987 Ret.push_back(IS);
1988 return Ret;
1989}
1990
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001991void GdbIndexSection::fixCuIndex() {
1992 uint32_t Idx = 0;
1993 for (GdbIndexChunk &Chunk : Chunks) {
1994 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1995 Ent.CuIndex += Idx;
1996 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00001997 }
1998}
1999
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002000std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2001 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002002 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002003 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002004
2005 for (GdbIndexChunk &Chunk : Chunks) {
2006 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002007 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002008 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002009 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2010 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002011 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002012 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002013
2014 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2015 // duplicate entries, so we want to dedup them.
2016 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2017 uint32_t Val = (Ent.Type << 24) | Idx;
2018 if (Vec.empty() || Vec.back() != Val)
2019 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002020 }
2021 Idx += Chunk.CompilationUnits.size();
2022 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002023
2024 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002025 return Ret;
2026}
George Rimar8b547392016-12-15 09:08:13 +00002027
Rafael Espindola300b3862017-07-12 23:56:53 +00002028template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002029 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002030 std::vector<InputSection *> Sections = getDebugInfoSections();
2031 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002032
George Rimar2d23da02017-08-01 14:57:13 +00002033 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002034 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2035 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2036
2037 Chunks[I].DebugInfoSec = Sections[I];
2038 Chunks[I].CompilationUnits = readCuList(Dwarf);
2039 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2040 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002041 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002042
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002043 // .debug_gnu_pub{names,types} are useless in executables.
2044 // They are present in input object files solely for creating
2045 // a .gdb_index. So we can remove it from the output.
2046 for (InputSectionBase *S : InputSections)
2047 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2048 S->Live = false;
2049
2050 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002051 return make<GdbIndexSection>(std::move(Chunks));
2052}
2053
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002054static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002055 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002056 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002057 Ret += D.CompilationUnits.size();
2058 return Ret;
2059}
George Rimarec02b8d2016-12-15 12:07:53 +00002060
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002061static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002062 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002063 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002064 Ret += D.AddressAreas.size();
2065 return Ret;
2066}
2067
2068std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002069 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2070 if (Size < 1024)
2071 Size = 1024;
2072
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002073 uint32_t Mask = Size - 1;
2074 std::vector<GdbSymbol *> Ret(Size);
2075
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002076 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002077 GdbSymbol *Sym = KV.second;
2078 uint32_t I = Sym->NameHash & Mask;
2079 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2080
2081 while (Ret[I])
2082 I = (I + Step) & Mask;
2083 Ret[I] = Sym;
2084 }
George Rimar86665622017-06-07 16:59:11 +00002085 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002086}
2087
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002088GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002089 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002090 fixCuIndex();
2091 CuVectors = createCuVectors();
2092 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002093
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002094 // Compute offsets early to know the section size.
2095 // Each chunk size needs to be in sync with what we write in writeTo.
2096 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2097 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2098 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002099
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002100 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002101 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002102 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002103 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002104 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002105 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002106}
2107
George Rimar35e846e2017-03-21 08:19:34 +00002108size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002109 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002110}
2111
George Rimar35e846e2017-03-21 08:19:34 +00002112void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002113 // Write the section header.
2114 write32le(Buf, 7);
2115 write32le(Buf + 4, CuListOffset);
2116 write32le(Buf + 8, CuTypesOffset);
2117 write32le(Buf + 12, CuTypesOffset);
2118 write32le(Buf + 16, SymtabOffset);
2119 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002120 Buf += 24;
2121
2122 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002123 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002124 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002125 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002126 write64le(Buf + 8, Cu.CuLength);
2127 Buf += 16;
2128 }
Eugene Levianta113a412016-11-21 09:24:43 +00002129 }
George Rimar8b547392016-12-15 09:08:13 +00002130
2131 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002132 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002133 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00002134 uint64_t BaseAddr =
2135 E.Section->getParent()->Addr + E.Section->getOffset(0);
2136 write64le(Buf, BaseAddr + E.LowAddress);
2137 write64le(Buf + 8, BaseAddr + E.HighAddress);
2138 write32le(Buf + 16, E.CuIndex);
2139 Buf += 20;
2140 }
George Rimar8b547392016-12-15 09:08:13 +00002141 }
George Rimarec02b8d2016-12-15 12:07:53 +00002142
2143 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002144 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002145 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002146 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2147 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002148 }
2149 Buf += 8;
2150 }
2151
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002152 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002153 for (ArrayRef<uint32_t> Vec : CuVectors) {
2154 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002155 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002156 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002157 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002158 Buf += 4;
2159 }
2160 }
2161
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002162 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002163 for (auto &KV : Symbols) {
2164 CachedHashStringRef S = KV.first;
2165 GdbSymbol *Sym = KV.second;
2166 size_t Off = Sym->NameOffset;
2167 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002168 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002169 }
Eugene Levianta113a412016-11-21 09:24:43 +00002170}
2171
George Rimar67c60722017-07-18 11:55:35 +00002172bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002173
Rui Ueyama02551ab2017-10-27 03:14:24 +00002174EhFrameHeader::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002175 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002176
2177// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2178// Each entry of the search table consists of two values,
2179// the starting PC from where FDEs covers, and the FDE's address.
2180// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002181void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002182 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002183
Rui Ueyama02551ab2017-10-27 03:14:24 +00002184 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002185
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002186 // Sort the FDE list by their PC and uniqueify. Usually there is only
2187 // one FDE for a PC (i.e. function), but if ICF merges two functions
2188 // into one, there can be more than one FDEs pointing to the address.
2189 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2190 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2191 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2192 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2193
2194 Buf[0] = 1;
2195 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2196 Buf[2] = DW_EH_PE_udata4;
2197 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002198 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2199 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002200 Buf += 12;
2201
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002202 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002203 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002204 write32(Buf, Fde.Pc - VA);
2205 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002206 Buf += 8;
2207 }
2208}
2209
Rui Ueyama02551ab2017-10-27 03:14:24 +00002210size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002211 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002212 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002213}
2214
Rui Ueyama02551ab2017-10-27 03:14:24 +00002215bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002216
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002217template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002218VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002219 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2220 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002221
2222static StringRef getFileDefName() {
2223 if (!Config->SoName.empty())
2224 return Config->SoName;
2225 return Config->OutputFile;
2226}
2227
Rui Ueyama945055a2017-02-27 03:07:41 +00002228template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002229 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002230 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002231 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002232
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002233 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002234
2235 // sh_info should be set to the number of definitions. This fact is missed in
2236 // documentation, but confirmed by binutils community:
2237 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002238 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002239}
2240
2241template <class ELFT>
2242void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2243 StringRef Name, size_t NameOff) {
2244 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2245 Verdef->vd_version = 1;
2246 Verdef->vd_cnt = 1;
2247 Verdef->vd_aux = sizeof(Elf_Verdef);
2248 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2249 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2250 Verdef->vd_ndx = Index;
2251 Verdef->vd_hash = hashSysV(Name);
2252
2253 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2254 Verdaux->vda_name = NameOff;
2255 Verdaux->vda_next = 0;
2256}
2257
2258template <class ELFT>
2259void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2260 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2261
2262 for (VersionDefinition &V : Config->VersionDefinitions) {
2263 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2264 writeOne(Buf, V.Id, V.Name, V.NameOff);
2265 }
2266
2267 // Need to terminate the last version definition.
2268 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2269 Verdef->vd_next = 0;
2270}
2271
2272template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2273 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2274}
2275
2276template <class ELFT>
2277VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002278 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002279 ".gnu.version") {
2280 this->Entsize = sizeof(Elf_Versym);
2281}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002282
Rui Ueyama945055a2017-02-27 03:07:41 +00002283template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002284 // At the moment of june 2016 GNU docs does not mention that sh_link field
2285 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002286 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002287}
2288
2289template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002290 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002291}
2292
2293template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2294 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002295 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Zachary Turnera104d552017-11-03 22:33:49 +00002296 OutVersym->vs_index = S.Sym->VersionId;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002297 ++OutVersym;
2298 }
2299}
2300
George Rimar11992c862016-11-25 08:05:41 +00002301template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2302 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2303}
2304
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002305template <class ELFT>
2306VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002307 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2308 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002309 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2310 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2311 // First identifiers are reserved by verdef section if it exist.
2312 NextIndex = getVerDefNum() + 1;
2313}
2314
2315template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002316void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2317 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2318 if (!Ver) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002319 SS->VersionId = VER_NDX_GLOBAL;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002320 return;
2321 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002322
Rafael Espindola6e93d052017-08-04 22:31:42 +00002323 SharedFile<ELFT> *File = SS->getFile<ELFT>();
Rui Ueyama4076fa12017-02-26 23:35:34 +00002324
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002325 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2326 // to create one by adding it to our needed list and creating a dynstr entry
2327 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002328 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002329 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002330 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002331 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2332 // prepare to create one by allocating a version identifier and creating a
2333 // dynstr entry for the version name.
2334 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002335 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2336 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002337 NV.Index = NextIndex++;
2338 }
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002339 SS->VersionId = NV.Index;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002340}
2341
2342template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2343 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2344 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2345 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2346
2347 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2348 // Create an Elf_Verneed for this DSO.
2349 Verneed->vn_version = 1;
2350 Verneed->vn_cnt = P.first->VerdefMap.size();
2351 Verneed->vn_file = P.second;
2352 Verneed->vn_aux =
2353 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2354 Verneed->vn_next = sizeof(Elf_Verneed);
2355 ++Verneed;
2356
2357 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2358 // VerdefMap, which will only contain references to needed version
2359 // definitions. Each Elf_Vernaux is based on the information contained in
2360 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2361 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2362 // data structures within a single input file.
2363 for (auto &NV : P.first->VerdefMap) {
2364 Vernaux->vna_hash = NV.first->vd_hash;
2365 Vernaux->vna_flags = 0;
2366 Vernaux->vna_other = NV.second.Index;
2367 Vernaux->vna_name = NV.second.StrTab;
2368 Vernaux->vna_next = sizeof(Elf_Vernaux);
2369 ++Vernaux;
2370 }
2371
2372 Vernaux[-1].vna_next = 0;
2373 }
2374 Verneed[-1].vn_next = 0;
2375}
2376
Rui Ueyama945055a2017-02-27 03:07:41 +00002377template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002378 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2379 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002380}
2381
2382template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2383 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2384 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2385 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2386 return Size;
2387}
2388
George Rimar11992c862016-11-25 08:05:41 +00002389template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2390 return getNeedNum() == 0;
2391}
2392
Rafael Espindola6119b862017-03-06 20:23:56 +00002393void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002394 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002395 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002396}
2397
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002398MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2399 uint64_t Flags, uint32_t Alignment)
2400 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2401 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002402
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002403size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2404
2405void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002406
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002407void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002408 // Add all string pieces to the string table builder to create section
2409 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002410 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002411 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2412 if (Sec->Pieces[I].Live)
2413 Builder.add(Sec->getData(I));
2414
2415 // Fix the string table content. After this, the contents will never change.
2416 Builder.finalize();
2417
2418 // finalize() fixed tail-optimized strings, so we can now get
2419 // offsets of strings. Get an offset for each string and save it
2420 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002421 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002422 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2423 if (Sec->Pieces[I].Live)
2424 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2425}
2426
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002427void MergeNoTailSection::writeTo(uint8_t *Buf) {
2428 for (size_t I = 0; I < NumShards; ++I)
2429 Shards[I].write(Buf + ShardOffsets[I]);
2430}
2431
2432// This function is very hot (i.e. it can take several seconds to finish)
2433// because sometimes the number of inputs is in an order of magnitude of
2434// millions. So, we use multi-threading.
2435//
2436// For any strings S and T, we know S is not mergeable with T if S's hash
2437// value is different from T's. If that's the case, we can safely put S and
2438// T into different string builders without worrying about merge misses.
2439// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002440void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002441 // Initializes string table builders.
2442 for (size_t I = 0; I < NumShards; ++I)
2443 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2444
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002445 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2446 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002447 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002448 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002449 Concurrency =
2450 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002451
2452 // Add section pieces to the builders.
2453 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2454 for (MergeInputSection *Sec : Sections) {
2455 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2456 if (!Sec->Pieces[I].Live)
2457 continue;
Rui Ueyama95bf5092017-10-21 23:20:13 +00002458 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002459 if ((ShardId & (Concurrency - 1)) == ThreadId)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002460 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002461 }
2462 }
2463 });
2464
2465 // Compute an in-section offset for each shard.
2466 size_t Off = 0;
2467 for (size_t I = 0; I < NumShards; ++I) {
2468 Shards[I].finalizeInOrder();
2469 if (Shards[I].getSize() > 0)
2470 Off = alignTo(Off, Alignment);
2471 ShardOffsets[I] = Off;
2472 Off += Shards[I].getSize();
2473 }
2474 Size = Off;
2475
2476 // So far, section pieces have offsets from beginning of shards, but
2477 // we want offsets from beginning of the whole section. Fix them.
2478 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002479 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2480 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002481 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002482 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002483 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002484}
2485
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002486static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2487 uint32_t Type,
2488 uint64_t Flags,
2489 uint32_t Alignment) {
2490 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2491 if (ShouldTailMerge)
2492 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2493 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002494}
2495
Rui Ueyama2b714b52017-10-11 03:12:53 +00002496// Debug sections may be compressed by zlib. Uncompress if exists.
2497void elf::decompressSections() {
2498 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2499 if (Sec->Live)
2500 Sec->maybeUncompress();
2501 });
2502}
2503
2504// This function scans over the inputsections to create mergeable
2505// synthetic sections.
2506//
2507// It removes MergeInputSections from the input section array and adds
2508// new synthetic sections at the location of the first input section
2509// that it replaces. It then finalizes each synthetic section in order
2510// to compute an output offset for each piece of each input section.
2511void elf::mergeSections() {
2512 // splitIntoPieces needs to be called on each MergeInputSection
2513 // before calling finalizeContents(). Do that first.
2514 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2515 if (Sec->Live)
2516 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2517 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002518 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002519
2520 std::vector<MergeSyntheticSection *> MergeSections;
2521 for (InputSectionBase *&S : InputSections) {
2522 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2523 if (!MS)
2524 continue;
2525
2526 // We do not want to handle sections that are not alive, so just remove
2527 // them instead of trying to merge.
2528 if (!MS->Live)
2529 continue;
2530
2531 StringRef OutsecName = getOutputSectionName(MS->Name);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002532 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2533
2534 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002535 // While we could create a single synthetic section for two different
2536 // values of Entsize, it is better to take Entsize into consideration.
2537 //
2538 // With a single synthetic section no two pieces with different Entsize
2539 // could be equal, so we may as well have two sections.
2540 //
2541 // Using Entsize in here also allows us to propagate it to the synthetic
2542 // section.
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002543 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002544 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002545 });
2546 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002547 MergeSyntheticSection *Syn =
2548 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002549 MergeSections.push_back(Syn);
2550 I = std::prev(MergeSections.end());
2551 S = Syn;
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002552 Syn->Entsize = MS->Entsize;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002553 } else {
2554 S = nullptr;
2555 }
2556 (*I)->addSection(MS);
2557 }
2558 for (auto *MS : MergeSections)
2559 MS->finalizeContents();
2560
2561 std::vector<InputSectionBase *> &V = InputSections;
2562 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2563}
2564
George Rimar42886c42017-03-15 12:02:31 +00002565MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002566 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2567 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002568
George Rimar90a528b2017-03-21 09:01:39 +00002569ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002570 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002571 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002572
2573// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2574// This section will have been sorted last in the .ARM.exidx table.
2575// This table entry will have the form:
2576// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002577// The sentinel must have the PREL31 value of an address higher than any
2578// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002579void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002580 // The Sections are sorted in order of ascending PREL31 address with the
2581 // sentinel last. We need to find the InputSection that precedes the
2582 // sentinel. By construction the Sentinel is in the last
2583 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +00002584 OutputSection *C = getParent();
Rui Ueyama6b394ca2017-10-11 01:50:56 +00002585 auto ISD =
2586 std::find_if(C->SectionCommands.rbegin(), C->SectionCommands.rend(),
2587 [](const BaseCommand *Base) {
2588 return isa<InputSectionDescription>(Base);
2589 });
Peter Smithea79b212017-05-31 09:02:21 +00002590 auto L = cast<InputSectionDescription>(*ISD);
2591 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002592 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002593 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002594 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002595 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002596 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002597}
2598
George Rimar7b827042017-03-16 10:40:50 +00002599ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002600 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002601 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002602 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002603 this->OutSecOff = Off;
2604}
2605
George Rimar7b827042017-03-16 10:40:50 +00002606void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002607 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002608 T->Offset = Off;
2609 Thunks.push_back(T);
2610 T->addSymbols(*this);
2611 Size = Off + T->size();
2612}
2613
George Rimar7b827042017-03-16 10:40:50 +00002614void ThunkSection::writeTo(uint8_t *Buf) {
2615 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002616 T->writeTo(Buf + T->Offset, *this);
2617}
2618
George Rimar7b827042017-03-16 10:40:50 +00002619InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002620 if (Thunks.empty())
2621 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002622 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002623 return T->getTargetInputSection();
2624}
2625
George Rimar9782ca52017-03-15 15:29:29 +00002626InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002627BssSection *InX::Bss;
2628BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002629BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002630EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002631EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002632SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002633StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002634SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002635InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002636GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002637GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002638GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002639GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002640HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002641IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002642MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002643MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002644PltSection *InX::Plt;
2645PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002646StringTableSection *InX::ShStrTab;
2647StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002648SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002649
Rafael Espindola300b3862017-07-12 23:56:53 +00002650template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2651template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2652template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2653template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2654
Rui Ueyama572247f2017-10-27 03:13:39 +00002655template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2656template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2657template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2658template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2659
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002660template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2661template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2662template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2663template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
George Rimara9189572017-03-17 16:50:07 +00002664
Rafael Espindola6119b862017-03-06 20:23:56 +00002665template MergeInputSection *elf::createCommentSection<ELF32LE>();
2666template MergeInputSection *elf::createCommentSection<ELF32BE>();
2667template MergeInputSection *elf::createCommentSection<ELF64LE>();
2668template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002669
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002670template class elf::MipsAbiFlagsSection<ELF32LE>;
2671template class elf::MipsAbiFlagsSection<ELF32BE>;
2672template class elf::MipsAbiFlagsSection<ELF64LE>;
2673template class elf::MipsAbiFlagsSection<ELF64BE>;
2674
Simon Atanasyance02cf02016-11-09 21:36:56 +00002675template class elf::MipsOptionsSection<ELF32LE>;
2676template class elf::MipsOptionsSection<ELF32BE>;
2677template class elf::MipsOptionsSection<ELF64LE>;
2678template class elf::MipsOptionsSection<ELF64BE>;
2679
2680template class elf::MipsReginfoSection<ELF32LE>;
2681template class elf::MipsReginfoSection<ELF32BE>;
2682template class elf::MipsReginfoSection<ELF64LE>;
2683template class elf::MipsReginfoSection<ELF64BE>;
2684
Eugene Leviant6380ce22016-11-15 12:26:55 +00002685template class elf::DynamicSection<ELF32LE>;
2686template class elf::DynamicSection<ELF32BE>;
2687template class elf::DynamicSection<ELF64LE>;
2688template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002689
2690template class elf::RelocationSection<ELF32LE>;
2691template class elf::RelocationSection<ELF32BE>;
2692template class elf::RelocationSection<ELF64LE>;
2693template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002694
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002695template class elf::AndroidPackedRelocationSection<ELF32LE>;
2696template class elf::AndroidPackedRelocationSection<ELF32BE>;
2697template class elf::AndroidPackedRelocationSection<ELF64LE>;
2698template class elf::AndroidPackedRelocationSection<ELF64BE>;
2699
Eugene Leviant9230db92016-11-17 09:16:34 +00002700template class elf::SymbolTableSection<ELF32LE>;
2701template class elf::SymbolTableSection<ELF32BE>;
2702template class elf::SymbolTableSection<ELF64LE>;
2703template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002704
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002705template class elf::VersionTableSection<ELF32LE>;
2706template class elf::VersionTableSection<ELF32BE>;
2707template class elf::VersionTableSection<ELF64LE>;
2708template class elf::VersionTableSection<ELF64BE>;
2709
2710template class elf::VersionNeedSection<ELF32LE>;
2711template class elf::VersionNeedSection<ELF32BE>;
2712template class elf::VersionNeedSection<ELF64LE>;
2713template class elf::VersionNeedSection<ELF64BE>;
2714
2715template class elf::VersionDefinitionSection<ELF32LE>;
2716template class elf::VersionDefinitionSection<ELF32BE>;
2717template class elf::VersionDefinitionSection<ELF64LE>;
2718template class elf::VersionDefinitionSection<ELF64BE>;