blob: 36e3ffa284ef4858c8f618fc6243af19814449bb [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"
Rafael Espindolad26b52f2017-12-09 16:56:18 +000025#include "Symbols.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000026#include "Target.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000027#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000028#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000029#include "lld/Common/Memory.h"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000030#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000031#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000033#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000034#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000035#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000036#include "llvm/Support/Endian.h"
Peter Collingbourne5c54f152017-10-27 17:49:40 +000037#include "llvm/Support/LEB128.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000038#include "llvm/Support/MD5.h"
39#include "llvm/Support/RandomNumberGenerator.h"
40#include "llvm/Support/SHA1.h"
41#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000042#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000043#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000044
45using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000046using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000047using namespace llvm::ELF;
48using namespace llvm::object;
49using namespace llvm::support;
50using namespace llvm::support::endian;
51
52using namespace lld;
53using namespace lld::elf;
54
NAKAMURA Takumi70947e22017-09-30 13:40:22 +000055constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000056
Rui Ueyama79048e42017-10-27 03:59:34 +000057static void write32(void *Buf, uint32_t Val) {
58 endian::write32(Buf, Val, Config->Endianness);
59}
60
Rui Ueyama9320cb02017-02-27 02:56:02 +000061uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000062 if (OutputSection *Sec = getParent())
63 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000064 return 0;
65}
66
Rui Ueyama3da3f062016-11-10 20:20:37 +000067// Returns an LLD version string.
68static ArrayRef<uint8_t> getVersion() {
69 // Check LLD_VERSION first for ease of testing.
70 // You can get consitent output by using the environment variable.
71 // This is only for testing.
72 StringRef S = getenv("LLD_VERSION");
73 if (S.empty())
74 S = Saver.save(Twine("Linker: ") + getLLDVersion());
75
76 // +1 to include the terminating '\0'.
77 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000078}
Rui Ueyama3da3f062016-11-10 20:20:37 +000079
80// Creates a .comment section containing LLD version info.
81// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000082// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000083// The returned object is a mergeable string section.
Rafael Espindola5c73c492017-12-21 01:21:59 +000084MergeInputSection *elf::createCommentSection() {
85 return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
86 getVersion(), ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +000087}
88
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000089// .MIPS.abiflags section.
90template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +000091MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +000092 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +000093 Flags(Flags) {
94 this->Entsize = sizeof(Elf_Mips_ABIFlags);
95}
Rui Ueyama12f2da82016-11-22 03:57:06 +000096
97template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
98 memcpy(Buf, &Flags, sizeof(Flags));
99}
100
101template <class ELFT>
102MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
103 Elf_Mips_ABIFlags Flags = {};
104 bool Create = false;
105
Rui Ueyama536a2672017-02-27 02:32:08 +0000106 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000107 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000108 continue;
109 Sec->Live = false;
110 Create = true;
111
Rui Ueyama25f30882017-10-27 03:25:04 +0000112 std::string Filename = toString(Sec->File);
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000113 const size_t Size = Sec->Data.size();
114 // Older version of BFD (such as the default FreeBSD linker) concatenate
115 // .MIPS.abiflags instead of merging. To allow for this case (or potential
116 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
117 if (Size < sizeof(Elf_Mips_ABIFlags)) {
118 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
119 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000120 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000121 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000122 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000123 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000124 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000125 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000126 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000127 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000128
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000129 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000130 // select the highest number of ISA/Rev/Ext.
131 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
132 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
133 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
134 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
135 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
136 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
137 Flags.ases |= S->ases;
138 Flags.flags1 |= S->flags1;
139 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000140 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000141 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000142
Rui Ueyama12f2da82016-11-22 03:57:06 +0000143 if (Create)
144 return make<MipsAbiFlagsSection<ELFT>>(Flags);
145 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000146}
147
Simon Atanasyance02cf02016-11-09 21:36:56 +0000148// .MIPS.options section.
149template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000150MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000151 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000152 Reginfo(Reginfo) {
153 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
154}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000155
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000156template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
157 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
158 Options->kind = ODK_REGINFO;
159 Options->size = getSize();
160
161 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000162 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000163 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000164}
165
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000166template <class ELFT>
167MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
168 // N64 ABI only.
169 if (!ELFT::Is64Bits)
170 return nullptr;
171
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000172 std::vector<InputSectionBase *> Sections;
173 for (InputSectionBase *Sec : InputSections)
174 if (Sec->Type == SHT_MIPS_OPTIONS)
175 Sections.push_back(Sec);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000176
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000177 if (Sections.empty())
178 return nullptr;
179
180 Elf_Mips_RegInfo Reginfo = {};
181 for (InputSectionBase *Sec : Sections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000182 Sec->Live = false;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000183
Rui Ueyama25f30882017-10-27 03:25:04 +0000184 std::string Filename = toString(Sec->File);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000185 ArrayRef<uint8_t> D = Sec->Data;
186
187 while (!D.empty()) {
188 if (D.size() < sizeof(Elf_Mips_Options)) {
189 error(Filename + ": invalid size of .MIPS.options section");
190 break;
191 }
192
193 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
194 if (Opt->kind == ODK_REGINFO) {
195 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
196 error(Filename + ": unsupported non-zero ri_gp_value");
197 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000198 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000199 break;
200 }
201
202 if (!Opt->size)
203 fatal(Filename + ": zero option descriptor size");
204 D = D.slice(Opt->size);
205 }
206 };
207
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000208 return make<MipsOptionsSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000209}
210
211// MIPS .reginfo section.
212template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000213MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000214 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000215 Reginfo(Reginfo) {
216 this->Entsize = sizeof(Elf_Mips_RegInfo);
217}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000218
Rui Ueyamab71cae92016-11-22 03:57:08 +0000219template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000220 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000221 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000222 memcpy(Buf, &Reginfo, sizeof(Reginfo));
223}
224
225template <class ELFT>
226MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
227 // Section should be alive for O32 and N32 ABIs only.
228 if (ELFT::Is64Bits)
229 return nullptr;
230
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000231 std::vector<InputSectionBase *> Sections;
232 for (InputSectionBase *Sec : InputSections)
233 if (Sec->Type == SHT_MIPS_REGINFO)
234 Sections.push_back(Sec);
Rui Ueyamab71cae92016-11-22 03:57:08 +0000235
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000236 if (Sections.empty())
237 return nullptr;
238
239 Elf_Mips_RegInfo Reginfo = {};
240 for (InputSectionBase *Sec : Sections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000241 Sec->Live = false;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000242
243 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama25f30882017-10-27 03:25:04 +0000244 error(toString(Sec->File) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000245 return nullptr;
246 }
247 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
248 if (Config->Relocatable && R->ri_gp_value)
Rui Ueyama25f30882017-10-27 03:25:04 +0000249 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000250
251 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000252 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000253 };
254
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000255 return make<MipsReginfoSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000256}
257
Rui Ueyama3255a522017-02-27 02:32:49 +0000258InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000259 // StringSaver guarantees that the returned string ends with '\0'.
260 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000261 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
262
Rafael Espindolace3b52c2017-12-21 02:11:51 +0000263 auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
264 ".interp");
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000265 Sec->Live = true;
266 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000267}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000268
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000269Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
Rafael Espindola1037eef2017-12-19 23:59:35 +0000270 uint64_t Size, InputSectionBase &Section) {
271 auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
272 Value, Size, &Section);
George Rimar69b17c32017-05-16 10:04:42 +0000273 if (InX::SymTab)
274 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000275 return S;
276}
277
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000278static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000279 switch (Config->BuildId) {
280 case BuildIdKind::Fast:
281 return 8;
282 case BuildIdKind::Md5:
283 case BuildIdKind::Uuid:
284 return 16;
285 case BuildIdKind::Sha1:
286 return 20;
287 case BuildIdKind::Hexstring:
288 return Config->BuildIdVector.size();
289 default:
290 llvm_unreachable("unknown BuildIdKind");
291 }
292}
293
George Rimar6c2949d2017-03-20 16:40:21 +0000294BuildIdSection::BuildIdSection()
Jake Ehrlich1128dc52017-10-30 22:08:11 +0000295 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000296 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000297
George Rimar6c2949d2017-03-20 16:40:21 +0000298void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyama79048e42017-10-27 03:59:34 +0000299 write32(Buf, 4); // Name size
300 write32(Buf + 4, HashSize); // Content size
301 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000302 memcpy(Buf + 12, "GNU", 4); // Name string
303 HashBuf = Buf + 16;
304}
305
Rui Ueyama35e00752016-11-10 00:12:28 +0000306// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000307static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
308 size_t ChunkSize) {
309 std::vector<ArrayRef<uint8_t>> Ret;
310 while (Arr.size() > ChunkSize) {
311 Ret.push_back(Arr.take_front(ChunkSize));
312 Arr = Arr.drop_front(ChunkSize);
313 }
314 if (!Arr.empty())
315 Ret.push_back(Arr);
316 return Ret;
317}
318
Rui Ueyama35e00752016-11-10 00:12:28 +0000319// Computes a hash value of Data using a given hash function.
320// In order to utilize multiple cores, we first split data into 1MB
321// chunks, compute a hash for each chunk, and then compute a hash value
322// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000323void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000324 llvm::ArrayRef<uint8_t> Data,
325 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000326 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000327 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000328
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000329 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000330 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000331 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
332 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000333
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000334 // Write to the final output buffer.
335 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000336}
337
Rui Ueyama732f4e22017-10-04 00:21:17 +0000338BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
339 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Peter Collingbourne6c55a702017-11-06 04:33:58 +0000340 this->Bss = true;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000341 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000342 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000343 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000344}
Peter Smithebfe9942017-02-09 10:27:57 +0000345
George Rimar6c2949d2017-03-20 16:40:21 +0000346void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000347 switch (Config->BuildId) {
348 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000349 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000350 write64le(Dest, xxHash64(toStringRef(Arr)));
351 });
352 break;
353 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000354 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000355 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000356 });
357 break;
358 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000359 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000360 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000361 });
362 break;
363 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000364 if (auto EC = getRandomBytes(HashBuf, HashSize))
365 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000366 break;
367 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000368 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000369 break;
370 default:
371 llvm_unreachable("unknown BuildIdKind");
372 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000373}
374
Rui Ueyama572247f2017-10-27 03:13:39 +0000375EhFrameSection::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000376 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000377
378// Search for an existing CIE record or create a new one.
379// CIE records from input object files are uniquified by their contents
380// and where their relocations point to.
Rui Ueyama572247f2017-10-27 03:13:39 +0000381template <class ELFT, class RelTy>
382CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000383 auto *Sec = cast<EhInputSection>(Cie.Sec);
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000384 if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000385 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000387 Symbol *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000388 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000389 if (FirstRelI != (unsigned)-1)
390 Personality =
391 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
393 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000394 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000395
396 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000397 if (!Rec) {
398 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000399 Rec->Cie = &Cie;
400 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000401 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000402 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000403}
404
405// There is one FDE per function. Returns true if a given FDE
406// points to a live function.
Rui Ueyama572247f2017-10-27 03:13:39 +0000407template <class ELFT, class RelTy>
408bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000409 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000410 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000411
412 // An FDE should point to some function because FDEs are to describe
413 // functions. That's however not always the case due to an issue of
414 // ld.gold with -r. ld.gold may discard only functions and leave their
415 // corresponding FDEs, which results in creating bad .eh_frame sections.
416 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000417 if (FirstRelI == (unsigned)-1)
418 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000419
Rafael Espindola66b4e212017-02-23 22:06:28 +0000420 const RelTy &Rel = Rels[FirstRelI];
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000421 Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000422
423 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +0000424 if (auto *D = dyn_cast<Defined>(&B))
Rafael Espindola13dbf942017-12-13 17:36:53 +0000425 if (SectionBase *Sec = D->Section)
426 return Sec->Live;
Rui Ueyama27a357c2017-09-18 19:15:54 +0000427 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000428}
429
430// .eh_frame is a sequence of CIE or FDE records. In general, there
431// is one CIE record per input object file which is followed by
432// a list of FDEs. This function searches an existing CIE or create a new
433// one and associates FDEs to the CIE.
Rui Ueyama572247f2017-10-27 03:13:39 +0000434template <class ELFT, class RelTy>
435void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000436 DenseMap<size_t, CieRecord *> OffsetToCie;
437 for (EhSectionPiece &Piece : Sec->Pieces) {
438 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000439 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000440 return;
441
442 size_t Offset = Piece.InputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000443 uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000444 if (ID == 0) {
Rui Ueyama572247f2017-10-27 03:13:39 +0000445 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000446 continue;
447 }
448
449 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000450 CieRecord *Rec = OffsetToCie[CieOffset];
451 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000452 fatal(toString(Sec) + ": invalid CIE reference");
453
Rui Ueyama572247f2017-10-27 03:13:39 +0000454 if (!isFdeLive<ELFT>(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000455 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000456 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000457 NumFdes++;
458 }
459}
460
Rui Ueyama572247f2017-10-27 03:13:39 +0000461template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000462 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000463 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000464
465 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000466 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000467
Petr Hosek7b793212017-03-10 20:00:42 +0000468 for (auto *DS : Sec->DependentSections)
469 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000470
471 // .eh_frame is a sequence of CIE or FDE records. This function
472 // splits it into pieces so that we can call
473 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000474 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000475 if (Sec->Pieces.empty())
476 return;
477
Rui Ueyamabfa84322017-10-26 22:30:25 +0000478 if (Sec->AreRelocsRela)
Rui Ueyama572247f2017-10-27 03:13:39 +0000479 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
Rui Ueyamafaa38022017-09-19 20:28:03 +0000480 else
Rui Ueyama572247f2017-10-27 03:13:39 +0000481 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000482}
483
Rafael Espindola66b4e212017-02-23 22:06:28 +0000484static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
485 memcpy(Buf, D.data(), D.size());
486
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000487 size_t Aligned = alignTo(D.size(), Config->Wordsize);
Andrew Ng6dee7362017-09-07 08:43:56 +0000488
489 // Zero-clear trailing padding if it exists.
490 memset(Buf + D.size(), 0, Aligned - D.size());
491
Rafael Espindola66b4e212017-02-23 22:06:28 +0000492 // Fix the size field. -4 since size does not include the size field itself.
Rui Ueyama79048e42017-10-27 03:59:34 +0000493 write32(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000494}
495
Rui Ueyama572247f2017-10-27 03:13:39 +0000496void EhFrameSection::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000497 if (this->Size)
498 return; // Already finalized.
499
500 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000501 for (CieRecord *Rec : CieRecords) {
502 Rec->Cie->OutputOff = Off;
503 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000504
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000505 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000506 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000507 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000508 }
509 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000510
511 // The LSB standard does not allow a .eh_frame section with zero
512 // Call Frame Information records. Therefore add a CIE record length
513 // 0 as a terminator if this .eh_frame section is empty.
514 if (Off == 0)
515 Off = 4;
516
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000517 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000518}
519
Rui Ueyamac0552252017-10-27 03:13:24 +0000520// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
521// to get an FDE from an address to which FDE is applied. This function
522// returns a list of such pairs.
Rui Ueyama572247f2017-10-27 03:13:39 +0000523std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
Rui Ueyamac0552252017-10-27 03:13:24 +0000524 uint8_t *Buf = getParent()->Loc + OutSecOff;
525 std::vector<FdeData> Ret;
526
527 for (CieRecord *Rec : CieRecords) {
Rui Ueyama86297522017-10-27 03:14:09 +0000528 uint8_t Enc = getFdeEncoding(Rec->Cie);
Rui Ueyamac0552252017-10-27 03:13:24 +0000529 for (EhSectionPiece *Fde : Rec->Fdes) {
530 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
531 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
532 Ret.push_back({Pc, FdeVA});
533 }
534 }
535 return Ret;
536}
537
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000538static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000539 switch (Size) {
540 case DW_EH_PE_udata2:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000541 return read16(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000542 case DW_EH_PE_udata4:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000543 return read32(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000544 case DW_EH_PE_udata8:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000545 return read64(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000546 case DW_EH_PE_absptr:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000547 return readUint(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000548 }
549 fatal("unknown FDE size encoding");
550}
551
552// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
553// We need it to create .eh_frame_hdr section.
Rui Ueyama572247f2017-10-27 03:13:39 +0000554uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
555 uint8_t Enc) const {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000556 // The starting address to which this FDE applies is
557 // stored at FDE + 8 byte.
558 size_t Off = FdeOff + 8;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000559 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000560 if ((Enc & 0x70) == DW_EH_PE_absptr)
561 return Addr;
562 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000563 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000564 fatal("unknown FDE size relative encoding");
565}
566
Rui Ueyama572247f2017-10-27 03:13:39 +0000567void EhFrameSection::writeTo(uint8_t *Buf) {
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000568 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000569 for (CieRecord *Rec : CieRecords) {
570 size_t CieOffset = Rec->Cie->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000571 writeCieFde(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000572
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000573 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000574 size_t Off = Fde->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000575 writeCieFde(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000576
577 // FDE's second word should have the offset to an associated CIE.
578 // Write it.
Rui Ueyama79048e42017-10-27 03:59:34 +0000579 write32(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000580 }
581 }
582
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000583 // Apply relocations. .eh_frame section contents are not contiguous
584 // in the output buffer, but relocateAlloc() still works because
585 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000586 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000587 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000588}
589
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000590GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000591 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
592 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000593
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000594void GotSection::addEntry(Symbol &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000595 Sym.GotIndex = NumEntries;
596 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000597}
598
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000599bool GotSection::addDynTlsEntry(Symbol &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000600 if (Sym.GlobalDynIndex != -1U)
601 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000602 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000603 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000604 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000605 return true;
606}
607
608// Reserves TLS entries for a TLS module ID and a TLS block offset.
609// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000610bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000611 if (TlsIndexOff != uint32_t(-1))
612 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000613 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000614 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000615 return true;
616}
617
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000618uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000619 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000620}
621
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000622uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000623 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000624}
625
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000626void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000627
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000628bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000629 // We need to emit a GOT even if it's empty if there's a relocation that is
630 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
631 // (i.e. _GLOBAL_OFFSET_TABLE_).
632 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
George Rimar11992c862016-11-25 08:05:41 +0000633}
634
Igor Kudrin202a9f62017-07-14 08:10:45 +0000635void GotSection::writeTo(uint8_t *Buf) {
636 // Buf points to the start of this section's buffer,
637 // whereas InputSectionBase::relocateAlloc() expects its argument
638 // to point to the start of the output section.
639 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
640}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000641
George Rimar14534eb2017-03-20 16:44:28 +0000642MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000643 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
644 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000645
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000646void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000647 // For "true" local symbols which can be referenced from the same module
648 // only compiler creates two instructions for address loading:
649 //
650 // lw $8, 0($gp) # R_MIPS_GOT16
651 // addi $8, $8, 0 # R_MIPS_LO16
652 //
653 // The first instruction loads high 16 bits of the symbol address while
654 // the second adds an offset. That allows to reduce number of required
655 // GOT entries because only one global offset table entry is necessary
656 // for every 64 KBytes of local data. So for local symbols we need to
657 // allocate number of GOT entries to hold all required "page" addresses.
658 //
659 // All global symbols (hidden and regular) considered by compiler uniformly.
660 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
661 // to load address of the symbol. So for each such symbol we need to
662 // allocate dedicated GOT entry to store its address.
663 //
664 // If a symbol is preemptible we need help of dynamic linker to get its
665 // final address. The corresponding GOT entries are allocated in the
666 // "global" part of GOT. Entries for non preemptible global symbol allocated
667 // in the "local" part of GOT.
668 //
669 // See "Global Offset Table" in Chapter 5:
670 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
671 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
672 // At this point we do not know final symbol value so to reduce number
673 // of allocated GOT entries do the following trick. Save all output
674 // sections referenced by GOT relocations. Then later in the `finalize`
675 // method calculate number of "pages" required to cover all saved output
676 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000677 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000678 return;
679 }
680 if (Sym.isTls()) {
681 // GOT entries created for MIPS TLS relocations behave like
682 // almost GOT entries from other ABIs. They go to the end
683 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000684 Sym.GotIndex = TlsEntries.size();
685 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000686 return;
687 }
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000688 auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000689 if (S.isInGot() && !A)
690 return;
691 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000692 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000693 return;
694 Items.emplace_back(&S, A);
695 if (!A)
696 S.GotIndex = NewIndex;
697 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000698 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000699 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000700 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000701 Sym.IsInGlobalMipsGot = true;
702 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000703 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000704 Sym.Is32BitMipsGot = true;
705 } else {
706 // Hold local GOT entries accessed via a 16-bit index separately.
707 // That allows to write them in the beginning of the GOT and keep
708 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000709 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000710 }
711}
712
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000713bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000714 if (Sym.GlobalDynIndex != -1U)
715 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000716 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000717 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000718 TlsEntries.push_back(nullptr);
719 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000720 return true;
721}
722
723// Reserves TLS entries for a TLS module ID and a TLS block offset.
724// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000725bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 if (TlsIndexOff != uint32_t(-1))
727 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000728 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000729 TlsEntries.push_back(nullptr);
730 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000731 return true;
732}
733
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000734static uint64_t getMipsPageAddr(uint64_t Addr) {
735 return (Addr + 0x8000) & ~0xffff;
736}
737
738static uint64_t getMipsPageCount(uint64_t Size) {
739 return (Size + 0xfffe) / 0xffff + 1;
740}
741
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000742uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
George Rimar14534eb2017-03-20 16:44:28 +0000743 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000744 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000745 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
746 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
747 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000748 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000749 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000750}
751
Rui Ueyama48882242017-11-04 00:31:04 +0000752uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
753 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000754 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000755 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000756 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000757 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000758 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000759 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000760 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000761 Index += LocalEntries.size();
762 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000763 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000764 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000765 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000766 auto It = EntryIndexMap.find({&B, Addend});
767 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000768 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000769 }
George Rimar14534eb2017-03-20 16:44:28 +0000770 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000771}
772
George Rimar14534eb2017-03-20 16:44:28 +0000773uint64_t MipsGotSection::getTlsOffset() const {
774 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000775}
776
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000777uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
George Rimar14534eb2017-03-20 16:44:28 +0000778 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000779}
780
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000781const Symbol *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000782 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783}
784
George Rimar14534eb2017-03-20 16:44:28 +0000785unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000786 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
787 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000788}
789
George Rimar67c60722017-07-18 11:55:35 +0000790void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000791
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000792bool MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000794 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000795 // For each output section referenced by GOT page relocations calculate
796 // and save into PageIndexMap an upper bound of MIPS GOT entries required
797 // to store page addresses of local symbols. We assume the worst case -
798 // each 64kb page of the output section has at least one GOT relocation
799 // against it. And take in account the case when the section intersects
800 // page boundaries.
801 P.second = PageEntriesNum;
802 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000803 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000804 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000805 Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000806 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000807}
808
George Rimar14534eb2017-03-20 16:44:28 +0000809bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000810 // We add the .got section to the result for dynamic MIPS target because
811 // its address and properties are mentioned in the .dynamic section.
812 return Config->Relocatable;
813}
814
George Rimar67c60722017-07-18 11:55:35 +0000815uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000816
George Rimar14534eb2017-03-20 16:44:28 +0000817void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000818 // Set the MSB of the second GOT slot. This is not required by any
819 // MIPS ABI documentation, though.
820 //
821 // There is a comment in glibc saying that "The MSB of got[1] of a
822 // gnu object is set to identify gnu objects," and in GNU gold it
823 // says "the second entry will be used by some runtime loaders".
824 // But how this field is being used is unclear.
825 //
826 // We are not really willing to mimic other linkers behaviors
827 // without understanding why they do that, but because all files
828 // generated by GNU tools have this special GOT value, and because
829 // we've been doing this for years, it is probably a safe bet to
830 // keep doing this for now. We really need to revisit this to see
831 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000832 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
833 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000834 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000835 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000836 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000837 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000838 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000839 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
840 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000841 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000842 }
George Rimar14534eb2017-03-20 16:44:28 +0000843 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000844 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000845 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000846 Buf += Config->Wordsize;
Rui Ueyama48882242017-11-04 00:31:04 +0000847 const Symbol *Sym = SA.first;
848 uint64_t VA = Sym->getVA(SA.second);
Simon Atanasyan5a4e2132017-11-08 23:34:34 +0000849 if (Sym->StOther & STO_MIPS_MICROMIPS)
850 VA |= 1;
George Rimar14534eb2017-03-20 16:44:28 +0000851 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000852 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000853 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
854 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
855 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000856 // Initialize TLS-related GOT entries. If the entry has a corresponding
857 // dynamic relocations, leave it initialized by zero. Write down adjusted
858 // TLS symbol's values otherwise. To calculate the adjustments use offsets
859 // for thread-local storage.
860 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000861 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000862 writeUint(Buf + TlsIndexOff, 1);
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000863 for (const Symbol *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000864 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000865 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000866 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000867 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000868 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
869 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000870 }
871 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000872 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
873 writeUint(Entry, 1);
874 Entry += Config->Wordsize;
875 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000876 }
877 }
878}
879
George Rimar10f74fc2017-03-15 09:12:56 +0000880GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000881 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
882 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000883
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000884void GotPltSection::addEntry(Symbol &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000885 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
886 Entries.push_back(&Sym);
887}
888
George Rimar10f74fc2017-03-15 09:12:56 +0000889size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000890 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
891 Target->GotPltEntrySize;
892}
893
George Rimar10f74fc2017-03-15 09:12:56 +0000894void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000895 Target->writeGotPltHeader(Buf);
896 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000897 for (const Symbol *B : Entries) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000898 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000899 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000900 }
901}
902
Peter Smithbaffdb82016-12-08 12:58:55 +0000903// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
904// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000905IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000906 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
907 Target->GotPltEntrySize,
908 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000909
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000910void IgotPltSection::addEntry(Symbol &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000911 Sym.IsInIgot = true;
912 Sym.GotPltIndex = Entries.size();
913 Entries.push_back(&Sym);
914}
915
George Rimar10f74fc2017-03-15 09:12:56 +0000916size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000917 return Entries.size() * Target->GotPltEntrySize;
918}
919
George Rimar10f74fc2017-03-15 09:12:56 +0000920void IgotPltSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000921 for (const Symbol *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000922 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000923 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000924 }
925}
926
George Rimar49648002017-03-15 09:32:36 +0000927StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
928 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000929 Dynamic(Dynamic) {
930 // ELF string tables start with a NUL byte.
931 addString("");
932}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000933
934// Adds a string to the string table. If HashIt is true we hash and check for
935// duplicates. It is optional because the name of global symbols are already
936// uniqued and hashing them again has a big cost for a small value: uniquing
937// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000938unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000939 if (HashIt) {
940 auto R = StringMap.insert(std::make_pair(S, this->Size));
941 if (!R.second)
942 return R.first->second;
943 }
944 unsigned Ret = this->Size;
945 this->Size = this->Size + S.size() + 1;
946 Strings.push_back(S);
947 return Ret;
948}
949
George Rimar49648002017-03-15 09:32:36 +0000950void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000951 for (StringRef S : Strings) {
952 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000953 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000954 Buf += S.size() + 1;
955 }
956}
957
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000958// Returns the number of version definition entries. Because the first entry
959// is for the version definition itself, it is the number of versioned symbols
960// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000961static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
962
963template <class ELFT>
964DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000965 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +0000966 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000967 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +0000968
Petr Hosekffa786f2017-05-26 19:12:38 +0000969 // .dynamic section is not writable on MIPS and on Fuchsia OS
970 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000971 // See "Special Section" in Chapter 4 in the following document:
972 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +0000973 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +0000974 this->Flags = SHF_ALLOC;
975
Rui Ueyama22e55512017-12-15 19:39:59 +0000976 // Add strings to .dynstr early so that .dynstr's size will be
977 // fixed early.
978 for (StringRef S : Config->FilterList)
979 addInt(DT_FILTER, InX::DynStrTab->addString(S));
980 for (StringRef S : Config->AuxiliaryList)
981 addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
983 if (!Config->Rpath.empty())
984 addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
985 InX::DynStrTab->addString(Config->Rpath));
986
987 for (InputFile *File : SharedFiles) {
988 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989 if (F->IsNeeded)
990 addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991 }
992 if (!Config->SoName.empty())
993 addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
Eugene Leviant6380ce22016-11-15 12:26:55 +0000994}
995
Rui Ueyama15475e92017-11-24 02:15:51 +0000996template <class ELFT>
997void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
998 Entries.push_back({Tag, Fn});
999}
1000
1001template <class ELFT>
1002void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003 Entries.push_back({Tag, [=] { return Val; }});
1004}
1005
1006template <class ELFT>
1007void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008 Entries.push_back(
1009 {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010}
1011
1012template <class ELFT>
1013void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1014 Entries.push_back({Tag, [=] { return Sec->Addr; }});
1015}
1016
1017template <class ELFT>
1018void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019 Entries.push_back({Tag, [=] { return Sec->Size; }});
1020}
1021
1022template <class ELFT>
1023void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1024 Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1025}
1026
Rui Ueyama22e55512017-12-15 19:39:59 +00001027// Add remaining entries to complete .dynamic contents.
1028template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029 if (this->Size)
1030 return; // Already finalized.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001031
1032 // Set DT_FLAGS and DT_FLAGS_1.
1033 uint32_t DtFlags = 0;
1034 uint32_t DtFlags1 = 0;
1035 if (Config->Bsymbolic)
1036 DtFlags |= DF_SYMBOLIC;
1037 if (Config->ZNodelete)
1038 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001039 if (Config->ZNodlopen)
1040 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001041 if (Config->ZNow) {
1042 DtFlags |= DF_BIND_NOW;
1043 DtFlags1 |= DF_1_NOW;
1044 }
1045 if (Config->ZOrigin) {
1046 DtFlags |= DF_ORIGIN;
1047 DtFlags1 |= DF_1_ORIGIN;
1048 }
1049
1050 if (DtFlags)
Rui Ueyama15475e92017-11-24 02:15:51 +00001051 addInt(DT_FLAGS, DtFlags);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001052 if (DtFlags1)
Rui Ueyama15475e92017-11-24 02:15:51 +00001053 addInt(DT_FLAGS_1, DtFlags1);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001054
Petr Hosekffa786f2017-05-26 19:12:38 +00001055 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056 // need it for each process, so we don't write it for DSOs. The loader writes
1057 // the pointer into this entry.
1058 //
1059 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060 // systems (currently only Fuchsia OS) provide other means to give the
1061 // debugger this information. Such systems may choose make .dynamic read-only.
1062 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
Rui Ueyama15475e92017-11-24 02:15:51 +00001064 addInt(DT_DEBUG, 0);
George Rimarb4081bb2017-05-12 08:04:58 +00001065
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001066 this->Link = InX::DynStrTab->getParent()->SectionIndex;
George Rimar32085882017-12-30 08:40:45 +00001067 if (!InX::RelaDyn->empty()) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001068 addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069 addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001070
1071 bool IsRela = Config->IsRela;
Rui Ueyama15475e92017-11-24 02:15:51 +00001072 addInt(IsRela ? DT_RELAENT : DT_RELENT,
1073 IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
Eugene Leviant6380ce22016-11-15 12:26:55 +00001074
1075 // MIPS dynamic loader does not support RELCOUNT tag.
1076 // The problem is in the tight relation between dynamic
1077 // relocations and GOT. So do not emit this tag on MIPS.
1078 if (Config->EMachine != EM_MIPS) {
Rafael Espindola58946cd2017-12-10 19:44:42 +00001079 size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001080 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama15475e92017-11-24 02:15:51 +00001081 addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001082 }
1083 }
George Rimaredb61162017-12-31 07:42:54 +00001084 // .rel[a].plt section usually consists of two parts, containing plt and
1085 // iplt relocations. It is possible to have only iplt relocations in the
1086 // output. In that case RelaPlt is empty and have zero offset, the same offset
1087 // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088 // case, so here we always use RelaPlt as marker for the begining of
1089 // .rel[a].plt section.
1090 if (InX::RelaPlt->getParent()->Live) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001091 addInSec(DT_JMPREL, InX::RelaPlt);
1092 addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
Rui Ueyama0cc14832017-06-28 17:05:39 +00001093 switch (Config->EMachine) {
1094 case EM_MIPS:
Rui Ueyama15475e92017-11-24 02:15:51 +00001095 addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001096 break;
1097 case EM_SPARCV9:
Rui Ueyama15475e92017-11-24 02:15:51 +00001098 addInSec(DT_PLTGOT, InX::Plt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001099 break;
1100 default:
Rui Ueyama15475e92017-11-24 02:15:51 +00001101 addInSec(DT_PLTGOT, InX::GotPlt);
Rui Ueyama0cc14832017-06-28 17:05:39 +00001102 break;
1103 }
Rui Ueyama15475e92017-11-24 02:15:51 +00001104 addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001105 }
1106
Rui Ueyama15475e92017-11-24 02:15:51 +00001107 addInSec(DT_SYMTAB, InX::DynSymTab);
1108 addInt(DT_SYMENT, sizeof(Elf_Sym));
1109 addInSec(DT_STRTAB, InX::DynStrTab);
1110 addInt(DT_STRSZ, InX::DynStrTab->getSize());
George Rimar0a7412f2017-03-09 08:48:34 +00001111 if (!Config->ZText)
Rui Ueyama15475e92017-11-24 02:15:51 +00001112 addInt(DT_TEXTREL, 0);
George Rimar69b17c32017-05-16 10:04:42 +00001113 if (InX::GnuHashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001114 addInSec(DT_GNU_HASH, InX::GnuHashTab);
George Rimaraaf54712017-09-27 09:14:59 +00001115 if (InX::HashTab)
Rui Ueyama15475e92017-11-24 02:15:51 +00001116 addInSec(DT_HASH, InX::HashTab);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001117
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001118 if (Out::PreinitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001119 addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120 addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001121 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001122 if (Out::InitArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001123 addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124 addSize(DT_INIT_ARRAYSZ, Out::InitArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001125 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001126 if (Out::FiniArray) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001127 addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128 addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001129 }
1130
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001131 if (Symbol *B = Symtab->find(Config->Init))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001132 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001133 addSym(DT_INIT, B);
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001134 if (Symbol *B = Symtab->find(Config->Fini))
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001135 if (B->isDefined())
Rui Ueyama15475e92017-11-24 02:15:51 +00001136 addSym(DT_FINI, B);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001137
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001138 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139 if (HasVerNeed || In<ELFT>::VerDef)
Rui Ueyama15475e92017-11-24 02:15:51 +00001140 addInSec(DT_VERSYM, In<ELFT>::VerSym);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001141 if (In<ELFT>::VerDef) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001142 addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143 addInt(DT_VERDEFNUM, getVerDefNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001144 }
1145 if (HasVerNeed) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001146 addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147 addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
Eugene Leviant6380ce22016-11-15 12:26:55 +00001148 }
1149
1150 if (Config->EMachine == EM_MIPS) {
Rui Ueyama15475e92017-11-24 02:15:51 +00001151 addInt(DT_MIPS_RLD_VERSION, 1);
1152 addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153 addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154 addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
James Hendersonf70c5be2017-11-22 12:04:21 +00001155
Rui Ueyama15475e92017-11-24 02:15:51 +00001156 add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
James Hendersonf70c5be2017-11-22 12:04:21 +00001157
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001158 if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama15475e92017-11-24 02:15:51 +00001159 addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001160 else
Rui Ueyama15475e92017-11-24 02:15:51 +00001161 addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162 addInSec(DT_PLTGOT, InX::MipsGot);
Rafael Espindola895aea62017-05-11 22:02:41 +00001163 if (InX::MipsRldMap)
Rui Ueyama15475e92017-11-24 02:15:51 +00001164 addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001165 }
1166
Rui Ueyama15475e92017-11-24 02:15:51 +00001167 addInt(DT_NULL, 0);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001168
George Rimar8f3a6c82017-10-06 10:06:13 +00001169 getParent()->Link = this->Link;
1170 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001171}
1172
1173template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
Rui Ueyama15475e92017-11-24 02:15:51 +00001176 for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177 P->d_tag = KV.first;
1178 P->d_un.d_val = KV.second();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001179 ++P;
1180 }
1181}
1182
George Rimar97def8c2017-03-17 12:07:44 +00001183uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001184 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001185}
1186
George Rimar97def8c2017-03-17 12:07:44 +00001187int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001188 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001189 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001190 return Addend;
1191}
1192
George Rimar97def8c2017-03-17 12:07:44 +00001193uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001194 if (Sym && !UseSymVA)
1195 return Sym->DynsymIndex;
1196 return 0;
1197}
1198
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001199RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1200 int32_t DynamicTag,
1201 int32_t SizeDynamicTag)
1202 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1203 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001204
Rafael Espindola73584cb2018-01-05 20:08:38 +00001205void RelocationBaseSection::addReloc(uint32_t DynType,
1206 InputSectionBase *InputSec,
1207 uint64_t OffsetInSec, bool UseSymVA,
1208 Symbol *Sym, int64_t Addend, RelExpr Expr,
1209 RelType Type) {
1210 // REL type relocations don't have addend fields unlike RELAs, and
1211 // their addends are stored to the section to which they are applied.
1212 // So, store addends if we need to.
1213 if (!Config->IsRela && UseSymVA)
1214 InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
1215 addReloc({DynType, InputSec, OffsetInSec, UseSymVA, Sym, Addend});
1216}
1217
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001218void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001219 if (Reloc.Type == Target->RelativeRel)
1220 ++NumRelativeRelocs;
1221 Relocs.push_back(Reloc);
1222}
1223
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001224void RelocationBaseSection::finalizeContents() {
1225 // If all relocations are R_*_RELATIVE they don't refer to any
1226 // dynamic symbol and we don't need a dynamic symbol table. If that
1227 // is the case, just use 0 as the link.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001228 Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001229
1230 // Set required output section properties.
Rafael Espindola6d907105c2017-12-10 19:28:32 +00001231 getParent()->Link = Link;
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001232}
1233
1234template <class ELFT>
1235static void encodeDynamicReloc(typename ELFT::Rela *P,
1236 const DynamicReloc &Rel) {
1237 if (Config->IsRela)
1238 P->r_addend = Rel.getAddend();
1239 P->r_offset = Rel.getOffset();
1240 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1241 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242 // entries. These entries are placed after the global and local sections of
1243 // the GOT. At the point when we create these relocations, the size of the
1244 // global and local sections is unknown, so the offset that we store in the
1245 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246 // the GOT, rather than being relative to the start of the GOT. This line of
1247 // code adds the size of the global and local sections to the virtual
1248 // address computed by getOffset() in order to adjust it into the TLS
1249 // section.
1250 P->r_offset += InX::MipsGot->getTlsOffset();
1251 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252}
1253
1254template <class ELFT>
1255RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1256 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1257 Config->IsRela ? DT_RELA : DT_REL,
1258 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1259 Sort(Sort) {
1260 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1261}
1262
Eugene Levianta96d9022016-11-16 10:02:27 +00001263template <class ELFT, class RelTy>
1264static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001265 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001267 if (AIsRel != BIsRel)
1268 return AIsRel;
1269
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001270 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001271}
1272
1273template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001275 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001276 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001277 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001278 }
1279
1280 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001281 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001282 std::stable_sort((Elf_Rela *)BufBegin,
1283 (Elf_Rela *)BufBegin + Relocs.size(),
1284 compRelocations<ELFT, Elf_Rela>);
1285 else
1286 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287 compRelocations<ELFT, Elf_Rel>);
1288 }
1289}
1290
1291template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292 return this->Entsize * Relocs.size();
1293}
1294
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001295template <class ELFT>
1296AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1297 StringRef Name)
1298 : RelocationBaseSection(
1299 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1300 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1301 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1302 this->Entsize = 1;
1303}
Eugene Levianta96d9022016-11-16 10:02:27 +00001304
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001305template <class ELFT>
1306bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1307 // This function computes the contents of an Android-format packed relocation
1308 // section.
1309 //
1310 // This format compresses relocations by using relocation groups to factor out
1311 // fields that are common between relocations and storing deltas from previous
1312 // relocations in SLEB128 format (which has a short representation for small
1313 // numbers). A good example of a relocation type with common fields is
1314 // R_*_RELATIVE, which is normally used to represent function pointers in
1315 // vtables. In the REL format, each relative relocation has the same r_info
1316 // field, and is only different from other relative relocations in terms of
1317 // the r_offset field. By sorting relocations by offset, grouping them by
1318 // r_info and representing each relocation with only the delta from the
1319 // previous offset, each 8-byte relocation can be compressed to as little as 1
1320 // byte (or less with run-length encoding). This relocation packer was able to
1321 // reduce the size of the relocation section in an Android Chromium DSO from
1322 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1323 //
1324 // A relocation section consists of a header containing the literal bytes
1325 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1326 // elements are the total number of relocations in the section and an initial
1327 // r_offset value. The remaining elements define a sequence of relocation
1328 // groups. Each relocation group starts with a header consisting of the
1329 // following elements:
1330 //
1331 // - the number of relocations in the relocation group
1332 // - flags for the relocation group
1333 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1334 // for each relocation in the group.
1335 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1336 // field for each relocation in the group.
1337 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1338 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1339 // each relocation in the group.
1340 //
1341 // Following the relocation group header are descriptions of each of the
1342 // relocations in the group. They consist of the following elements:
1343 //
1344 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1345 // delta for this relocation.
1346 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1347 // field for this relocation.
1348 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1349 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1350 // this relocation.
1351
1352 size_t OldSize = RelocData.size();
1353
1354 RelocData = {'A', 'P', 'S', '2'};
1355 raw_svector_ostream OS(RelocData);
Rui Ueyama04c821c2017-12-08 02:20:50 +00001356 auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001357
1358 // The format header includes the number of relocations and the initial
1359 // offset (we set this to zero because the first relocation group will
1360 // perform the initial adjustment).
Rui Ueyama04c821c2017-12-08 02:20:50 +00001361 Add(Relocs.size());
1362 Add(0);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001363
1364 std::vector<Elf_Rela> Relatives, NonRelatives;
1365
1366 for (const DynamicReloc &Rel : Relocs) {
1367 Elf_Rela R;
1368 encodeDynamicReloc<ELFT>(&R, Rel);
1369
1370 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1371 Relatives.push_back(R);
1372 else
1373 NonRelatives.push_back(R);
1374 }
1375
1376 std::sort(Relatives.begin(), Relatives.end(),
1377 [](const Elf_Rel &A, const Elf_Rel &B) {
1378 return A.r_offset < B.r_offset;
1379 });
1380
1381 // Try to find groups of relative relocations which are spaced one word
1382 // apart from one another. These generally correspond to vtable entries. The
1383 // format allows these groups to be encoded using a sort of run-length
1384 // encoding, but each group will cost 7 bytes in addition to the offset from
1385 // the previous group, so it is only profitable to do this for groups of
1386 // size 8 or larger.
1387 std::vector<Elf_Rela> UngroupedRelatives;
1388 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1389 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1390 std::vector<Elf_Rela> Group;
1391 do {
1392 Group.push_back(*I++);
1393 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1394
1395 if (Group.size() < 8)
1396 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1397 Group.end());
1398 else
1399 RelativeGroups.emplace_back(std::move(Group));
1400 }
1401
1402 unsigned HasAddendIfRela =
1403 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1404
1405 uint64_t Offset = 0;
1406 uint64_t Addend = 0;
1407
1408 // Emit the run-length encoding for the groups of adjacent relative
1409 // relocations. Each group is represented using two groups in the packed
1410 // format. The first is used to set the current offset to the start of the
1411 // group (and also encodes the first relocation), and the second encodes the
1412 // remaining relocations.
1413 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1414 // The first relocation in the group.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001415 Add(1);
1416 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1417 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1418 Add(G[0].r_offset - Offset);
1419 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001420 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001421 Add(G[0].r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001422 Addend = G[0].r_addend;
1423 }
1424
1425 // The remaining relocations.
Rui Ueyama04c821c2017-12-08 02:20:50 +00001426 Add(G.size() - 1);
1427 Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1428 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1429 Add(Config->Wordsize);
1430 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001431 if (Config->IsRela) {
1432 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001433 Add(I->r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001434 Addend = I->r_addend;
1435 }
1436 }
1437
1438 Offset = G.back().r_offset;
1439 }
1440
1441 // Now the ungrouped relatives.
1442 if (!UngroupedRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001443 Add(UngroupedRelatives.size());
1444 Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1445 Add(Target->RelativeRel);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001446 for (Elf_Rela &R : UngroupedRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001447 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001448 Offset = R.r_offset;
1449 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001450 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001451 Addend = R.r_addend;
1452 }
1453 }
1454 }
1455
1456 // Finally the non-relative relocations.
1457 std::sort(NonRelatives.begin(), NonRelatives.end(),
1458 [](const Elf_Rela &A, const Elf_Rela &B) {
1459 return A.r_offset < B.r_offset;
1460 });
1461 if (!NonRelatives.empty()) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001462 Add(NonRelatives.size());
1463 Add(HasAddendIfRela);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001464 for (Elf_Rela &R : NonRelatives) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001465 Add(R.r_offset - Offset);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001466 Offset = R.r_offset;
Rui Ueyama04c821c2017-12-08 02:20:50 +00001467 Add(R.r_info);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001468 if (Config->IsRela) {
Rui Ueyama04c821c2017-12-08 02:20:50 +00001469 Add(R.r_addend - Addend);
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001470 Addend = R.r_addend;
1471 }
1472 }
1473 }
1474
1475 // Returns whether the section size changed. We need to keep recomputing both
1476 // section layout and the contents of this section until the size converges
1477 // because changing this section's size can affect section layout, which in
1478 // turn can affect the sizes of the LEB-encoded integers stored in this
1479 // section.
1480 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001481}
1482
George Rimarf45f6812017-05-16 08:53:30 +00001483SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001484 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001485 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001486 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001487 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001488 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001489
1490// Orders symbols according to their positions in the GOT,
1491// in compliance with MIPS ABI rules.
1492// See "Global Offset Table" in Chapter 5 in the following document
1493// for detailed description:
1494// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001495static bool sortMipsSymbols(const SymbolTableEntry &L,
1496 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001497 // Sort entries related to non-local preemptible symbols by GOT indexes.
1498 // All other entries go to the first part of GOT in arbitrary order.
Zachary Turnera104d552017-11-03 22:33:49 +00001499 bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1500 bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001501 if (LIsInLocalGot || RIsInLocalGot)
1502 return !RIsInLocalGot;
Zachary Turnera104d552017-11-03 22:33:49 +00001503 return L.Sym->GotIndex < R.Sym->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001504}
1505
George Rimarf45f6812017-05-16 08:53:30 +00001506void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001507 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001508
Rui Ueyama6e967342017-02-28 03:29:12 +00001509 // If it is a .dynsym, there should be no local symbols, but we need
1510 // to do a few things for the dynamic linker.
1511 if (this->Type == SHT_DYNSYM) {
1512 // Section's Info field has the index of the first non-local symbol.
1513 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001514 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001515
George Rimarf45f6812017-05-16 08:53:30 +00001516 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001517 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001518 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001519 } else if (Config->EMachine == EM_MIPS) {
1520 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1521 }
1522
1523 size_t I = 0;
Zachary Turnera104d552017-11-03 22:33:49 +00001524 for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001525 return;
Peter Smith55865432017-02-20 11:12:33 +00001526 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001527}
Peter Smith55865432017-02-20 11:12:33 +00001528
George Rimar0d6f30e2017-10-18 13:06:18 +00001529// The ELF spec requires that all local symbols precede global symbols, so we
1530// sort symbol entries in this function. (For .dynsym, we don't do that because
1531// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001532void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001533 if (this->Type == SHT_DYNSYM)
1534 return;
1535 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001536 auto It = std::stable_partition(
1537 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
Zachary Turnera104d552017-11-03 22:33:49 +00001538 return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL;
Rui Ueyama6e967342017-02-28 03:29:12 +00001539 });
1540 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001541 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001542}
1543
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001544void SymbolTableBaseSection::addSymbol(Symbol *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001545 // Adding a local symbol to a .dynsym is a bug.
1546 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001547
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001548 bool HashIt = B->isLocal();
1549 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001550}
1551
Rui Ueyama48882242017-11-04 00:31:04 +00001552size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
George Rimar5d6efd12017-09-27 09:08:53 +00001553 // Initializes symbol lookup tables lazily. This is used only
1554 // for -r or -emit-relocs.
1555 llvm::call_once(OnceFlag, [&] {
1556 SymbolIndexMap.reserve(Symbols.size());
1557 size_t I = 0;
1558 for (const SymbolTableEntry &E : Symbols) {
Zachary Turnera104d552017-11-03 22:33:49 +00001559 if (E.Sym->Type == STT_SECTION)
1560 SectionIndexMap[E.Sym->getOutputSection()] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001561 else
Zachary Turnera104d552017-11-03 22:33:49 +00001562 SymbolIndexMap[E.Sym] = ++I;
George Rimar5d6efd12017-09-27 09:08:53 +00001563 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001564 });
George Rimar5d6efd12017-09-27 09:08:53 +00001565
1566 // Section symbols are mapped based on their output sections
1567 // to maintain their semantics.
Rui Ueyama48882242017-11-04 00:31:04 +00001568 if (Sym->Type == STT_SECTION)
1569 return SectionIndexMap.lookup(Sym->getOutputSection());
1570 return SymbolIndexMap.lookup(Sym);
George Rimar190bac52017-01-23 14:07:23 +00001571}
1572
George Rimarf45f6812017-05-16 08:53:30 +00001573template <class ELFT>
1574SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1575 : SymbolTableBaseSection(StrTabSec) {
1576 this->Entsize = sizeof(Elf_Sym);
1577}
1578
Rui Ueyama1f032532017-02-28 01:56:36 +00001579// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001580template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001581 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001582 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001583 Buf += sizeof(Elf_Sym);
1584
Eugene Leviant9230db92016-11-17 09:16:34 +00001585 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001586
Rui Ueyama1f032532017-02-28 01:56:36 +00001587 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001588 Symbol *Sym = Ent.Sym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001589
Rui Ueyama1b003182017-02-28 19:22:09 +00001590 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001591 ESym->st_other = 0;
Rui Ueyama48882242017-11-04 00:31:04 +00001592 if (Sym->isLocal()) {
1593 ESym->setBindingAndType(STB_LOCAL, Sym->Type);
Rui Ueyama1f032532017-02-28 01:56:36 +00001594 } else {
Rui Ueyama48882242017-11-04 00:31:04 +00001595 ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596 ESym->setVisibility(Sym->Visibility);
Rui Ueyama1f032532017-02-28 01:56:36 +00001597 }
1598
1599 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001600
Rui Ueyama1b003182017-02-28 19:22:09 +00001601 // Set a section index.
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001602 BssSection *CommonSec = nullptr;
1603 if (!Config->DefineCommon)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001604 if (auto *D = dyn_cast<Defined>(Sym))
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001605 CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606 if (CommonSec)
1607 ESym->st_shndx = SHN_COMMON;
1608 else if (const OutputSection *OutSec = Sym->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001609 ESym->st_shndx = OutSec->SectionIndex;
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001610 else if (isa<Defined>(Sym))
Eugene Leviant9230db92016-11-17 09:16:34 +00001611 ESym->st_shndx = SHN_ABS;
George Rimar2727ce22017-10-06 09:56:24 +00001612 else
1613 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001614
George Rimardbe843d2017-06-28 09:51:33 +00001615 // Copy symbol size if it is a defined symbol. st_size is not significant
1616 // for undefined symbols, so whether copying it or not is up to us if that's
1617 // the case. We'll leave it as zero because by not setting a value, we can
1618 // get the exact same outputs for two sets of input files that differ only
1619 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001620 if (ESym->st_shndx == SHN_UNDEF)
1621 ESym->st_size = 0;
1622 else
Rui Ueyama48882242017-11-04 00:31:04 +00001623 ESym->st_size = Sym->getSize();
George Rimardbe843d2017-06-28 09:51:33 +00001624
Rui Ueyama1b003182017-02-28 19:22:09 +00001625 // st_value is usually an address of a symbol, but that has a
1626 // special meaining for uninstantiated common symbols (this can
1627 // occur if -r is given).
Peter Collingbourne6c55a702017-11-06 04:33:58 +00001628 if (CommonSec)
1629 ESym->st_value = CommonSec->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001630 else
Rui Ueyama48882242017-11-04 00:31:04 +00001631 ESym->st_value = Sym->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001632
Rui Ueyama1f032532017-02-28 01:56:36 +00001633 ++ESym;
1634 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001635
Rui Ueyama1f032532017-02-28 01:56:36 +00001636 // On MIPS we need to mark symbol which has a PLT entry and requires
1637 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640 if (Config->EMachine == EM_MIPS) {
1641 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
1643 for (SymbolTableEntry &Ent : Symbols) {
Rui Ueyama48882242017-11-04 00:31:04 +00001644 Symbol *Sym = Ent.Sym;
1645 if (Sym->isInPlt() && Sym->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001646 ESym->st_other |= STO_MIPS_PLT;
Simon Atanasyancfa8aa7e2017-11-13 22:40:36 +00001647 if (isMicroMips()) {
1648 // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649 // defined microMIPS symbols and shared symbols with PLT record.
1650 if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1651 (Sym->isShared() && Sym->NeedsPltAddr)) {
1652 if (StrTabSec.isDynamic())
1653 ESym->st_value |= 1;
1654 ESym->st_other |= STO_MIPS_MICROMIPS;
1655 }
1656 }
Rui Ueyama1f032532017-02-28 01:56:36 +00001657 if (Config->Relocatable)
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +00001658 if (auto *D = dyn_cast<Defined>(Sym))
Rui Ueyama7957b082017-11-07 00:04:22 +00001659 if (isMipsPIC<ELFT>(D))
Rui Ueyama1f032532017-02-28 01:56:36 +00001660 ESym->st_other |= STO_MIPS_PIC;
1661 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001662 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001663 }
1664}
1665
Rui Ueyamae4120632017-02-28 22:05:13 +00001666// .hash and .gnu.hash sections contain on-disk hash tables that map
1667// symbol names to their dynamic symbol table indices. Their purpose
1668// is to help the dynamic linker resolve symbols quickly. If ELF files
1669// don't have them, the dynamic linker has to do linear search on all
1670// dynamic symbols, which makes programs slower. Therefore, a .hash
1671// section is added to a DSO by default. A .gnu.hash is added if you
1672// give the -hash-style=gnu or -hash-style=both option.
1673//
1674// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1675// Each ELF file has a list of DSOs that the ELF file depends on and a
1676// list of dynamic symbols that need to be resolved from any of the
1677// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1678// where m is the number of DSOs and n is the number of dynamic
1679// symbols. For modern large programs, both m and n are large. So
1680// making each step faster by using hash tables substiantially
1681// improves time to load programs.
1682//
1683// (Note that this is not the only way to design the shared library.
1684// For instance, the Windows DLL takes a different approach. On
1685// Windows, each dynamic symbol has a name of DLL from which the symbol
1686// has to be resolved. That makes the cost of symbol resolution O(n).
1687// This disables some hacky techniques you can use on Unix such as
1688// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1689//
1690// Due to historical reasons, we have two different hash tables, .hash
1691// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1692// and better version of .hash. .hash is just an on-disk hash table, but
1693// .gnu.hash has a bloom filter in addition to a hash table to skip
1694// DSOs very quickly. If you are sure that your dynamic linker knows
1695// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1696// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001697GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001698 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1699}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001700
George Rimarf45f6812017-05-16 08:53:30 +00001701void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001702 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001703
1704 // Computes bloom filter size in word size. We want to allocate 8
1705 // bits for each symbol. It must be a power of two.
1706 if (Symbols.empty())
1707 MaskWords = 1;
1708 else
George Rimar5f73bc92017-03-29 15:23:28 +00001709 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001710
George Rimar5f73bc92017-03-29 15:23:28 +00001711 Size = 16; // Header
1712 Size += Config->Wordsize * MaskWords; // Bloom filter
1713 Size += NBuckets * 4; // Hash buckets
1714 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001715}
1716
George Rimarf45f6812017-05-16 08:53:30 +00001717void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamac4e50bf2017-12-06 00:49:48 +00001718 // The output buffer is not guaranteed to be zero-cleared because we pre-
1719 // fill executable sections with trap instructions. This is a precaution
1720 // for that case, which happens only when -no-rosegment is given.
1721 memset(Buf, 0, Size);
1722
Rui Ueyamae13373b2017-03-01 02:51:42 +00001723 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001724 write32(Buf, NBuckets);
1725 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1726 write32(Buf + 8, MaskWords);
1727 write32(Buf + 12, getShift2());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001728 Buf += 16;
1729
Rui Ueyama7986b452017-03-01 18:09:09 +00001730 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001731 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001732 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001733 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001734}
1735
Rui Ueyama7986b452017-03-01 18:09:09 +00001736// This function writes a 2-bit bloom filter. This bloom filter alone
1737// usually filters out 80% or more of all symbol lookups [1].
1738// The dynamic linker uses the hash table only when a symbol is not
1739// filtered out by a bloom filter.
1740//
1741// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1742// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001743void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001744 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001745 for (const Entry &Sym : Symbols) {
1746 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001747 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1748 Val |= uint64_t(1) << (Sym.Hash % C);
1749 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1750 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001751 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001752}
1753
George Rimarf45f6812017-05-16 08:53:30 +00001754void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001755 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rafael Espindolaf9f2abe2017-12-07 18:51:19 +00001756 uint32_t OldBucket = -1;
George Rimar5f73bc92017-03-29 15:23:28 +00001757 uint32_t *Values = Buckets + NBuckets;
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001758 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001759 // Write a hash value. It represents a sequence of chains that share the
1760 // same hash modulo value. The last element of each chain is terminated by
1761 // LSB 1.
Rafael Espindola50ca10b2017-12-07 18:46:03 +00001762 uint32_t Hash = I->Hash;
1763 bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx;
1764 Hash = IsLastInChain ? Hash | 1 : Hash & ~1;
1765 write32(Values++, Hash);
Rafael Espindolad182aaa2017-12-07 18:59:29 +00001766
1767 if (I->BucketIdx == OldBucket)
1768 continue;
1769 // Write a hash bucket. Hash buckets contain indices in the following hash
1770 // value table.
1771 write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1772 OldBucket = I->BucketIdx;
Eugene Leviantbe809a72016-11-18 06:44:18 +00001773 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001774}
1775
1776static uint32_t hashGnu(StringRef Name) {
1777 uint32_t H = 5381;
1778 for (uint8_t C : Name)
1779 H = (H << 5) + H + C;
1780 return H;
1781}
1782
1783// Add symbols to this symbol hash table. Note that this function
1784// destructively sort a given vector -- which is needed because
1785// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001786void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001787 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1788 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001789 std::vector<SymbolTableEntry>::iterator Mid =
1790 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001791 // Shared symbols that this executable preempts are special. The dynamic
1792 // linker has to look them up, so they have to be in the hash table.
Zachary Turnera104d552017-11-03 22:33:49 +00001793 if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001794 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
Peter Collingbourneb472aa02017-11-06 04:39:07 +00001795 return !S.Sym->isDefined();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001796 });
1797 if (Mid == V.end())
1798 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001799
Rui Ueyama1cf7f9c2017-11-30 23:59:40 +00001800 // We chose load factor 4 for the on-disk hash table. For each hash
1801 // collision, the dynamic linker will compare a uint32_t hash value.
1802 // Since the integer comparison is quite fast, we believe we can make
1803 // the load factor even larger. 4 is just a conservative choice.
Rui Ueyama22788262017-12-02 00:37:13 +00001804 NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
Rui Ueyama1cf7f9c2017-11-30 23:59:40 +00001805
Rui Ueyama22788262017-12-02 00:37:13 +00001806 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1807 Symbol *B = Ent.Sym;
1808 uint32_t Hash = hashGnu(B->getName());
1809 uint32_t BucketIdx = Hash % NBuckets;
1810 Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
1811 }
1812
1813 std::stable_sort(
1814 Symbols.begin(), Symbols.end(),
1815 [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
Eugene Leviantbe809a72016-11-18 06:44:18 +00001816
1817 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001818 for (const Entry &Ent : Symbols)
Rui Ueyama48882242017-11-04 00:31:04 +00001819 V.push_back({Ent.Sym, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001820}
1821
George Rimaraaf54712017-09-27 09:14:59 +00001822HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001823 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1824 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001825}
1826
George Rimaraaf54712017-09-27 09:14:59 +00001827void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001828 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001829
George Rimar67c60722017-07-18 11:55:35 +00001830 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001831 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001832
1833 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001834 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001835 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001836}
1837
George Rimaraaf54712017-09-27 09:14:59 +00001838void HashTableSection::writeTo(uint8_t *Buf) {
Shoaib Meenaid79bbf42018-01-11 06:57:01 +00001839 // See comment in GnuHashTableSection::writeTo.
1840 memset(Buf, 0, Size);
1841
George Rimar69b17c32017-05-16 10:04:42 +00001842 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001843
George Rimaraaf54712017-09-27 09:14:59 +00001844 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00001845 write32(P++, NumSymbols); // nbucket
1846 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001847
George Rimaraaf54712017-09-27 09:14:59 +00001848 uint32_t *Buckets = P;
1849 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001850
George Rimar69b17c32017-05-16 10:04:42 +00001851 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Rui Ueyama48882242017-11-04 00:31:04 +00001852 Symbol *Sym = S.Sym;
1853 StringRef Name = Sym->getName();
1854 unsigned I = Sym->DynsymIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001855 uint32_t Hash = hashSysV(Name) % NumSymbols;
1856 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00001857 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001858 }
1859}
1860
George Rimardfc020e2017-03-17 11:01:57 +00001861PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001862 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001863 HeaderSize(S) {
1864 // The PLT needs to be writable on SPARC as the dynamic linker will
1865 // modify the instructions in the PLT entries.
1866 if (Config->EMachine == EM_SPARCV9)
1867 this->Flags |= SHF_WRITE;
1868}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001869
George Rimardfc020e2017-03-17 11:01:57 +00001870void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001871 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1872 // linker to resolve dynsyms at runtime. Write such code.
1873 if (HeaderSize != 0)
1874 Target->writePltHeader(Buf);
1875 size_t Off = HeaderSize;
1876 // The IPlt is immediately after the Plt, account for this in RelOff
1877 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001878
1879 for (auto &I : Entries) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001880 const Symbol *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001881 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001882 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001883 uint64_t Plt = this->getVA() + Off;
1884 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1885 Off += Target->PltEntrySize;
1886 }
1887}
1888
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001889template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001890 Sym.PltIndex = Entries.size();
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001891 RelocationBaseSection *PltRelocSection = InX::RelaPlt;
Peter Smithf09245a2017-02-09 10:56:15 +00001892 if (HeaderSize == 0) {
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001893 PltRelocSection = InX::RelaIplt;
Peter Smithf09245a2017-02-09 10:56:15 +00001894 Sym.IsInIplt = true;
1895 }
Rafael Espindola87e0dea2017-12-10 20:07:03 +00001896 unsigned RelOff =
1897 static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001898 Entries.push_back(std::make_pair(&Sym, RelOff));
1899}
1900
George Rimardfc020e2017-03-17 11:01:57 +00001901size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001902 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001903}
1904
Peter Smith96943762017-01-25 10:31:16 +00001905// Some architectures such as additional symbols in the PLT section. For
1906// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001907void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001908 // The PLT may have symbols defined for the Header, the IPLT has no header
1909 if (HeaderSize != 0)
Rafael Espindola1037eef2017-12-19 23:59:35 +00001910 Target->addPltHeaderSymbols(*this);
Peter Smithf09245a2017-02-09 10:56:15 +00001911 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001912 for (size_t I = 0; I < Entries.size(); ++I) {
Rafael Espindola1037eef2017-12-19 23:59:35 +00001913 Target->addPltSymbols(*this, Off);
Peter Smith96943762017-01-25 10:31:16 +00001914 Off += Target->PltEntrySize;
1915 }
1916}
1917
George Rimardfc020e2017-03-17 11:01:57 +00001918unsigned PltSection::getPltRelocOff() const {
1919 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001920}
1921
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001922// The string hash function for .gdb_index.
1923static uint32_t computeGdbHash(StringRef S) {
1924 uint32_t H = 0;
1925 for (uint8_t C : S)
1926 H = H * 67 + tolower(C) - 113;
1927 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001928}
1929
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001930static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1931 std::vector<GdbIndexChunk::CuEntry> Ret;
1932 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1933 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001934 return Ret;
1935}
1936
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001937static std::vector<GdbIndexChunk::AddressEntry>
1938readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1939 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001940
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001941 uint32_t CuIdx = 0;
1942 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001943 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001944 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001945
George Rimar35e846e2017-03-21 08:19:34 +00001946 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001947 for (DWARFAddressRange &R : Ranges) {
1948 InputSectionBase *S = Sections[R.SectionIndex];
1949 if (!S || S == &InputSection::Discarded || !S->Live)
1950 continue;
1951 // Range list with zero size has no effect.
1952 if (R.LowPC == R.HighPC)
1953 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001954 auto *IS = cast<InputSection>(S);
1955 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001956 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001957 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001958 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001959 }
1960 return Ret;
1961}
1962
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001963static std::vector<GdbIndexChunk::NameTypeEntry>
1964readPubNamesAndTypes(DWARFContext &Dwarf) {
1965 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1966 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001967
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001968 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1969 for (StringRef Sec : {Sec1, Sec2}) {
1970 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001971 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1972 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1973 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1974 Ret.push_back({S, Ent.Descriptor.toBits()});
1975 }
1976 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001977 }
1978 return Ret;
1979}
1980
George Rimar86665622017-06-07 16:59:11 +00001981static std::vector<InputSection *> getDebugInfoSections() {
1982 std::vector<InputSection *> Ret;
1983 for (InputSectionBase *S : InputSections)
1984 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001985 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001986 Ret.push_back(IS);
1987 return Ret;
1988}
1989
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001990void GdbIndexSection::fixCuIndex() {
1991 uint32_t Idx = 0;
1992 for (GdbIndexChunk &Chunk : Chunks) {
1993 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1994 Ent.CuIndex += Idx;
1995 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00001996 }
1997}
1998
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001999std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2000 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002001 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002002 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002003
2004 for (GdbIndexChunk &Chunk : Chunks) {
2005 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002006 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002007 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002008 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2009 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002010 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002011 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002012
2013 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2014 // duplicate entries, so we want to dedup them.
2015 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2016 uint32_t Val = (Ent.Type << 24) | Idx;
2017 if (Vec.empty() || Vec.back() != Val)
2018 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002019 }
2020 Idx += Chunk.CompilationUnits.size();
2021 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002022
2023 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002024 return Ret;
2025}
George Rimar8b547392016-12-15 09:08:13 +00002026
Rafael Espindola300b3862017-07-12 23:56:53 +00002027template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002028 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002029 std::vector<InputSection *> Sections = getDebugInfoSections();
2030 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002031
George Rimar2d23da02017-08-01 14:57:13 +00002032 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002033 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
2036 Chunks[I].DebugInfoSec = Sections[I];
2037 Chunks[I].CompilationUnits = readCuList(Dwarf);
2038 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002040 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002041
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002042 // .debug_gnu_pub{names,types} are useless in executables.
2043 // They are present in input object files solely for creating
2044 // a .gdb_index. So we can remove it from the output.
2045 for (InputSectionBase *S : InputSections)
2046 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2047 S->Live = false;
2048
2049 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002050 return make<GdbIndexSection>(std::move(Chunks));
2051}
2052
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002053static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002054 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002055 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002056 Ret += D.CompilationUnits.size();
2057 return Ret;
2058}
George Rimarec02b8d2016-12-15 12:07:53 +00002059
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002060static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002061 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002062 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002063 Ret += D.AddressAreas.size();
2064 return Ret;
2065}
2066
2067std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002068 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2069 if (Size < 1024)
2070 Size = 1024;
2071
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002072 uint32_t Mask = Size - 1;
2073 std::vector<GdbSymbol *> Ret(Size);
2074
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002075 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002076 GdbSymbol *Sym = KV.second;
2077 uint32_t I = Sym->NameHash & Mask;
2078 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2079
2080 while (Ret[I])
2081 I = (I + Step) & Mask;
2082 Ret[I] = Sym;
2083 }
George Rimar86665622017-06-07 16:59:11 +00002084 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002085}
2086
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002087GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002088 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002089 fixCuIndex();
2090 CuVectors = createCuVectors();
2091 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002092
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002093 // Compute offsets early to know the section size.
2094 // Each chunk size needs to be in sync with what we write in writeTo.
2095 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2096 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2097 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002098
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002099 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002100 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002101 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002102 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002103 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002104 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002105}
2106
George Rimar35e846e2017-03-21 08:19:34 +00002107size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002108 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002109}
2110
George Rimar35e846e2017-03-21 08:19:34 +00002111void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002112 // Write the section header.
2113 write32le(Buf, 7);
2114 write32le(Buf + 4, CuListOffset);
2115 write32le(Buf + 8, CuTypesOffset);
2116 write32le(Buf + 12, CuTypesOffset);
2117 write32le(Buf + 16, SymtabOffset);
2118 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002119 Buf += 24;
2120
2121 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002122 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002123 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002124 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002125 write64le(Buf + 8, Cu.CuLength);
2126 Buf += 16;
2127 }
Eugene Levianta113a412016-11-21 09:24:43 +00002128 }
George Rimar8b547392016-12-15 09:08:13 +00002129
2130 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002131 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002132 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00002133 uint64_t BaseAddr =
2134 E.Section->getParent()->Addr + E.Section->getOffset(0);
2135 write64le(Buf, BaseAddr + E.LowAddress);
2136 write64le(Buf + 8, BaseAddr + E.HighAddress);
2137 write32le(Buf + 16, E.CuIndex);
2138 Buf += 20;
2139 }
George Rimar8b547392016-12-15 09:08:13 +00002140 }
George Rimarec02b8d2016-12-15 12:07:53 +00002141
2142 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002143 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002144 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002145 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2146 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002147 }
2148 Buf += 8;
2149 }
2150
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002151 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002152 for (ArrayRef<uint32_t> Vec : CuVectors) {
2153 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002154 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002155 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002156 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002157 Buf += 4;
2158 }
2159 }
2160
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002161 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002162 for (auto &KV : Symbols) {
2163 CachedHashStringRef S = KV.first;
2164 GdbSymbol *Sym = KV.second;
2165 size_t Off = Sym->NameOffset;
2166 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002167 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002168 }
Eugene Levianta113a412016-11-21 09:24:43 +00002169}
2170
George Rimar67c60722017-07-18 11:55:35 +00002171bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002172
Rui Ueyama02551ab2017-10-27 03:14:24 +00002173EhFrameHeader::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002174 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002175
2176// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2177// Each entry of the search table consists of two values,
2178// the starting PC from where FDEs covers, and the FDE's address.
2179// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002180void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002181 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002182
Rui Ueyama02551ab2017-10-27 03:14:24 +00002183 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002184
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002185 // Sort the FDE list by their PC and uniqueify. Usually there is only
2186 // one FDE for a PC (i.e. function), but if ICF merges two functions
2187 // into one, there can be more than one FDEs pointing to the address.
2188 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2189 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2190 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2191 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2192
2193 Buf[0] = 1;
2194 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2195 Buf[2] = DW_EH_PE_udata4;
2196 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002197 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2198 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002199 Buf += 12;
2200
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002201 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002202 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002203 write32(Buf, Fde.Pc - VA);
2204 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002205 Buf += 8;
2206 }
2207}
2208
Rui Ueyama02551ab2017-10-27 03:14:24 +00002209size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002210 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002211 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002212}
2213
Rui Ueyama02551ab2017-10-27 03:14:24 +00002214bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002215
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002216template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002217VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002218 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2219 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002220
2221static StringRef getFileDefName() {
2222 if (!Config->SoName.empty())
2223 return Config->SoName;
2224 return Config->OutputFile;
2225}
2226
Rui Ueyama945055a2017-02-27 03:07:41 +00002227template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002228 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002229 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002230 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002231
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002232 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002233
2234 // sh_info should be set to the number of definitions. This fact is missed in
2235 // documentation, but confirmed by binutils community:
2236 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002237 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002238}
2239
2240template <class ELFT>
2241void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2242 StringRef Name, size_t NameOff) {
2243 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2244 Verdef->vd_version = 1;
2245 Verdef->vd_cnt = 1;
2246 Verdef->vd_aux = sizeof(Elf_Verdef);
2247 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2248 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2249 Verdef->vd_ndx = Index;
2250 Verdef->vd_hash = hashSysV(Name);
2251
2252 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2253 Verdaux->vda_name = NameOff;
2254 Verdaux->vda_next = 0;
2255}
2256
2257template <class ELFT>
2258void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2259 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2260
2261 for (VersionDefinition &V : Config->VersionDefinitions) {
2262 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2263 writeOne(Buf, V.Id, V.Name, V.NameOff);
2264 }
2265
2266 // Need to terminate the last version definition.
2267 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2268 Verdef->vd_next = 0;
2269}
2270
2271template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2272 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2273}
2274
2275template <class ELFT>
2276VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002277 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002278 ".gnu.version") {
2279 this->Entsize = sizeof(Elf_Versym);
2280}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002281
Rui Ueyama945055a2017-02-27 03:07:41 +00002282template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002283 // At the moment of june 2016 GNU docs does not mention that sh_link field
2284 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002285 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002286}
2287
2288template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002289 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002290}
2291
2292template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2293 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002294 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Zachary Turnera104d552017-11-03 22:33:49 +00002295 OutVersym->vs_index = S.Sym->VersionId;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002296 ++OutVersym;
2297 }
2298}
2299
George Rimar11992c862016-11-25 08:05:41 +00002300template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2301 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2302}
2303
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002304template <class ELFT>
2305VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002306 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2307 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002308 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2309 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2310 // First identifiers are reserved by verdef section if it exist.
2311 NextIndex = getVerDefNum() + 1;
2312}
2313
2314template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002315void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002316 SharedFile<ELFT> &File = SS->getFile<ELFT>();
2317 const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex];
Rui Ueyama4076fa12017-02-26 23:35:34 +00002318 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
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002323 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2324 // to create one by adding it to our needed list and creating a dynstr entry
2325 // for the soname.
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002326 if (File.VerdefMap.empty())
2327 Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)});
2328 typename SharedFile<ELFT>::NeededVer &NV = File.VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002329 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2330 // prepare to create one by allocating a version identifier and creating a
2331 // dynstr entry for the version name.
2332 if (NV.Index == 0) {
Rafael Espindolaa32ddc42017-12-20 16:28:19 +00002333 NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() +
Rafael Espindola895aea62017-05-11 22:02:41 +00002334 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002335 NV.Index = NextIndex++;
2336 }
Rui Ueyamaf1f00842017-10-31 16:07:41 +00002337 SS->VersionId = NV.Index;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002338}
2339
2340template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2341 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2342 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2343 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2344
2345 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2346 // Create an Elf_Verneed for this DSO.
2347 Verneed->vn_version = 1;
2348 Verneed->vn_cnt = P.first->VerdefMap.size();
2349 Verneed->vn_file = P.second;
2350 Verneed->vn_aux =
2351 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2352 Verneed->vn_next = sizeof(Elf_Verneed);
2353 ++Verneed;
2354
2355 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2356 // VerdefMap, which will only contain references to needed version
2357 // definitions. Each Elf_Vernaux is based on the information contained in
2358 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2359 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2360 // data structures within a single input file.
2361 for (auto &NV : P.first->VerdefMap) {
2362 Vernaux->vna_hash = NV.first->vd_hash;
2363 Vernaux->vna_flags = 0;
2364 Vernaux->vna_other = NV.second.Index;
2365 Vernaux->vna_name = NV.second.StrTab;
2366 Vernaux->vna_next = sizeof(Elf_Vernaux);
2367 ++Vernaux;
2368 }
2369
2370 Vernaux[-1].vna_next = 0;
2371 }
2372 Verneed[-1].vn_next = 0;
2373}
2374
Rui Ueyama945055a2017-02-27 03:07:41 +00002375template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002376 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2377 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002378}
2379
2380template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2381 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2382 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2383 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2384 return Size;
2385}
2386
George Rimar11992c862016-11-25 08:05:41 +00002387template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2388 return getNeedNum() == 0;
2389}
2390
Rafael Espindola6119b862017-03-06 20:23:56 +00002391void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002392 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002393 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002394}
2395
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002396MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2397 uint64_t Flags, uint32_t Alignment)
2398 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2399 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002400
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002401size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2402
2403void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002404
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002405void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002406 // Add all string pieces to the string table builder to create section
2407 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002408 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002409 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2410 if (Sec->Pieces[I].Live)
2411 Builder.add(Sec->getData(I));
2412
2413 // Fix the string table content. After this, the contents will never change.
2414 Builder.finalize();
2415
2416 // finalize() fixed tail-optimized strings, so we can now get
2417 // offsets of strings. Get an offset for each string and save it
2418 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002419 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002420 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2421 if (Sec->Pieces[I].Live)
2422 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2423}
2424
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002425void MergeNoTailSection::writeTo(uint8_t *Buf) {
2426 for (size_t I = 0; I < NumShards; ++I)
2427 Shards[I].write(Buf + ShardOffsets[I]);
2428}
2429
2430// This function is very hot (i.e. it can take several seconds to finish)
2431// because sometimes the number of inputs is in an order of magnitude of
2432// millions. So, we use multi-threading.
2433//
2434// For any strings S and T, we know S is not mergeable with T if S's hash
2435// value is different from T's. If that's the case, we can safely put S and
2436// T into different string builders without worrying about merge misses.
2437// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002438void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002439 // Initializes string table builders.
2440 for (size_t I = 0; I < NumShards; ++I)
2441 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2442
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002443 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2444 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002445 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002446 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002447 Concurrency =
2448 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002449
2450 // Add section pieces to the builders.
2451 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2452 for (MergeInputSection *Sec : Sections) {
2453 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2454 if (!Sec->Pieces[I].Live)
2455 continue;
Rui Ueyama95bf5092017-10-21 23:20:13 +00002456 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002457 if ((ShardId & (Concurrency - 1)) == ThreadId)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002458 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002459 }
2460 }
2461 });
2462
2463 // Compute an in-section offset for each shard.
2464 size_t Off = 0;
2465 for (size_t I = 0; I < NumShards; ++I) {
2466 Shards[I].finalizeInOrder();
2467 if (Shards[I].getSize() > 0)
2468 Off = alignTo(Off, Alignment);
2469 ShardOffsets[I] = Off;
2470 Off += Shards[I].getSize();
2471 }
2472 Size = Off;
2473
2474 // So far, section pieces have offsets from beginning of shards, but
2475 // we want offsets from beginning of the whole section. Fix them.
2476 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002477 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2478 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002479 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002480 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002481 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002482}
2483
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002484static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2485 uint32_t Type,
2486 uint64_t Flags,
2487 uint32_t Alignment) {
2488 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2489 if (ShouldTailMerge)
2490 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2491 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002492}
2493
Rui Ueyama2b714b52017-10-11 03:12:53 +00002494// Debug sections may be compressed by zlib. Uncompress if exists.
2495void elf::decompressSections() {
2496 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2497 if (Sec->Live)
2498 Sec->maybeUncompress();
2499 });
2500}
2501
2502// This function scans over the inputsections to create mergeable
2503// synthetic sections.
2504//
2505// It removes MergeInputSections from the input section array and adds
2506// new synthetic sections at the location of the first input section
2507// that it replaces. It then finalizes each synthetic section in order
2508// to compute an output offset for each piece of each input section.
2509void elf::mergeSections() {
2510 // splitIntoPieces needs to be called on each MergeInputSection
2511 // before calling finalizeContents(). Do that first.
2512 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2513 if (Sec->Live)
2514 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2515 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002516 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002517
2518 std::vector<MergeSyntheticSection *> MergeSections;
2519 for (InputSectionBase *&S : InputSections) {
2520 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2521 if (!MS)
2522 continue;
2523
2524 // We do not want to handle sections that are not alive, so just remove
2525 // them instead of trying to merge.
2526 if (!MS->Live)
2527 continue;
2528
George Rimar78e27e82017-12-01 09:04:52 +00002529 StringRef OutsecName = getOutputSectionName(MS);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002530 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2531
2532 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002533 // While we could create a single synthetic section for two different
2534 // values of Entsize, it is better to take Entsize into consideration.
2535 //
2536 // With a single synthetic section no two pieces with different Entsize
2537 // could be equal, so we may as well have two sections.
2538 //
2539 // Using Entsize in here also allows us to propagate it to the synthetic
2540 // section.
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002541 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002542 Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002543 });
2544 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002545 MergeSyntheticSection *Syn =
2546 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002547 MergeSections.push_back(Syn);
2548 I = std::prev(MergeSections.end());
2549 S = Syn;
Rafael Espindolaa5d43d02017-11-15 16:56:20 +00002550 Syn->Entsize = MS->Entsize;
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002551 } else {
2552 S = nullptr;
2553 }
2554 (*I)->addSection(MS);
2555 }
2556 for (auto *MS : MergeSections)
2557 MS->finalizeContents();
2558
2559 std::vector<InputSectionBase *> &V = InputSections;
2560 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2561}
2562
George Rimar42886c42017-03-15 12:02:31 +00002563MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002564 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2565 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002566
George Rimar90a528b2017-03-21 09:01:39 +00002567ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002568 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002569 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002570
2571// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2572// This section will have been sorted last in the .ARM.exidx table.
2573// This table entry will have the form:
2574// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002575// The sentinel must have the PREL31 value of an address higher than any
2576// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002577void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Igor Kudrinf01caab2017-12-14 06:23:50 +00002578 assert(Highest);
Igor Kudrin5966d152017-12-20 08:56:10 +00002579 uint64_t S =
2580 Highest->getParent()->Addr + Highest->getOffset(Highest->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002581 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002582 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002583 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002584}
2585
Igor Kudrin5966d152017-12-20 08:56:10 +00002586// The sentinel has to be removed if there are no other .ARM.exidx entries.
2587bool ARMExidxSentinelSection::empty() const {
2588 OutputSection *OS = getParent();
2589 for (auto *B : OS->SectionCommands)
2590 if (auto *ISD = dyn_cast<InputSectionDescription>(B))
2591 for (auto *S : ISD->Sections)
2592 if (!isa<ARMExidxSentinelSection>(S))
2593 return false;
2594 return true;
2595}
2596
George Rimar7b827042017-03-16 10:40:50 +00002597ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002598 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002599 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002600 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002601 this->OutSecOff = Off;
2602}
2603
George Rimar7b827042017-03-16 10:40:50 +00002604void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002605 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002606 T->Offset = Off;
2607 Thunks.push_back(T);
2608 T->addSymbols(*this);
2609 Size = Off + T->size();
2610}
2611
George Rimar7b827042017-03-16 10:40:50 +00002612void ThunkSection::writeTo(uint8_t *Buf) {
2613 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002614 T->writeTo(Buf + T->Offset, *this);
2615}
2616
George Rimar7b827042017-03-16 10:40:50 +00002617InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002618 if (Thunks.empty())
2619 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002620 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002621 return T->getTargetInputSection();
2622}
2623
George Rimar9782ca52017-03-15 15:29:29 +00002624InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002625BssSection *InX::Bss;
2626BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002627BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002628EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002629EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002630SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002631StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002632SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002633InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002634GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002635GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002636GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002637GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002638HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002639IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002640MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002641MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002642PltSection *InX::Plt;
2643PltSection *InX::Iplt;
Rafael Espindola58946cd2017-12-10 19:44:42 +00002644RelocationBaseSection *InX::RelaDyn;
Rafael Espindola87e0dea2017-12-10 20:07:03 +00002645RelocationBaseSection *InX::RelaPlt;
2646RelocationBaseSection *InX::RelaIplt;
George Rimar9782ca52017-03-15 15:29:29 +00002647StringTableSection *InX::ShStrTab;
2648StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002649SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002650
Rafael Espindola300b3862017-07-12 23:56:53 +00002651template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2652template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2653template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2654template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2655
Rui Ueyama572247f2017-10-27 03:13:39 +00002656template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2657template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2658template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2659template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2660
Rui Ueyamaf52496e2017-11-03 21:21:47 +00002661template void PltSection::addEntry<ELF32LE>(Symbol &Sym);
2662template void PltSection::addEntry<ELF32BE>(Symbol &Sym);
2663template void PltSection::addEntry<ELF64LE>(Symbol &Sym);
2664template void PltSection::addEntry<ELF64BE>(Symbol &Sym);
George Rimara9189572017-03-17 16:50:07 +00002665
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002666template class elf::MipsAbiFlagsSection<ELF32LE>;
2667template class elf::MipsAbiFlagsSection<ELF32BE>;
2668template class elf::MipsAbiFlagsSection<ELF64LE>;
2669template class elf::MipsAbiFlagsSection<ELF64BE>;
2670
Simon Atanasyance02cf02016-11-09 21:36:56 +00002671template class elf::MipsOptionsSection<ELF32LE>;
2672template class elf::MipsOptionsSection<ELF32BE>;
2673template class elf::MipsOptionsSection<ELF64LE>;
2674template class elf::MipsOptionsSection<ELF64BE>;
2675
2676template class elf::MipsReginfoSection<ELF32LE>;
2677template class elf::MipsReginfoSection<ELF32BE>;
2678template class elf::MipsReginfoSection<ELF64LE>;
2679template class elf::MipsReginfoSection<ELF64BE>;
2680
Eugene Leviant6380ce22016-11-15 12:26:55 +00002681template class elf::DynamicSection<ELF32LE>;
2682template class elf::DynamicSection<ELF32BE>;
2683template class elf::DynamicSection<ELF64LE>;
2684template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002685
2686template class elf::RelocationSection<ELF32LE>;
2687template class elf::RelocationSection<ELF32BE>;
2688template class elf::RelocationSection<ELF64LE>;
2689template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002690
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002691template class elf::AndroidPackedRelocationSection<ELF32LE>;
2692template class elf::AndroidPackedRelocationSection<ELF32BE>;
2693template class elf::AndroidPackedRelocationSection<ELF64LE>;
2694template class elf::AndroidPackedRelocationSection<ELF64BE>;
2695
Eugene Leviant9230db92016-11-17 09:16:34 +00002696template class elf::SymbolTableSection<ELF32LE>;
2697template class elf::SymbolTableSection<ELF32BE>;
2698template class elf::SymbolTableSection<ELF64LE>;
2699template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002700
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002701template class elf::VersionTableSection<ELF32LE>;
2702template class elf::VersionTableSection<ELF32BE>;
2703template class elf::VersionTableSection<ELF64LE>;
2704template class elf::VersionTableSection<ELF64BE>;
2705
2706template class elf::VersionNeedSection<ELF32LE>;
2707template class elf::VersionNeedSection<ELF32BE>;
2708template class elf::VersionNeedSection<ELF64LE>;
2709template class elf::VersionNeedSection<ELF64BE>;
2710
2711template class elf::VersionDefinitionSection<ELF32LE>;
2712template class elf::VersionDefinitionSection<ELF32BE>;
2713template class elf::VersionDefinitionSection<ELF64LE>;
2714template class elf::VersionDefinitionSection<ELF64BE>;