blob: c458f2dd1a975ae98b472332619dffdbc4d2fed9 [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 Ueyama9381eb12016-12-18 14:06:06 +000022#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000023#include "OutputSections.h"
24#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000025#include "SymbolTable.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"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000029#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000030#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000031#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000032#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000033#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000034#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000035#include "llvm/Support/Endian.h"
Peter Collingbourne5c54f152017-10-27 17:49:40 +000036#include "llvm/Support/LEB128.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000037#include "llvm/Support/MD5.h"
38#include "llvm/Support/RandomNumberGenerator.h"
39#include "llvm/Support/SHA1.h"
40#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000041#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000042#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000043
44using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000045using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000046using namespace llvm::ELF;
47using namespace llvm::object;
48using namespace llvm::support;
49using namespace llvm::support::endian;
50
51using namespace lld;
52using namespace lld::elf;
53
NAKAMURA Takumi70947e22017-09-30 13:40:22 +000054constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000055
Rui Ueyama79048e42017-10-27 03:59:34 +000056static void write32(void *Buf, uint32_t Val) {
57 endian::write32(Buf, Val, Config->Endianness);
58}
59
Rui Ueyama9320cb02017-02-27 02:56:02 +000060uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000061 if (OutputSection *Sec = getParent())
62 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000063 return 0;
64}
65
Rui Ueyama0fda1d72017-10-06 04:32:08 +000066// Create a .bss section for each common symbol and replace the common symbol
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000067// with a DefinedRegular symbol.
68template <class ELFT> void elf::createCommonSections() {
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000069 for (Symbol *S : Symtab->getSymbols()) {
70 auto *Sym = dyn_cast<DefinedCommon>(S->body());
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000071
72 if (!Sym)
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000073 continue;
George Rimar176d6062017-03-17 13:31:07 +000074
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000075 // Create a synthetic section for the common data.
Rui Ueyama732f4e22017-10-04 00:21:17 +000076 auto *Section = make<BssSection>("COMMON", Sym->Size, Sym->Alignment);
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000077 Section->File = Sym->getFile();
78 Section->Live = !Config->GcSections;
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000079 InputSections.push_back(Section);
80
81 // Replace all DefinedCommon symbols with DefinedRegular symbols so that we
82 // don't have to care about DefinedCommon symbols beyond this point.
83 replaceBody<DefinedRegular>(S, Sym->getFile(), Sym->getName(),
Rui Ueyama662bb002017-10-13 03:37:26 +000084 static_cast<bool>(Sym->isLocal()), Sym->StOther,
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000085 Sym->Type, 0, Sym->getSize<ELFT>(), Section);
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000086 }
Rui Ueyamae8a61022016-11-05 23:05:47 +000087}
88
Rui Ueyama3da3f062016-11-10 20:20:37 +000089// Returns an LLD version string.
90static ArrayRef<uint8_t> getVersion() {
91 // Check LLD_VERSION first for ease of testing.
92 // You can get consitent output by using the environment variable.
93 // This is only for testing.
94 StringRef S = getenv("LLD_VERSION");
95 if (S.empty())
96 S = Saver.save(Twine("Linker: ") + getLLDVersion());
97
98 // +1 to include the terminating '\0'.
99 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +0000100}
Rui Ueyama3da3f062016-11-10 20:20:37 +0000101
102// Creates a .comment section containing LLD version info.
103// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +0000104// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +0000105// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000106template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000107 typename ELFT::Shdr Hdr = {};
108 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
109 Hdr.sh_type = SHT_PROGBITS;
110 Hdr.sh_entsize = 1;
111 Hdr.sh_addralign = 1;
112
Rafael Espindola6119b862017-03-06 20:23:56 +0000113 auto *Ret =
Rui Ueyama709fb2bb12017-07-26 22:13:32 +0000114 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000115 Ret->Data = getVersion();
Rui Ueyama3da3f062016-11-10 20:20:37 +0000116 return Ret;
117}
118
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000119// .MIPS.abiflags section.
120template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000121MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000122 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000123 Flags(Flags) {
124 this->Entsize = sizeof(Elf_Mips_ABIFlags);
125}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000126
127template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
128 memcpy(Buf, &Flags, sizeof(Flags));
129}
130
131template <class ELFT>
132MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
133 Elf_Mips_ABIFlags Flags = {};
134 bool Create = false;
135
Rui Ueyama536a2672017-02-27 02:32:08 +0000136 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000137 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000138 continue;
139 Sec->Live = false;
140 Create = true;
141
Rui Ueyama25f30882017-10-27 03:25:04 +0000142 std::string Filename = toString(Sec->File);
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000143 const size_t Size = Sec->Data.size();
144 // Older version of BFD (such as the default FreeBSD linker) concatenate
145 // .MIPS.abiflags instead of merging. To allow for this case (or potential
146 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
147 if (Size < sizeof(Elf_Mips_ABIFlags)) {
148 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
149 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000150 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000151 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000152 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000153 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000154 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000155 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000156 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000157 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000158
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000159 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000160 // select the highest number of ISA/Rev/Ext.
161 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
162 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
163 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
164 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
165 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
166 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
167 Flags.ases |= S->ases;
168 Flags.flags1 |= S->flags1;
169 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000170 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000171 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000172
Rui Ueyama12f2da82016-11-22 03:57:06 +0000173 if (Create)
174 return make<MipsAbiFlagsSection<ELFT>>(Flags);
175 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000176}
177
Simon Atanasyance02cf02016-11-09 21:36:56 +0000178// .MIPS.options section.
179template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000180MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000181 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000182 Reginfo(Reginfo) {
183 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
184}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000185
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000186template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
187 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
188 Options->kind = ODK_REGINFO;
189 Options->size = getSize();
190
191 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000192 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000193 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000194}
195
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000196template <class ELFT>
197MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
198 // N64 ABI only.
199 if (!ELFT::Is64Bits)
200 return nullptr;
201
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000202 std::vector<InputSectionBase *> Sections;
203 for (InputSectionBase *Sec : InputSections)
204 if (Sec->Type == SHT_MIPS_OPTIONS)
205 Sections.push_back(Sec);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000206
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000207 if (Sections.empty())
208 return nullptr;
209
210 Elf_Mips_RegInfo Reginfo = {};
211 for (InputSectionBase *Sec : Sections) {
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000212 Sec->Live = false;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000213
Rui Ueyama25f30882017-10-27 03:25:04 +0000214 std::string Filename = toString(Sec->File);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000215 ArrayRef<uint8_t> D = Sec->Data;
216
217 while (!D.empty()) {
218 if (D.size() < sizeof(Elf_Mips_Options)) {
219 error(Filename + ": invalid size of .MIPS.options section");
220 break;
221 }
222
223 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
224 if (Opt->kind == ODK_REGINFO) {
225 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
226 error(Filename + ": unsupported non-zero ri_gp_value");
227 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000228 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000229 break;
230 }
231
232 if (!Opt->size)
233 fatal(Filename + ": zero option descriptor size");
234 D = D.slice(Opt->size);
235 }
236 };
237
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000238 return make<MipsOptionsSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000239}
240
241// MIPS .reginfo section.
242template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000243MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000244 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000245 Reginfo(Reginfo) {
246 this->Entsize = sizeof(Elf_Mips_RegInfo);
247}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000248
Rui Ueyamab71cae92016-11-22 03:57:08 +0000249template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000250 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000251 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000252 memcpy(Buf, &Reginfo, sizeof(Reginfo));
253}
254
255template <class ELFT>
256MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
257 // Section should be alive for O32 and N32 ABIs only.
258 if (ELFT::Is64Bits)
259 return nullptr;
260
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000261 std::vector<InputSectionBase *> Sections;
262 for (InputSectionBase *Sec : InputSections)
263 if (Sec->Type == SHT_MIPS_REGINFO)
264 Sections.push_back(Sec);
Rui Ueyamab71cae92016-11-22 03:57:08 +0000265
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000266 if (Sections.empty())
267 return nullptr;
268
269 Elf_Mips_RegInfo Reginfo = {};
270 for (InputSectionBase *Sec : Sections) {
Rui Ueyamab71cae92016-11-22 03:57:08 +0000271 Sec->Live = false;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000272
273 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rui Ueyama25f30882017-10-27 03:25:04 +0000274 error(toString(Sec->File) + ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000275 return nullptr;
276 }
277 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
278 if (Config->Relocatable && R->ri_gp_value)
Rui Ueyama25f30882017-10-27 03:25:04 +0000279 error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000280
281 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000282 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000283 };
284
Rui Ueyamaf9c66e42017-10-27 04:15:28 +0000285 return make<MipsReginfoSection<ELFT>>(Reginfo);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000286}
287
Rui Ueyama3255a522017-02-27 02:32:49 +0000288InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000289 // StringSaver guarantees that the returned string ends with '\0'.
290 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000291 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
292
293 auto *Sec =
294 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
295 Sec->Live = true;
296 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000297}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000298
Rui Ueyama65316d72017-02-23 03:15:57 +0000299SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
300 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000301 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
Rafael Espindola6e93d052017-08-04 22:31:42 +0000302 Value, Size, Section);
George Rimar69b17c32017-05-16 10:04:42 +0000303 if (InX::SymTab)
304 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000305 return S;
306}
307
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000308static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000309 switch (Config->BuildId) {
310 case BuildIdKind::Fast:
311 return 8;
312 case BuildIdKind::Md5:
313 case BuildIdKind::Uuid:
314 return 16;
315 case BuildIdKind::Sha1:
316 return 20;
317 case BuildIdKind::Hexstring:
318 return Config->BuildIdVector.size();
319 default:
320 llvm_unreachable("unknown BuildIdKind");
321 }
322}
323
George Rimar6c2949d2017-03-20 16:40:21 +0000324BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000325 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000326 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000327
George Rimar6c2949d2017-03-20 16:40:21 +0000328void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyama79048e42017-10-27 03:59:34 +0000329 write32(Buf, 4); // Name size
330 write32(Buf + 4, HashSize); // Content size
331 write32(Buf + 8, NT_GNU_BUILD_ID); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000332 memcpy(Buf + 12, "GNU", 4); // Name string
333 HashBuf = Buf + 16;
334}
335
Rui Ueyama35e00752016-11-10 00:12:28 +0000336// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000337static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
338 size_t ChunkSize) {
339 std::vector<ArrayRef<uint8_t>> Ret;
340 while (Arr.size() > ChunkSize) {
341 Ret.push_back(Arr.take_front(ChunkSize));
342 Arr = Arr.drop_front(ChunkSize);
343 }
344 if (!Arr.empty())
345 Ret.push_back(Arr);
346 return Ret;
347}
348
Rui Ueyama35e00752016-11-10 00:12:28 +0000349// Computes a hash value of Data using a given hash function.
350// In order to utilize multiple cores, we first split data into 1MB
351// chunks, compute a hash for each chunk, and then compute a hash value
352// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000353void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000354 llvm::ArrayRef<uint8_t> Data,
355 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000356 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000357 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000358
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000359 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000360 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000361 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
362 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000363
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000364 // Write to the final output buffer.
365 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000366}
367
Rui Ueyama732f4e22017-10-04 00:21:17 +0000368BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
369 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000370 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000371 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000372 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000373}
Peter Smithebfe9942017-02-09 10:27:57 +0000374
George Rimar6c2949d2017-03-20 16:40:21 +0000375void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000376 switch (Config->BuildId) {
377 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000378 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000379 write64le(Dest, xxHash64(toStringRef(Arr)));
380 });
381 break;
382 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000383 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000384 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000385 });
386 break;
387 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000388 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000389 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000390 });
391 break;
392 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000393 if (auto EC = getRandomBytes(HashBuf, HashSize))
394 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000395 break;
396 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000397 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000398 break;
399 default:
400 llvm_unreachable("unknown BuildIdKind");
401 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000402}
403
Rui Ueyama572247f2017-10-27 03:13:39 +0000404EhFrameSection::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000405 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000406
407// Search for an existing CIE record or create a new one.
408// CIE records from input object files are uniquified by their contents
409// and where their relocations point to.
Rui Ueyama572247f2017-10-27 03:13:39 +0000410template <class ELFT, class RelTy>
411CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000412 auto *Sec = cast<EhInputSection>(Cie.Sec);
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000413 if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000414 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
415
416 SymbolBody *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000417 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000418 if (FirstRelI != (unsigned)-1)
419 Personality =
420 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
421
422 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000423 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000424
425 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000426 if (!Rec) {
427 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000428 Rec->Cie = &Cie;
429 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000430 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000431 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000432}
433
434// There is one FDE per function. Returns true if a given FDE
435// points to a live function.
Rui Ueyama572247f2017-10-27 03:13:39 +0000436template <class ELFT, class RelTy>
437bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000438 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000439 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000440
441 // An FDE should point to some function because FDEs are to describe
442 // functions. That's however not always the case due to an issue of
443 // ld.gold with -r. ld.gold may discard only functions and leave their
444 // corresponding FDEs, which results in creating bad .eh_frame sections.
445 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000446 if (FirstRelI == (unsigned)-1)
447 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000448
Rafael Espindola66b4e212017-02-23 22:06:28 +0000449 const RelTy &Rel = Rels[FirstRelI];
450 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000451
452 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Rui Ueyama27a357c2017-09-18 19:15:54 +0000453 if (auto *D = dyn_cast<DefinedRegular>(&B))
George Rimard605f412017-10-26 09:13:19 +0000454 if (auto *Sec = cast_or_null<InputSectionBase>(D->Section))
455 return Sec->Live && (Sec == Sec->Repl);
Rui Ueyama27a357c2017-09-18 19:15:54 +0000456 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000457}
458
459// .eh_frame is a sequence of CIE or FDE records. In general, there
460// is one CIE record per input object file which is followed by
461// a list of FDEs. This function searches an existing CIE or create a new
462// one and associates FDEs to the CIE.
Rui Ueyama572247f2017-10-27 03:13:39 +0000463template <class ELFT, class RelTy>
464void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000465 DenseMap<size_t, CieRecord *> OffsetToCie;
466 for (EhSectionPiece &Piece : Sec->Pieces) {
467 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000468 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000469 return;
470
471 size_t Offset = Piece.InputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000472 uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000473 if (ID == 0) {
Rui Ueyama572247f2017-10-27 03:13:39 +0000474 OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000475 continue;
476 }
477
478 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000479 CieRecord *Rec = OffsetToCie[CieOffset];
480 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000481 fatal(toString(Sec) + ": invalid CIE reference");
482
Rui Ueyama572247f2017-10-27 03:13:39 +0000483 if (!isFdeLive<ELFT>(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000484 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000485 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000486 NumFdes++;
487 }
488}
489
Rui Ueyama572247f2017-10-27 03:13:39 +0000490template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000491 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000492 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000493
494 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000495 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000496
Petr Hosek7b793212017-03-10 20:00:42 +0000497 for (auto *DS : Sec->DependentSections)
498 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000499
500 // .eh_frame is a sequence of CIE or FDE records. This function
501 // splits it into pieces so that we can call
502 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000503 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000504 if (Sec->Pieces.empty())
505 return;
506
Rui Ueyamabfa84322017-10-26 22:30:25 +0000507 if (Sec->AreRelocsRela)
Rui Ueyama572247f2017-10-27 03:13:39 +0000508 addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
Rui Ueyamafaa38022017-09-19 20:28:03 +0000509 else
Rui Ueyama572247f2017-10-27 03:13:39 +0000510 addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000511}
512
Rafael Espindola66b4e212017-02-23 22:06:28 +0000513static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
514 memcpy(Buf, D.data(), D.size());
515
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000516 size_t Aligned = alignTo(D.size(), Config->Wordsize);
Andrew Ng6dee7362017-09-07 08:43:56 +0000517
518 // Zero-clear trailing padding if it exists.
519 memset(Buf + D.size(), 0, Aligned - D.size());
520
Rafael Espindola66b4e212017-02-23 22:06:28 +0000521 // Fix the size field. -4 since size does not include the size field itself.
Rui Ueyama79048e42017-10-27 03:59:34 +0000522 write32(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000523}
524
Rui Ueyama572247f2017-10-27 03:13:39 +0000525void EhFrameSection::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000526 if (this->Size)
527 return; // Already finalized.
528
529 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000530 for (CieRecord *Rec : CieRecords) {
531 Rec->Cie->OutputOff = Off;
532 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000533
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000534 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000535 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000536 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000537 }
538 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000539
540 // The LSB standard does not allow a .eh_frame section with zero
541 // Call Frame Information records. Therefore add a CIE record length
542 // 0 as a terminator if this .eh_frame section is empty.
543 if (Off == 0)
544 Off = 4;
545
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000546 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000547}
548
Rui Ueyamac0552252017-10-27 03:13:24 +0000549// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
550// to get an FDE from an address to which FDE is applied. This function
551// returns a list of such pairs.
Rui Ueyama572247f2017-10-27 03:13:39 +0000552std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
Rui Ueyamac0552252017-10-27 03:13:24 +0000553 uint8_t *Buf = getParent()->Loc + OutSecOff;
554 std::vector<FdeData> Ret;
555
556 for (CieRecord *Rec : CieRecords) {
Rui Ueyama86297522017-10-27 03:14:09 +0000557 uint8_t Enc = getFdeEncoding(Rec->Cie);
Rui Ueyamac0552252017-10-27 03:13:24 +0000558 for (EhSectionPiece *Fde : Rec->Fdes) {
559 uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
560 uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
561 Ret.push_back({Pc, FdeVA});
562 }
563 }
564 return Ret;
565}
566
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000567static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000568 switch (Size) {
569 case DW_EH_PE_udata2:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000570 return read16(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000571 case DW_EH_PE_udata4:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000572 return read32(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000573 case DW_EH_PE_udata8:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000574 return read64(Buf, Config->Endianness);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000575 case DW_EH_PE_absptr:
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000576 return readUint(Buf);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000577 }
578 fatal("unknown FDE size encoding");
579}
580
581// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
582// We need it to create .eh_frame_hdr section.
Rui Ueyama572247f2017-10-27 03:13:39 +0000583uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
584 uint8_t Enc) const {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000585 // The starting address to which this FDE applies is
586 // stored at FDE + 8 byte.
587 size_t Off = FdeOff + 8;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000588 uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000589 if ((Enc & 0x70) == DW_EH_PE_absptr)
590 return Addr;
591 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000592 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000593 fatal("unknown FDE size relative encoding");
594}
595
Rui Ueyama572247f2017-10-27 03:13:39 +0000596void EhFrameSection::writeTo(uint8_t *Buf) {
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000597 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000598 for (CieRecord *Rec : CieRecords) {
599 size_t CieOffset = Rec->Cie->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000600 writeCieFde(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000601
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000602 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000603 size_t Off = Fde->OutputOff;
Rui Ueyama076e2bb2017-10-27 03:13:09 +0000604 writeCieFde(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000605
606 // FDE's second word should have the offset to an associated CIE.
607 // Write it.
Rui Ueyama79048e42017-10-27 03:59:34 +0000608 write32(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000609 }
610 }
611
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000612 // Apply relocations. .eh_frame section contents are not contiguous
613 // in the output buffer, but relocateAlloc() still works because
614 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000615 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000616 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000617}
618
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000619GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000620 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
621 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000622
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000623void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000624 Sym.GotIndex = NumEntries;
625 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000626}
627
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000628bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000629 if (Sym.GlobalDynIndex != -1U)
630 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000631 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000632 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000633 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000634 return true;
635}
636
637// Reserves TLS entries for a TLS module ID and a TLS block offset.
638// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000639bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640 if (TlsIndexOff != uint32_t(-1))
641 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000642 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000643 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000644 return true;
645}
646
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000647uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000648 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000649}
650
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000651uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000652 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000653}
654
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000655void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000656
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000657bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000658 // We need to emit a GOT even if it's empty if there's a relocation that is
659 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
660 // (i.e. _GLOBAL_OFFSET_TABLE_).
661 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
George Rimar11992c862016-11-25 08:05:41 +0000662}
663
Igor Kudrin202a9f62017-07-14 08:10:45 +0000664void GotSection::writeTo(uint8_t *Buf) {
665 // Buf points to the start of this section's buffer,
666 // whereas InputSectionBase::relocateAlloc() expects its argument
667 // to point to the start of the output section.
668 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
669}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000670
George Rimar14534eb2017-03-20 16:44:28 +0000671MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000672 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
673 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000674
George Rimar14534eb2017-03-20 16:44:28 +0000675void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000676 // For "true" local symbols which can be referenced from the same module
677 // only compiler creates two instructions for address loading:
678 //
679 // lw $8, 0($gp) # R_MIPS_GOT16
680 // addi $8, $8, 0 # R_MIPS_LO16
681 //
682 // The first instruction loads high 16 bits of the symbol address while
683 // the second adds an offset. That allows to reduce number of required
684 // GOT entries because only one global offset table entry is necessary
685 // for every 64 KBytes of local data. So for local symbols we need to
686 // allocate number of GOT entries to hold all required "page" addresses.
687 //
688 // All global symbols (hidden and regular) considered by compiler uniformly.
689 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
690 // to load address of the symbol. So for each such symbol we need to
691 // allocate dedicated GOT entry to store its address.
692 //
693 // If a symbol is preemptible we need help of dynamic linker to get its
694 // final address. The corresponding GOT entries are allocated in the
695 // "global" part of GOT. Entries for non preemptible global symbol allocated
696 // in the "local" part of GOT.
697 //
698 // See "Global Offset Table" in Chapter 5:
699 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
700 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
701 // At this point we do not know final symbol value so to reduce number
702 // of allocated GOT entries do the following trick. Save all output
703 // sections referenced by GOT relocations. Then later in the `finalize`
704 // method calculate number of "pages" required to cover all saved output
705 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000706 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000707 return;
708 }
709 if (Sym.isTls()) {
710 // GOT entries created for MIPS TLS relocations behave like
711 // almost GOT entries from other ABIs. They go to the end
712 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000713 Sym.GotIndex = TlsEntries.size();
714 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000715 return;
716 }
George Rimar14534eb2017-03-20 16:44:28 +0000717 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 if (S.isInGot() && !A)
719 return;
720 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000721 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000722 return;
723 Items.emplace_back(&S, A);
724 if (!A)
725 S.GotIndex = NewIndex;
726 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000727 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000728 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000729 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000730 Sym.IsInGlobalMipsGot = true;
731 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000732 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000733 Sym.Is32BitMipsGot = true;
734 } else {
735 // Hold local GOT entries accessed via a 16-bit index separately.
736 // That allows to write them in the beginning of the GOT and keep
737 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000738 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000739 }
740}
741
George Rimar14534eb2017-03-20 16:44:28 +0000742bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000743 if (Sym.GlobalDynIndex != -1U)
744 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000745 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000746 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000747 TlsEntries.push_back(nullptr);
748 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000749 return true;
750}
751
752// Reserves TLS entries for a TLS module ID and a TLS block offset.
753// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000754bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000755 if (TlsIndexOff != uint32_t(-1))
756 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000757 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000758 TlsEntries.push_back(nullptr);
759 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000760 return true;
761}
762
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000763static uint64_t getMipsPageAddr(uint64_t Addr) {
764 return (Addr + 0x8000) & ~0xffff;
765}
766
767static uint64_t getMipsPageCount(uint64_t Size) {
768 return (Size + 0xfffe) / 0xffff + 1;
769}
770
George Rimar14534eb2017-03-20 16:44:28 +0000771uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
772 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000773 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000774 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
775 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
776 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000777 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000778 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000779}
780
George Rimar14534eb2017-03-20 16:44:28 +0000781uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
782 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000784 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000785 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000786 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000787 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000788 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000789 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000790 Index += LocalEntries.size();
791 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000792 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000795 auto It = EntryIndexMap.find({&B, Addend});
796 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000797 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000798 }
George Rimar14534eb2017-03-20 16:44:28 +0000799 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000800}
801
George Rimar14534eb2017-03-20 16:44:28 +0000802uint64_t MipsGotSection::getTlsOffset() const {
803 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804}
805
George Rimar14534eb2017-03-20 16:44:28 +0000806uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
807 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000808}
809
George Rimar14534eb2017-03-20 16:44:28 +0000810const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000811 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000812}
813
George Rimar14534eb2017-03-20 16:44:28 +0000814unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000815 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
816 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000817}
818
George Rimar67c60722017-07-18 11:55:35 +0000819void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000820
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000821bool MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000822 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000823 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000824 // For each output section referenced by GOT page relocations calculate
825 // and save into PageIndexMap an upper bound of MIPS GOT entries required
826 // to store page addresses of local symbols. We assume the worst case -
827 // each 64kb page of the output section has at least one GOT relocation
828 // against it. And take in account the case when the section intersects
829 // page boundaries.
830 P.second = PageEntriesNum;
831 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000832 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000833 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000834 Config->Wordsize;
Peter Collingbourne5c54f152017-10-27 17:49:40 +0000835 return false;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000836}
837
George Rimar14534eb2017-03-20 16:44:28 +0000838bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000839 // We add the .got section to the result for dynamic MIPS target because
840 // its address and properties are mentioned in the .dynamic section.
841 return Config->Relocatable;
842}
843
George Rimar67c60722017-07-18 11:55:35 +0000844uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000845
George Rimar14534eb2017-03-20 16:44:28 +0000846void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000847 // Set the MSB of the second GOT slot. This is not required by any
848 // MIPS ABI documentation, though.
849 //
850 // There is a comment in glibc saying that "The MSB of got[1] of a
851 // gnu object is set to identify gnu objects," and in GNU gold it
852 // says "the second entry will be used by some runtime loaders".
853 // But how this field is being used is unclear.
854 //
855 // We are not really willing to mimic other linkers behaviors
856 // without understanding why they do that, but because all files
857 // generated by GNU tools have this special GOT value, and because
858 // we've been doing this for years, it is probably a safe bet to
859 // keep doing this for now. We really need to revisit this to see
860 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000861 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
862 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000863 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000864 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000865 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000866 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000867 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000868 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
869 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000870 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000871 }
George Rimar14534eb2017-03-20 16:44:28 +0000872 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000873 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000874 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000875 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000876 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000877 uint64_t VA = Body->getVA(SA.second);
878 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000879 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000880 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
881 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
882 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000883 // Initialize TLS-related GOT entries. If the entry has a corresponding
884 // dynamic relocations, leave it initialized by zero. Write down adjusted
885 // TLS symbol's values otherwise. To calculate the adjustments use offsets
886 // for thread-local storage.
887 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000888 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000889 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000890 for (const SymbolBody *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000891 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000892 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000893 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000894 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000895 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
896 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000897 }
898 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000899 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
900 writeUint(Entry, 1);
901 Entry += Config->Wordsize;
902 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000903 }
904 }
905}
906
George Rimar10f74fc2017-03-15 09:12:56 +0000907GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000908 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
909 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000910
George Rimar10f74fc2017-03-15 09:12:56 +0000911void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000912 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
913 Entries.push_back(&Sym);
914}
915
George Rimar10f74fc2017-03-15 09:12:56 +0000916size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000917 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
918 Target->GotPltEntrySize;
919}
920
George Rimar10f74fc2017-03-15 09:12:56 +0000921void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000922 Target->writeGotPltHeader(Buf);
923 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
924 for (const SymbolBody *B : Entries) {
925 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000926 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000927 }
928}
929
Peter Smithbaffdb82016-12-08 12:58:55 +0000930// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
931// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000932IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000933 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
934 Target->GotPltEntrySize,
935 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000936
George Rimar10f74fc2017-03-15 09:12:56 +0000937void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000938 Sym.IsInIgot = true;
939 Sym.GotPltIndex = Entries.size();
940 Entries.push_back(&Sym);
941}
942
George Rimar10f74fc2017-03-15 09:12:56 +0000943size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000944 return Entries.size() * Target->GotPltEntrySize;
945}
946
George Rimar10f74fc2017-03-15 09:12:56 +0000947void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000948 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000949 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000950 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000951 }
952}
953
George Rimar49648002017-03-15 09:32:36 +0000954StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
955 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000956 Dynamic(Dynamic) {
957 // ELF string tables start with a NUL byte.
958 addString("");
959}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000960
961// Adds a string to the string table. If HashIt is true we hash and check for
962// duplicates. It is optional because the name of global symbols are already
963// uniqued and hashing them again has a big cost for a small value: uniquing
964// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000965unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000966 if (HashIt) {
967 auto R = StringMap.insert(std::make_pair(S, this->Size));
968 if (!R.second)
969 return R.first->second;
970 }
971 unsigned Ret = this->Size;
972 this->Size = this->Size + S.size() + 1;
973 Strings.push_back(S);
974 return Ret;
975}
976
George Rimar49648002017-03-15 09:32:36 +0000977void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000978 for (StringRef S : Strings) {
979 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000980 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000981 Buf += S.size() + 1;
982 }
983}
984
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000985// Returns the number of version definition entries. Because the first entry
986// is for the version definition itself, it is the number of versioned symbols
987// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000988static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
989
990template <class ELFT>
991DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000992 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +0000993 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +0000994 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +0000995
Petr Hosekffa786f2017-05-26 19:12:38 +0000996 // .dynamic section is not writable on MIPS and on Fuchsia OS
997 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000998 // See "Special Section" in Chapter 4 in the following document:
999 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001000 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001001 this->Flags = SHF_ALLOC;
1002
1003 addEntries();
1004}
1005
1006// There are some dynamic entries that don't depend on other sections.
1007// Such entries can be set early.
1008template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1009 // Add strings to .dynstr early so that .dynstr's size will be
1010 // fixed early.
George Rimarf525c922017-07-17 09:43:18 +00001011 for (StringRef S : Config->FilterList)
1012 add({DT_FILTER, InX::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001013 for (StringRef S : Config->AuxiliaryList)
Rafael Espindola895aea62017-05-11 22:02:41 +00001014 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001015 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001016 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001017 InX::DynStrTab->addString(Config->Rpath)});
George Rimar696a7f92017-09-19 09:20:54 +00001018 for (InputFile *File : SharedFiles) {
1019 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001020 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001021 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
George Rimar696a7f92017-09-19 09:20:54 +00001022 }
Eugene Leviant6380ce22016-11-15 12:26:55 +00001023 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001024 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001025
1026 // Set DT_FLAGS and DT_FLAGS_1.
1027 uint32_t DtFlags = 0;
1028 uint32_t DtFlags1 = 0;
1029 if (Config->Bsymbolic)
1030 DtFlags |= DF_SYMBOLIC;
1031 if (Config->ZNodelete)
1032 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001033 if (Config->ZNodlopen)
1034 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001035 if (Config->ZNow) {
1036 DtFlags |= DF_BIND_NOW;
1037 DtFlags1 |= DF_1_NOW;
1038 }
1039 if (Config->ZOrigin) {
1040 DtFlags |= DF_ORIGIN;
1041 DtFlags1 |= DF_1_ORIGIN;
1042 }
1043
1044 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001045 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001046 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001047 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001048
Petr Hosekffa786f2017-05-26 19:12:38 +00001049 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1050 // need it for each process, so we don't write it for DSOs. The loader writes
1051 // the pointer into this entry.
1052 //
1053 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1054 // systems (currently only Fuchsia OS) provide other means to give the
1055 // debugger this information. Such systems may choose make .dynamic read-only.
1056 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1057 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001058 add({DT_DEBUG, (uint64_t)0});
1059}
1060
1061// Add remaining entries to complete .dynamic contents.
1062template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1063 if (this->Size)
1064 return; // Already finalized.
1065
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001066 this->Link = InX::DynStrTab->getParent()->SectionIndex;
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001067 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001068 add({In<ELFT>::RelaDyn->DynamicTag, In<ELFT>::RelaDyn});
1069 add({In<ELFT>::RelaDyn->SizeDynamicTag, In<ELFT>::RelaDyn->getParent(),
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001070 Entry::SecSize});
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001071
1072 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001073 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001074 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001075
1076 // MIPS dynamic loader does not support RELCOUNT tag.
1077 // The problem is in the tight relation between dynamic
1078 // relocations and GOT. So do not emit this tag on MIPS.
1079 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001080 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001081 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001082 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001083 }
1084 }
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001085 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001086 add({DT_JMPREL, In<ELFT>::RelaPlt});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001087 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent(), Entry::SecSize});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001088 switch (Config->EMachine) {
1089 case EM_MIPS:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001090 add({DT_MIPS_PLTGOT, InX::GotPlt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001091 break;
1092 case EM_SPARCV9:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001093 add({DT_PLTGOT, InX::Plt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001094 break;
1095 default:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001096 add({DT_PLTGOT, InX::GotPlt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001097 break;
1098 }
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001099 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001100 }
1101
George Rimar69b17c32017-05-16 10:04:42 +00001102 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001103 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001104 add({DT_STRTAB, InX::DynStrTab});
1105 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001106 if (!Config->ZText)
1107 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001108 if (InX::GnuHashTab)
1109 add({DT_GNU_HASH, InX::GnuHashTab});
George Rimaraaf54712017-09-27 09:14:59 +00001110 if (InX::HashTab)
1111 add({DT_HASH, InX::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001112
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001113 if (Out::PreinitArray) {
1114 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1115 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001116 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001117 if (Out::InitArray) {
1118 add({DT_INIT_ARRAY, Out::InitArray});
1119 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001120 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001121 if (Out::FiniArray) {
1122 add({DT_FINI_ARRAY, Out::FiniArray});
1123 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001124 }
1125
Rui Ueyama43099e42017-08-15 16:03:11 +00001126 if (SymbolBody *B = Symtab->find(Config->Init))
Rui Ueyamabda337a2017-10-27 22:54:16 +00001127 if (B->isInCurrentOutput())
Rui Ueyama43099e42017-08-15 16:03:11 +00001128 add({DT_INIT, B});
1129 if (SymbolBody *B = Symtab->find(Config->Fini))
Rui Ueyamabda337a2017-10-27 22:54:16 +00001130 if (B->isInCurrentOutput())
Rui Ueyama43099e42017-08-15 16:03:11 +00001131 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001132
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001133 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1134 if (HasVerNeed || In<ELFT>::VerDef)
1135 add({DT_VERSYM, In<ELFT>::VerSym});
1136 if (In<ELFT>::VerDef) {
1137 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001138 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001139 }
1140 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001141 add({DT_VERNEED, In<ELFT>::VerNeed});
1142 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001143 }
1144
1145 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001146 add({DT_MIPS_RLD_VERSION, 1});
1147 add({DT_MIPS_FLAGS, RHF_NOTPOT});
James Hendersonb5ca92e2017-10-10 10:09:35 +00001148 add({DT_MIPS_BASE_ADDRESS, Target->getImageBase()});
George Rimar69b17c32017-05-16 10:04:42 +00001149 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001150 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1151 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001152 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001153 else
George Rimar69b17c32017-05-16 10:04:42 +00001154 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001155 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001156 if (InX::MipsRldMap)
1157 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001158 }
1159
George Rimar8f3a6c82017-10-06 10:06:13 +00001160 add({DT_NULL, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001161
George Rimar8f3a6c82017-10-06 10:06:13 +00001162 getParent()->Link = this->Link;
1163 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001164}
1165
1166template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1167 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1168
1169 for (const Entry &E : Entries) {
1170 P->d_tag = E.Tag;
1171 switch (E.Kind) {
1172 case Entry::SecAddr:
1173 P->d_un.d_ptr = E.OutSec->Addr;
1174 break;
1175 case Entry::InSecAddr:
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001176 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001177 break;
1178 case Entry::SecSize:
1179 P->d_un.d_val = E.OutSec->Size;
1180 break;
1181 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001182 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001183 break;
1184 case Entry::PlainInt:
1185 P->d_un.d_val = E.Val;
1186 break;
1187 }
1188 ++P;
1189 }
1190}
1191
George Rimar97def8c2017-03-17 12:07:44 +00001192uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001193 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001194}
1195
George Rimar97def8c2017-03-17 12:07:44 +00001196int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001197 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001198 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001199 return Addend;
1200}
1201
George Rimar97def8c2017-03-17 12:07:44 +00001202uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001203 if (Sym && !UseSymVA)
1204 return Sym->DynsymIndex;
1205 return 0;
1206}
1207
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001208RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1209 int32_t DynamicTag,
1210 int32_t SizeDynamicTag)
1211 : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1212 DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
Eugene Levianta96d9022016-11-16 10:02:27 +00001213
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001214void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001215 if (Reloc.Type == Target->RelativeRel)
1216 ++NumRelativeRelocs;
1217 Relocs.push_back(Reloc);
1218}
1219
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001220void RelocationBaseSection::finalizeContents() {
1221 // If all relocations are R_*_RELATIVE they don't refer to any
1222 // dynamic symbol and we don't need a dynamic symbol table. If that
1223 // is the case, just use 0 as the link.
1224 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
1225
1226 // Set required output section properties.
1227 getParent()->Link = this->Link;
1228}
1229
1230template <class ELFT>
1231static void encodeDynamicReloc(typename ELFT::Rela *P,
1232 const DynamicReloc &Rel) {
1233 if (Config->IsRela)
1234 P->r_addend = Rel.getAddend();
1235 P->r_offset = Rel.getOffset();
1236 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1237 // The MIPS GOT section contains dynamic relocations that correspond to TLS
1238 // entries. These entries are placed after the global and local sections of
1239 // the GOT. At the point when we create these relocations, the size of the
1240 // global and local sections is unknown, so the offset that we store in the
1241 // TLS entry's DynamicReloc is relative to the start of the TLS section of
1242 // the GOT, rather than being relative to the start of the GOT. This line of
1243 // code adds the size of the global and local sections to the virtual
1244 // address computed by getOffset() in order to adjust it into the TLS
1245 // section.
1246 P->r_offset += InX::MipsGot->getTlsOffset();
1247 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1248}
1249
1250template <class ELFT>
1251RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1252 : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1253 Config->IsRela ? DT_RELA : DT_REL,
1254 Config->IsRela ? DT_RELASZ : DT_RELSZ),
1255 Sort(Sort) {
1256 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
1257}
1258
Eugene Levianta96d9022016-11-16 10:02:27 +00001259template <class ELFT, class RelTy>
1260static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001261 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1262 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001263 if (AIsRel != BIsRel)
1264 return AIsRel;
1265
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001266 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001267}
1268
1269template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1270 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001271 for (const DynamicReloc &Rel : Relocs) {
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001272 encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001273 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001274 }
1275
1276 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001277 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001278 std::stable_sort((Elf_Rela *)BufBegin,
1279 (Elf_Rela *)BufBegin + Relocs.size(),
1280 compRelocations<ELFT, Elf_Rela>);
1281 else
1282 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1283 compRelocations<ELFT, Elf_Rel>);
1284 }
1285}
1286
1287template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1288 return this->Entsize * Relocs.size();
1289}
1290
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001291template <class ELFT>
1292AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1293 StringRef Name)
1294 : RelocationBaseSection(
1295 Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1296 Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1297 Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1298 this->Entsize = 1;
1299}
Eugene Levianta96d9022016-11-16 10:02:27 +00001300
Peter Collingbourne5c54f152017-10-27 17:49:40 +00001301template <class ELFT>
1302bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1303 // This function computes the contents of an Android-format packed relocation
1304 // section.
1305 //
1306 // This format compresses relocations by using relocation groups to factor out
1307 // fields that are common between relocations and storing deltas from previous
1308 // relocations in SLEB128 format (which has a short representation for small
1309 // numbers). A good example of a relocation type with common fields is
1310 // R_*_RELATIVE, which is normally used to represent function pointers in
1311 // vtables. In the REL format, each relative relocation has the same r_info
1312 // field, and is only different from other relative relocations in terms of
1313 // the r_offset field. By sorting relocations by offset, grouping them by
1314 // r_info and representing each relocation with only the delta from the
1315 // previous offset, each 8-byte relocation can be compressed to as little as 1
1316 // byte (or less with run-length encoding). This relocation packer was able to
1317 // reduce the size of the relocation section in an Android Chromium DSO from
1318 // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1319 //
1320 // A relocation section consists of a header containing the literal bytes
1321 // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1322 // elements are the total number of relocations in the section and an initial
1323 // r_offset value. The remaining elements define a sequence of relocation
1324 // groups. Each relocation group starts with a header consisting of the
1325 // following elements:
1326 //
1327 // - the number of relocations in the relocation group
1328 // - flags for the relocation group
1329 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1330 // for each relocation in the group.
1331 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1332 // field for each relocation in the group.
1333 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1334 // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1335 // each relocation in the group.
1336 //
1337 // Following the relocation group header are descriptions of each of the
1338 // relocations in the group. They consist of the following elements:
1339 //
1340 // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1341 // delta for this relocation.
1342 // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1343 // field for this relocation.
1344 // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1345 // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1346 // this relocation.
1347
1348 size_t OldSize = RelocData.size();
1349
1350 RelocData = {'A', 'P', 'S', '2'};
1351 raw_svector_ostream OS(RelocData);
1352
1353 // The format header includes the number of relocations and the initial
1354 // offset (we set this to zero because the first relocation group will
1355 // perform the initial adjustment).
1356 encodeSLEB128(Relocs.size(), OS);
1357 encodeSLEB128(0, OS);
1358
1359 std::vector<Elf_Rela> Relatives, NonRelatives;
1360
1361 for (const DynamicReloc &Rel : Relocs) {
1362 Elf_Rela R;
1363 encodeDynamicReloc<ELFT>(&R, Rel);
1364
1365 if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1366 Relatives.push_back(R);
1367 else
1368 NonRelatives.push_back(R);
1369 }
1370
1371 std::sort(Relatives.begin(), Relatives.end(),
1372 [](const Elf_Rel &A, const Elf_Rel &B) {
1373 return A.r_offset < B.r_offset;
1374 });
1375
1376 // Try to find groups of relative relocations which are spaced one word
1377 // apart from one another. These generally correspond to vtable entries. The
1378 // format allows these groups to be encoded using a sort of run-length
1379 // encoding, but each group will cost 7 bytes in addition to the offset from
1380 // the previous group, so it is only profitable to do this for groups of
1381 // size 8 or larger.
1382 std::vector<Elf_Rela> UngroupedRelatives;
1383 std::vector<std::vector<Elf_Rela>> RelativeGroups;
1384 for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1385 std::vector<Elf_Rela> Group;
1386 do {
1387 Group.push_back(*I++);
1388 } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset);
1389
1390 if (Group.size() < 8)
1391 UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1392 Group.end());
1393 else
1394 RelativeGroups.emplace_back(std::move(Group));
1395 }
1396
1397 unsigned HasAddendIfRela =
1398 Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0;
1399
1400 uint64_t Offset = 0;
1401 uint64_t Addend = 0;
1402
1403 // Emit the run-length encoding for the groups of adjacent relative
1404 // relocations. Each group is represented using two groups in the packed
1405 // format. The first is used to set the current offset to the start of the
1406 // group (and also encodes the first relocation), and the second encodes the
1407 // remaining relocations.
1408 for (std::vector<Elf_Rela> &G : RelativeGroups) {
1409 // The first relocation in the group.
1410 encodeSLEB128(1, OS);
1411 encodeSLEB128(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1412 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela,
1413 OS);
1414 encodeSLEB128(G[0].r_offset - Offset, OS);
1415 encodeSLEB128(Target->RelativeRel, OS);
1416 if (Config->IsRela) {
1417 encodeSLEB128(G[0].r_addend - Addend, OS);
1418 Addend = G[0].r_addend;
1419 }
1420
1421 // The remaining relocations.
1422 encodeSLEB128(G.size() - 1, OS);
1423 encodeSLEB128(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1424 RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela,
1425 OS);
1426 encodeSLEB128(Config->Wordsize, OS);
1427 encodeSLEB128(Target->RelativeRel, OS);
1428 if (Config->IsRela) {
1429 for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1430 encodeSLEB128(I->r_addend - Addend, OS);
1431 Addend = I->r_addend;
1432 }
1433 }
1434
1435 Offset = G.back().r_offset;
1436 }
1437
1438 // Now the ungrouped relatives.
1439 if (!UngroupedRelatives.empty()) {
1440 encodeSLEB128(UngroupedRelatives.size(), OS);
1441 encodeSLEB128(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela, OS);
1442 encodeSLEB128(Target->RelativeRel, OS);
1443 for (Elf_Rela &R : UngroupedRelatives) {
1444 encodeSLEB128(R.r_offset - Offset, OS);
1445 Offset = R.r_offset;
1446 if (Config->IsRela) {
1447 encodeSLEB128(R.r_addend - Addend, OS);
1448 Addend = R.r_addend;
1449 }
1450 }
1451 }
1452
1453 // Finally the non-relative relocations.
1454 std::sort(NonRelatives.begin(), NonRelatives.end(),
1455 [](const Elf_Rela &A, const Elf_Rela &B) {
1456 return A.r_offset < B.r_offset;
1457 });
1458 if (!NonRelatives.empty()) {
1459 encodeSLEB128(NonRelatives.size(), OS);
1460 encodeSLEB128(HasAddendIfRela, OS);
1461 for (Elf_Rela &R : NonRelatives) {
1462 encodeSLEB128(R.r_offset - Offset, OS);
1463 Offset = R.r_offset;
1464 encodeSLEB128(R.r_info, OS);
1465 if (Config->IsRela) {
1466 encodeSLEB128(R.r_addend - Addend, OS);
1467 Addend = R.r_addend;
1468 }
1469 }
1470 }
1471
1472 // Returns whether the section size changed. We need to keep recomputing both
1473 // section layout and the contents of this section until the size converges
1474 // because changing this section's size can affect section layout, which in
1475 // turn can affect the sizes of the LEB-encoded integers stored in this
1476 // section.
1477 return RelocData.size() != OldSize;
Eugene Levianta96d9022016-11-16 10:02:27 +00001478}
1479
George Rimarf45f6812017-05-16 08:53:30 +00001480SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001481 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001482 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001483 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001484 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001485 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001486
1487// Orders symbols according to their positions in the GOT,
1488// in compliance with MIPS ABI rules.
1489// See "Global Offset Table" in Chapter 5 in the following document
1490// for detailed description:
1491// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001492static bool sortMipsSymbols(const SymbolTableEntry &L,
1493 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001494 // Sort entries related to non-local preemptible symbols by GOT indexes.
1495 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001496 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1497 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001498 if (LIsInLocalGot || RIsInLocalGot)
1499 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001500 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001501}
1502
George Rimarf45f6812017-05-16 08:53:30 +00001503void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001504 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001505
Rui Ueyama6e967342017-02-28 03:29:12 +00001506 // If it is a .dynsym, there should be no local symbols, but we need
1507 // to do a few things for the dynamic linker.
1508 if (this->Type == SHT_DYNSYM) {
1509 // Section's Info field has the index of the first non-local symbol.
1510 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001511 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001512
George Rimarf45f6812017-05-16 08:53:30 +00001513 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001514 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001515 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001516 } else if (Config->EMachine == EM_MIPS) {
1517 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1518 }
1519
1520 size_t I = 0;
1521 for (const SymbolTableEntry &S : Symbols)
1522 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001523 return;
Peter Smith55865432017-02-20 11:12:33 +00001524 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001525}
Peter Smith55865432017-02-20 11:12:33 +00001526
George Rimar0d6f30e2017-10-18 13:06:18 +00001527// The ELF spec requires that all local symbols precede global symbols, so we
1528// sort symbol entries in this function. (For .dynsym, we don't do that because
1529// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001530void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001531 if (this->Type == SHT_DYNSYM)
1532 return;
1533 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001534 auto It = std::stable_partition(
1535 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1536 return S.Symbol->isLocal() ||
1537 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1538 });
1539 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001540 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001541}
1542
George Rimarf45f6812017-05-16 08:53:30 +00001543void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001544 // Adding a local symbol to a .dynsym is a bug.
1545 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001546
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001547 bool HashIt = B->isLocal();
1548 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001549}
1550
George Rimarf45f6812017-05-16 08:53:30 +00001551size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
George Rimar5d6efd12017-09-27 09:08:53 +00001552 // Initializes symbol lookup tables lazily. This is used only
1553 // for -r or -emit-relocs.
1554 llvm::call_once(OnceFlag, [&] {
1555 SymbolIndexMap.reserve(Symbols.size());
1556 size_t I = 0;
1557 for (const SymbolTableEntry &E : Symbols) {
1558 if (E.Symbol->Type == STT_SECTION)
1559 SectionIndexMap[E.Symbol->getOutputSection()] = ++I;
1560 else
1561 SymbolIndexMap[E.Symbol] = ++I;
1562 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001563 });
George Rimar5d6efd12017-09-27 09:08:53 +00001564
1565 // Section symbols are mapped based on their output sections
1566 // to maintain their semantics.
1567 if (Body->Type == STT_SECTION)
1568 return SectionIndexMap.lookup(Body->getOutputSection());
1569 return SymbolIndexMap.lookup(Body);
George Rimar190bac52017-01-23 14:07:23 +00001570}
1571
George Rimarf45f6812017-05-16 08:53:30 +00001572template <class ELFT>
1573SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1574 : SymbolTableBaseSection(StrTabSec) {
1575 this->Entsize = sizeof(Elf_Sym);
1576}
1577
Rui Ueyama1f032532017-02-28 01:56:36 +00001578// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001579template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001580 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001581 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001582 Buf += sizeof(Elf_Sym);
1583
Eugene Leviant9230db92016-11-17 09:16:34 +00001584 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001585
Rui Ueyama1f032532017-02-28 01:56:36 +00001586 for (SymbolTableEntry &Ent : Symbols) {
1587 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001588
Rui Ueyama1b003182017-02-28 19:22:09 +00001589 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001590 ESym->st_other = 0;
Rui Ueyama1f032532017-02-28 01:56:36 +00001591 if (Body->isLocal()) {
1592 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1593 } else {
1594 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1595 ESym->setVisibility(Body->symbol()->Visibility);
1596 }
1597
1598 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001599
Rui Ueyama1b003182017-02-28 19:22:09 +00001600 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001601 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001602 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001603 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001604 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001605 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001606 ESym->st_shndx = SHN_COMMON;
George Rimar2727ce22017-10-06 09:56:24 +00001607 else
1608 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001609
George Rimardbe843d2017-06-28 09:51:33 +00001610 // Copy symbol size if it is a defined symbol. st_size is not significant
1611 // for undefined symbols, so whether copying it or not is up to us if that's
1612 // the case. We'll leave it as zero because by not setting a value, we can
1613 // get the exact same outputs for two sets of input files that differ only
1614 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001615 if (ESym->st_shndx == SHN_UNDEF)
1616 ESym->st_size = 0;
1617 else
George Rimardbe843d2017-06-28 09:51:33 +00001618 ESym->st_size = Body->getSize<ELFT>();
1619
Rui Ueyama1b003182017-02-28 19:22:09 +00001620 // st_value is usually an address of a symbol, but that has a
1621 // special meaining for uninstantiated common symbols (this can
1622 // occur if -r is given).
1623 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001624 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001625 else
George Rimarf64618a2017-03-17 11:56:54 +00001626 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001627
Rui Ueyama1f032532017-02-28 01:56:36 +00001628 ++ESym;
1629 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001630
Rui Ueyama1f032532017-02-28 01:56:36 +00001631 // On MIPS we need to mark symbol which has a PLT entry and requires
1632 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1633 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1634 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1635 if (Config->EMachine == EM_MIPS) {
1636 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1637
1638 for (SymbolTableEntry &Ent : Symbols) {
1639 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001640 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001641 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001642
1643 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001644 if (auto *D = dyn_cast<DefinedRegular>(Body))
1645 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001646 ESym->st_other |= STO_MIPS_PIC;
1647 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001648 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001649 }
1650}
1651
Rui Ueyamae4120632017-02-28 22:05:13 +00001652// .hash and .gnu.hash sections contain on-disk hash tables that map
1653// symbol names to their dynamic symbol table indices. Their purpose
1654// is to help the dynamic linker resolve symbols quickly. If ELF files
1655// don't have them, the dynamic linker has to do linear search on all
1656// dynamic symbols, which makes programs slower. Therefore, a .hash
1657// section is added to a DSO by default. A .gnu.hash is added if you
1658// give the -hash-style=gnu or -hash-style=both option.
1659//
1660// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1661// Each ELF file has a list of DSOs that the ELF file depends on and a
1662// list of dynamic symbols that need to be resolved from any of the
1663// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1664// where m is the number of DSOs and n is the number of dynamic
1665// symbols. For modern large programs, both m and n are large. So
1666// making each step faster by using hash tables substiantially
1667// improves time to load programs.
1668//
1669// (Note that this is not the only way to design the shared library.
1670// For instance, the Windows DLL takes a different approach. On
1671// Windows, each dynamic symbol has a name of DLL from which the symbol
1672// has to be resolved. That makes the cost of symbol resolution O(n).
1673// This disables some hacky techniques you can use on Unix such as
1674// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1675//
1676// Due to historical reasons, we have two different hash tables, .hash
1677// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1678// and better version of .hash. .hash is just an on-disk hash table, but
1679// .gnu.hash has a bloom filter in addition to a hash table to skip
1680// DSOs very quickly. If you are sure that your dynamic linker knows
1681// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1682// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001683GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001684 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1685}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001686
George Rimarf45f6812017-05-16 08:53:30 +00001687void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001688 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001689
1690 // Computes bloom filter size in word size. We want to allocate 8
1691 // bits for each symbol. It must be a power of two.
1692 if (Symbols.empty())
1693 MaskWords = 1;
1694 else
George Rimar5f73bc92017-03-29 15:23:28 +00001695 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001696
George Rimar5f73bc92017-03-29 15:23:28 +00001697 Size = 16; // Header
1698 Size += Config->Wordsize * MaskWords; // Bloom filter
1699 Size += NBuckets * 4; // Hash buckets
1700 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001701}
1702
George Rimarf45f6812017-05-16 08:53:30 +00001703void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001704 // Write a header.
Rui Ueyama79048e42017-10-27 03:59:34 +00001705 write32(Buf, NBuckets);
1706 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1707 write32(Buf + 8, MaskWords);
1708 write32(Buf + 12, getShift2());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001709 Buf += 16;
1710
Rui Ueyama7986b452017-03-01 18:09:09 +00001711 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001712 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001713 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001714 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001715}
1716
Rui Ueyama7986b452017-03-01 18:09:09 +00001717// This function writes a 2-bit bloom filter. This bloom filter alone
1718// usually filters out 80% or more of all symbol lookups [1].
1719// The dynamic linker uses the hash table only when a symbol is not
1720// filtered out by a bloom filter.
1721//
1722// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1723// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001724void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001725 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001726 for (const Entry &Sym : Symbols) {
1727 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001728 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1729 Val |= uint64_t(1) << (Sym.Hash % C);
1730 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1731 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001732 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001733}
1734
George Rimarf45f6812017-05-16 08:53:30 +00001735void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001736 // Group symbols by hash value.
1737 std::vector<std::vector<Entry>> Syms(NBuckets);
1738 for (const Entry &Ent : Symbols)
1739 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001740
Rui Ueyamae13373b2017-03-01 02:51:42 +00001741 // Write hash buckets. Hash buckets contain indices in the following
1742 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001743 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001744 for (size_t I = 0; I < NBuckets; ++I)
1745 if (!Syms[I].empty())
Rui Ueyama79048e42017-10-27 03:59:34 +00001746 write32(Buckets + I, Syms[I][0].Body->DynsymIndex);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001747
1748 // Write a hash value table. It represents a sequence of chains that
1749 // share the same hash modulo value. The last element of each chain
1750 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001751 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001752 size_t I = 0;
1753 for (std::vector<Entry> &Vec : Syms) {
1754 if (Vec.empty())
1755 continue;
1756 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
Rui Ueyama79048e42017-10-27 03:59:34 +00001757 write32(Values + I++, Ent.Hash & ~1);
1758 write32(Values + I++, Vec.back().Hash | 1);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001759 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001760}
1761
1762static uint32_t hashGnu(StringRef Name) {
1763 uint32_t H = 5381;
1764 for (uint8_t C : Name)
1765 H = (H << 5) + H + C;
1766 return H;
1767}
1768
Rui Ueyamae13373b2017-03-01 02:51:42 +00001769// Returns a number of hash buckets to accomodate given number of elements.
1770// We want to choose a moderate number that is not too small (which
1771// causes too many hash collisions) and not too large (which wastes
1772// disk space.)
1773//
1774// We return a prime number because it (is believed to) achieve good
1775// hash distribution.
1776static size_t getBucketSize(size_t NumSymbols) {
1777 // List of largest prime numbers that are not greater than 2^n + 1.
1778 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1779 251, 127, 61, 31, 13, 7, 3, 1})
1780 if (N <= NumSymbols)
1781 return N;
1782 return 0;
1783}
1784
Eugene Leviantbe809a72016-11-18 06:44:18 +00001785// Add symbols to this symbol hash table. Note that this function
1786// destructively sort a given vector -- which is needed because
1787// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001788void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001789 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1790 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001791 std::vector<SymbolTableEntry>::iterator Mid =
1792 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001793 // Shared symbols that this executable preempts are special. The dynamic
1794 // linker has to look them up, so they have to be in the hash table.
1795 if (auto *SS = dyn_cast<SharedSymbol>(S.Symbol))
1796 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
Rui Ueyamabda337a2017-10-27 22:54:16 +00001797 return !S.Symbol->isInCurrentOutput();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001798 });
1799 if (Mid == V.end())
1800 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001801
1802 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1803 SymbolBody *B = Ent.Symbol;
1804 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001805 }
1806
Rui Ueyamae13373b2017-03-01 02:51:42 +00001807 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001808 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001809 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001810 return L.Hash % NBuckets < R.Hash % NBuckets;
1811 });
1812
1813 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001814 for (const Entry &Ent : Symbols)
1815 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001816}
1817
George Rimaraaf54712017-09-27 09:14:59 +00001818HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001819 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1820 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001821}
1822
George Rimaraaf54712017-09-27 09:14:59 +00001823void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001824 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001825
George Rimar67c60722017-07-18 11:55:35 +00001826 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001827 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001828
1829 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001830 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001831 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001832}
1833
George Rimaraaf54712017-09-27 09:14:59 +00001834void HashTableSection::writeTo(uint8_t *Buf) {
George Rimar69b17c32017-05-16 10:04:42 +00001835 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001836
George Rimaraaf54712017-09-27 09:14:59 +00001837 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyama79048e42017-10-27 03:59:34 +00001838 write32(P++, NumSymbols); // nbucket
1839 write32(P++, NumSymbols); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001840
George Rimaraaf54712017-09-27 09:14:59 +00001841 uint32_t *Buckets = P;
1842 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001843
George Rimar69b17c32017-05-16 10:04:42 +00001844 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001845 SymbolBody *Body = S.Symbol;
1846 StringRef Name = Body->getName();
1847 unsigned I = Body->DynsymIndex;
1848 uint32_t Hash = hashSysV(Name) % NumSymbols;
1849 Chains[I] = Buckets[Hash];
Rui Ueyama79048e42017-10-27 03:59:34 +00001850 write32(Buckets + Hash, I);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001851 }
1852}
1853
George Rimardfc020e2017-03-17 11:01:57 +00001854PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001855 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001856 HeaderSize(S) {
1857 // The PLT needs to be writable on SPARC as the dynamic linker will
1858 // modify the instructions in the PLT entries.
1859 if (Config->EMachine == EM_SPARCV9)
1860 this->Flags |= SHF_WRITE;
1861}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001862
George Rimardfc020e2017-03-17 11:01:57 +00001863void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001864 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1865 // linker to resolve dynsyms at runtime. Write such code.
1866 if (HeaderSize != 0)
1867 Target->writePltHeader(Buf);
1868 size_t Off = HeaderSize;
1869 // The IPlt is immediately after the Plt, account for this in RelOff
1870 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001871
1872 for (auto &I : Entries) {
1873 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001874 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001875 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001876 uint64_t Plt = this->getVA() + Off;
1877 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1878 Off += Target->PltEntrySize;
1879 }
1880}
1881
George Rimardfc020e2017-03-17 11:01:57 +00001882template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001883 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001884 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1885 if (HeaderSize == 0) {
1886 PltRelocSection = In<ELFT>::RelaIplt;
1887 Sym.IsInIplt = true;
1888 }
1889 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001890 Entries.push_back(std::make_pair(&Sym, RelOff));
1891}
1892
George Rimardfc020e2017-03-17 11:01:57 +00001893size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001894 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001895}
1896
Peter Smith96943762017-01-25 10:31:16 +00001897// Some architectures such as additional symbols in the PLT section. For
1898// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001899void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001900 // The PLT may have symbols defined for the Header, the IPLT has no header
1901 if (HeaderSize != 0)
1902 Target->addPltHeaderSymbols(this);
1903 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001904 for (size_t I = 0; I < Entries.size(); ++I) {
1905 Target->addPltSymbols(this, Off);
1906 Off += Target->PltEntrySize;
1907 }
1908}
1909
George Rimardfc020e2017-03-17 11:01:57 +00001910unsigned PltSection::getPltRelocOff() const {
1911 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001912}
1913
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001914// The string hash function for .gdb_index.
1915static uint32_t computeGdbHash(StringRef S) {
1916 uint32_t H = 0;
1917 for (uint8_t C : S)
1918 H = H * 67 + tolower(C) - 113;
1919 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001920}
1921
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001922static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1923 std::vector<GdbIndexChunk::CuEntry> Ret;
1924 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1925 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001926 return Ret;
1927}
1928
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001929static std::vector<GdbIndexChunk::AddressEntry>
1930readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1931 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001932
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001933 uint32_t CuIdx = 0;
1934 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001935 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001936 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001937
George Rimar35e846e2017-03-21 08:19:34 +00001938 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001939 for (DWARFAddressRange &R : Ranges) {
1940 InputSectionBase *S = Sections[R.SectionIndex];
1941 if (!S || S == &InputSection::Discarded || !S->Live)
1942 continue;
1943 // Range list with zero size has no effect.
1944 if (R.LowPC == R.HighPC)
1945 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001946 auto *IS = cast<InputSection>(S);
1947 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001948 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001949 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001950 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001951 }
1952 return Ret;
1953}
1954
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001955static std::vector<GdbIndexChunk::NameTypeEntry>
1956readPubNamesAndTypes(DWARFContext &Dwarf) {
1957 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1958 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001959
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001960 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1961 for (StringRef Sec : {Sec1, Sec2}) {
1962 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001963 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1964 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1965 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1966 Ret.push_back({S, Ent.Descriptor.toBits()});
1967 }
1968 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001969 }
1970 return Ret;
1971}
1972
George Rimar86665622017-06-07 16:59:11 +00001973static std::vector<InputSection *> getDebugInfoSections() {
1974 std::vector<InputSection *> Ret;
1975 for (InputSectionBase *S : InputSections)
1976 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001977 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001978 Ret.push_back(IS);
1979 return Ret;
1980}
1981
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001982void GdbIndexSection::fixCuIndex() {
1983 uint32_t Idx = 0;
1984 for (GdbIndexChunk &Chunk : Chunks) {
1985 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1986 Ent.CuIndex += Idx;
1987 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00001988 }
1989}
1990
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001991std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
1992 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001993 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001994 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001995
1996 for (GdbIndexChunk &Chunk : Chunks) {
1997 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001998 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001999 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002000 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2001 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002002 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002003 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00002004
2005 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2006 // duplicate entries, so we want to dedup them.
2007 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2008 uint32_t Val = (Ent.Type << 24) | Idx;
2009 if (Vec.empty() || Vec.back() != Val)
2010 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002011 }
2012 Idx += Chunk.CompilationUnits.size();
2013 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002014
2015 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00002016 return Ret;
2017}
George Rimar8b547392016-12-15 09:08:13 +00002018
Rafael Espindola300b3862017-07-12 23:56:53 +00002019template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002020 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00002021 std::vector<InputSection *> Sections = getDebugInfoSections();
2022 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002023
George Rimar2d23da02017-08-01 14:57:13 +00002024 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002025 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2026 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2027
2028 Chunks[I].DebugInfoSec = Sections[I];
2029 Chunks[I].CompilationUnits = readCuList(Dwarf);
2030 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2031 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00002032 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002033
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00002034 // .debug_gnu_pub{names,types} are useless in executables.
2035 // They are present in input object files solely for creating
2036 // a .gdb_index. So we can remove it from the output.
2037 for (InputSectionBase *S : InputSections)
2038 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2039 S->Live = false;
2040
2041 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00002042 return make<GdbIndexSection>(std::move(Chunks));
2043}
2044
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002045static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002046 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002047 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00002048 Ret += D.CompilationUnits.size();
2049 return Ret;
2050}
George Rimarec02b8d2016-12-15 12:07:53 +00002051
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002052static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00002053 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00002054 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002055 Ret += D.AddressAreas.size();
2056 return Ret;
2057}
2058
2059std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002060 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2061 if (Size < 1024)
2062 Size = 1024;
2063
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002064 uint32_t Mask = Size - 1;
2065 std::vector<GdbSymbol *> Ret(Size);
2066
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002067 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002068 GdbSymbol *Sym = KV.second;
2069 uint32_t I = Sym->NameHash & Mask;
2070 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2071
2072 while (Ret[I])
2073 I = (I + Step) & Mask;
2074 Ret[I] = Sym;
2075 }
George Rimar86665622017-06-07 16:59:11 +00002076 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00002077}
2078
Rui Ueyama2b6631b2017-08-15 17:01:39 +00002079GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002080 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002081 fixCuIndex();
2082 CuVectors = createCuVectors();
2083 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00002084
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002085 // Compute offsets early to know the section size.
2086 // Each chunk size needs to be in sync with what we write in writeTo.
2087 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
2088 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
2089 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00002090
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002091 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002092 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002093 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002094 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00002095 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002096 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00002097}
2098
George Rimar35e846e2017-03-21 08:19:34 +00002099size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002100 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00002101}
2102
George Rimar35e846e2017-03-21 08:19:34 +00002103void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002104 // Write the section header.
2105 write32le(Buf, 7);
2106 write32le(Buf + 4, CuListOffset);
2107 write32le(Buf + 8, CuTypesOffset);
2108 write32le(Buf + 12, CuTypesOffset);
2109 write32le(Buf + 16, SymtabOffset);
2110 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00002111 Buf += 24;
2112
2113 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00002114 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002115 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00002116 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00002117 write64le(Buf + 8, Cu.CuLength);
2118 Buf += 16;
2119 }
Eugene Levianta113a412016-11-21 09:24:43 +00002120 }
George Rimar8b547392016-12-15 09:08:13 +00002121
2122 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00002123 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002124 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00002125 uint64_t BaseAddr =
2126 E.Section->getParent()->Addr + E.Section->getOffset(0);
2127 write64le(Buf, BaseAddr + E.LowAddress);
2128 write64le(Buf + 8, BaseAddr + E.HighAddress);
2129 write32le(Buf + 16, E.CuIndex);
2130 Buf += 20;
2131 }
George Rimar8b547392016-12-15 09:08:13 +00002132 }
George Rimarec02b8d2016-12-15 12:07:53 +00002133
2134 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002135 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00002136 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002137 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
2138 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00002139 }
2140 Buf += 8;
2141 }
2142
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002143 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002144 for (ArrayRef<uint32_t> Vec : CuVectors) {
2145 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00002146 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00002147 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00002148 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00002149 Buf += 4;
2150 }
2151 }
2152
Rui Ueyama9f4f4902017-09-24 21:45:35 +00002153 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002154 for (auto &KV : Symbols) {
2155 CachedHashStringRef S = KV.first;
2156 GdbSymbol *Sym = KV.second;
2157 size_t Off = Sym->NameOffset;
2158 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00002159 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00002160 }
Eugene Levianta113a412016-11-21 09:24:43 +00002161}
2162
George Rimar67c60722017-07-18 11:55:35 +00002163bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00002164
Rui Ueyama02551ab2017-10-27 03:14:24 +00002165EhFrameHeader::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002166 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002167
2168// .eh_frame_hdr contains a binary search table of pointers to FDEs.
2169// Each entry of the search table consists of two values,
2170// the starting PC from where FDEs covers, and the FDE's address.
2171// It is sorted by PC.
Rui Ueyama02551ab2017-10-27 03:14:24 +00002172void EhFrameHeader::writeTo(uint8_t *Buf) {
Rui Ueyama572247f2017-10-27 03:13:39 +00002173 typedef EhFrameSection::FdeData FdeData;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002174
Rui Ueyama02551ab2017-10-27 03:14:24 +00002175 std::vector<FdeData> Fdes = InX::EhFrame->getFdeData();
Rui Ueyamac0552252017-10-27 03:13:24 +00002176
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002177 // Sort the FDE list by their PC and uniqueify. Usually there is only
2178 // one FDE for a PC (i.e. function), but if ICF merges two functions
2179 // into one, there can be more than one FDEs pointing to the address.
2180 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
2181 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
2182 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
2183 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2184
2185 Buf[0] = 1;
2186 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2187 Buf[2] = DW_EH_PE_udata4;
2188 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rui Ueyama79048e42017-10-27 03:59:34 +00002189 write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4);
2190 write32(Buf + 8, Fdes.size());
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002191 Buf += 12;
2192
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002193 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002194 for (FdeData &Fde : Fdes) {
Rui Ueyama79048e42017-10-27 03:59:34 +00002195 write32(Buf, Fde.Pc - VA);
2196 write32(Buf + 4, Fde.FdeVA - VA);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002197 Buf += 8;
2198 }
2199}
2200
Rui Ueyama02551ab2017-10-27 03:14:24 +00002201size_t EhFrameHeader::getSize() const {
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002202 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rui Ueyama572247f2017-10-27 03:13:39 +00002203 return 12 + InX::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002204}
2205
Rui Ueyama02551ab2017-10-27 03:14:24 +00002206bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); }
George Rimar11992c862016-11-25 08:05:41 +00002207
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002208template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002209VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002210 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2211 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002212
2213static StringRef getFileDefName() {
2214 if (!Config->SoName.empty())
2215 return Config->SoName;
2216 return Config->OutputFile;
2217}
2218
Rui Ueyama945055a2017-02-27 03:07:41 +00002219template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002220 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002221 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002222 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002223
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002224 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002225
2226 // sh_info should be set to the number of definitions. This fact is missed in
2227 // documentation, but confirmed by binutils community:
2228 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002229 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002230}
2231
2232template <class ELFT>
2233void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2234 StringRef Name, size_t NameOff) {
2235 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2236 Verdef->vd_version = 1;
2237 Verdef->vd_cnt = 1;
2238 Verdef->vd_aux = sizeof(Elf_Verdef);
2239 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2240 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2241 Verdef->vd_ndx = Index;
2242 Verdef->vd_hash = hashSysV(Name);
2243
2244 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2245 Verdaux->vda_name = NameOff;
2246 Verdaux->vda_next = 0;
2247}
2248
2249template <class ELFT>
2250void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2251 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2252
2253 for (VersionDefinition &V : Config->VersionDefinitions) {
2254 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2255 writeOne(Buf, V.Id, V.Name, V.NameOff);
2256 }
2257
2258 // Need to terminate the last version definition.
2259 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2260 Verdef->vd_next = 0;
2261}
2262
2263template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2264 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2265}
2266
2267template <class ELFT>
2268VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002269 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002270 ".gnu.version") {
2271 this->Entsize = sizeof(Elf_Versym);
2272}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002273
Rui Ueyama945055a2017-02-27 03:07:41 +00002274template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002275 // At the moment of june 2016 GNU docs does not mention that sh_link field
2276 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002277 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002278}
2279
2280template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002281 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002282}
2283
2284template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2285 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002286 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002287 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2288 ++OutVersym;
2289 }
2290}
2291
George Rimar11992c862016-11-25 08:05:41 +00002292template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2293 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2294}
2295
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002296template <class ELFT>
2297VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002298 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2299 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002300 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2301 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2302 // First identifiers are reserved by verdef section if it exist.
2303 NextIndex = getVerDefNum() + 1;
2304}
2305
2306template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002307void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2308 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2309 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002310 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2311 return;
2312 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002313
Rafael Espindola6e93d052017-08-04 22:31:42 +00002314 SharedFile<ELFT> *File = SS->getFile<ELFT>();
Rui Ueyama4076fa12017-02-26 23:35:34 +00002315
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002316 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2317 // to create one by adding it to our needed list and creating a dynstr entry
2318 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002319 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002320 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002321 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002322 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2323 // prepare to create one by allocating a version identifier and creating a
2324 // dynstr entry for the version name.
2325 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002326 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2327 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002328 NV.Index = NextIndex++;
2329 }
2330 SS->symbol()->VersionId = NV.Index;
2331}
2332
2333template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2334 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2335 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2336 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2337
2338 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2339 // Create an Elf_Verneed for this DSO.
2340 Verneed->vn_version = 1;
2341 Verneed->vn_cnt = P.first->VerdefMap.size();
2342 Verneed->vn_file = P.second;
2343 Verneed->vn_aux =
2344 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2345 Verneed->vn_next = sizeof(Elf_Verneed);
2346 ++Verneed;
2347
2348 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2349 // VerdefMap, which will only contain references to needed version
2350 // definitions. Each Elf_Vernaux is based on the information contained in
2351 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2352 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2353 // data structures within a single input file.
2354 for (auto &NV : P.first->VerdefMap) {
2355 Vernaux->vna_hash = NV.first->vd_hash;
2356 Vernaux->vna_flags = 0;
2357 Vernaux->vna_other = NV.second.Index;
2358 Vernaux->vna_name = NV.second.StrTab;
2359 Vernaux->vna_next = sizeof(Elf_Vernaux);
2360 ++Vernaux;
2361 }
2362
2363 Vernaux[-1].vna_next = 0;
2364 }
2365 Verneed[-1].vn_next = 0;
2366}
2367
Rui Ueyama945055a2017-02-27 03:07:41 +00002368template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002369 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2370 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002371}
2372
2373template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2374 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2375 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2376 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2377 return Size;
2378}
2379
George Rimar11992c862016-11-25 08:05:41 +00002380template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2381 return getNeedNum() == 0;
2382}
2383
Rafael Espindola6119b862017-03-06 20:23:56 +00002384void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002385 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002386 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002387}
2388
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002389MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2390 uint64_t Flags, uint32_t Alignment)
2391 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2392 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002393
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002394size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2395
2396void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002397
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002398void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002399 // Add all string pieces to the string table builder to create section
2400 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002401 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002402 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2403 if (Sec->Pieces[I].Live)
2404 Builder.add(Sec->getData(I));
2405
2406 // Fix the string table content. After this, the contents will never change.
2407 Builder.finalize();
2408
2409 // finalize() fixed tail-optimized strings, so we can now get
2410 // offsets of strings. Get an offset for each string and save it
2411 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002412 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002413 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2414 if (Sec->Pieces[I].Live)
2415 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2416}
2417
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002418void MergeNoTailSection::writeTo(uint8_t *Buf) {
2419 for (size_t I = 0; I < NumShards; ++I)
2420 Shards[I].write(Buf + ShardOffsets[I]);
2421}
2422
2423// This function is very hot (i.e. it can take several seconds to finish)
2424// because sometimes the number of inputs is in an order of magnitude of
2425// millions. So, we use multi-threading.
2426//
2427// For any strings S and T, we know S is not mergeable with T if S's hash
2428// value is different from T's. If that's the case, we can safely put S and
2429// T into different string builders without worrying about merge misses.
2430// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002431void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002432 // Initializes string table builders.
2433 for (size_t I = 0; I < NumShards; ++I)
2434 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2435
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002436 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2437 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002438 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002439 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002440 Concurrency =
2441 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002442
2443 // Add section pieces to the builders.
2444 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2445 for (MergeInputSection *Sec : Sections) {
2446 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2447 if (!Sec->Pieces[I].Live)
2448 continue;
Rui Ueyama95bf5092017-10-21 23:20:13 +00002449 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002450 if ((ShardId & (Concurrency - 1)) == ThreadId)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002451 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002452 }
2453 }
2454 });
2455
2456 // Compute an in-section offset for each shard.
2457 size_t Off = 0;
2458 for (size_t I = 0; I < NumShards; ++I) {
2459 Shards[I].finalizeInOrder();
2460 if (Shards[I].getSize() > 0)
2461 Off = alignTo(Off, Alignment);
2462 ShardOffsets[I] = Off;
2463 Off += Shards[I].getSize();
2464 }
2465 Size = Off;
2466
2467 // So far, section pieces have offsets from beginning of shards, but
2468 // we want offsets from beginning of the whole section. Fix them.
2469 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002470 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2471 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002472 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002473 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002474 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002475}
2476
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002477static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2478 uint32_t Type,
2479 uint64_t Flags,
2480 uint32_t Alignment) {
2481 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2482 if (ShouldTailMerge)
2483 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2484 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002485}
2486
Rui Ueyama2b714b52017-10-11 03:12:53 +00002487// Debug sections may be compressed by zlib. Uncompress if exists.
2488void elf::decompressSections() {
2489 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2490 if (Sec->Live)
2491 Sec->maybeUncompress();
2492 });
2493}
2494
2495// This function scans over the inputsections to create mergeable
2496// synthetic sections.
2497//
2498// It removes MergeInputSections from the input section array and adds
2499// new synthetic sections at the location of the first input section
2500// that it replaces. It then finalizes each synthetic section in order
2501// to compute an output offset for each piece of each input section.
2502void elf::mergeSections() {
2503 // splitIntoPieces needs to be called on each MergeInputSection
2504 // before calling finalizeContents(). Do that first.
2505 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2506 if (Sec->Live)
2507 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2508 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002509 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002510
2511 std::vector<MergeSyntheticSection *> MergeSections;
2512 for (InputSectionBase *&S : InputSections) {
2513 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2514 if (!MS)
2515 continue;
2516
2517 // We do not want to handle sections that are not alive, so just remove
2518 // them instead of trying to merge.
2519 if (!MS->Live)
2520 continue;
2521
2522 StringRef OutsecName = getOutputSectionName(MS->Name);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002523 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2524
2525 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002526 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002527 Sec->Alignment == Alignment;
2528 });
2529 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002530 MergeSyntheticSection *Syn =
2531 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002532 MergeSections.push_back(Syn);
2533 I = std::prev(MergeSections.end());
2534 S = Syn;
2535 } else {
2536 S = nullptr;
2537 }
2538 (*I)->addSection(MS);
2539 }
2540 for (auto *MS : MergeSections)
2541 MS->finalizeContents();
2542
2543 std::vector<InputSectionBase *> &V = InputSections;
2544 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2545}
2546
George Rimar42886c42017-03-15 12:02:31 +00002547MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002548 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2549 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002550
George Rimar90a528b2017-03-21 09:01:39 +00002551ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002552 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002553 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002554
2555// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2556// This section will have been sorted last in the .ARM.exidx table.
2557// This table entry will have the form:
2558// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002559// The sentinel must have the PREL31 value of an address higher than any
2560// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002561void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002562 // The Sections are sorted in order of ascending PREL31 address with the
2563 // sentinel last. We need to find the InputSection that precedes the
2564 // sentinel. By construction the Sentinel is in the last
2565 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +00002566 OutputSection *C = getParent();
Rui Ueyama6b394ca2017-10-11 01:50:56 +00002567 auto ISD =
2568 std::find_if(C->SectionCommands.rbegin(), C->SectionCommands.rend(),
2569 [](const BaseCommand *Base) {
2570 return isa<InputSectionDescription>(Base);
2571 });
Peter Smithea79b212017-05-31 09:02:21 +00002572 auto L = cast<InputSectionDescription>(*ISD);
2573 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002574 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002575 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002576 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002577 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
Rui Ueyama79048e42017-10-27 03:59:34 +00002578 write32le(Buf + 4, 1);
Peter Smith719eb8e2016-11-24 11:43:55 +00002579}
2580
George Rimar7b827042017-03-16 10:40:50 +00002581ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002582 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002583 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002584 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002585 this->OutSecOff = Off;
2586}
2587
George Rimar7b827042017-03-16 10:40:50 +00002588void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002589 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002590 T->Offset = Off;
2591 Thunks.push_back(T);
2592 T->addSymbols(*this);
2593 Size = Off + T->size();
2594}
2595
George Rimar7b827042017-03-16 10:40:50 +00002596void ThunkSection::writeTo(uint8_t *Buf) {
2597 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002598 T->writeTo(Buf + T->Offset, *this);
2599}
2600
George Rimar7b827042017-03-16 10:40:50 +00002601InputSection *ThunkSection::getTargetInputSection() const {
Peter Smithf0c70f82017-10-27 08:58:28 +00002602 if (Thunks.empty())
2603 return nullptr;
George Rimar7b827042017-03-16 10:40:50 +00002604 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002605 return T->getTargetInputSection();
2606}
2607
George Rimar9782ca52017-03-15 15:29:29 +00002608InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002609BssSection *InX::Bss;
2610BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002611BuildIdSection *InX::BuildId;
Rui Ueyama02551ab2017-10-27 03:14:24 +00002612EhFrameHeader *InX::EhFrameHdr;
Rui Ueyama572247f2017-10-27 03:13:39 +00002613EhFrameSection *InX::EhFrame;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002614SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002615StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002616SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002617InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002618GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002619GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002620GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002621GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002622HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002623IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002624MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002625MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002626PltSection *InX::Plt;
2627PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002628StringTableSection *InX::ShStrTab;
2629StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002630SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002631
Rafael Espindola300b3862017-07-12 23:56:53 +00002632template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2633template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2634template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2635template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2636
Rui Ueyama572247f2017-10-27 03:13:39 +00002637template void EhFrameSection::addSection<ELF32LE>(InputSectionBase *);
2638template void EhFrameSection::addSection<ELF32BE>(InputSectionBase *);
2639template void EhFrameSection::addSection<ELF64LE>(InputSectionBase *);
2640template void EhFrameSection::addSection<ELF64BE>(InputSectionBase *);
2641
George Rimara9189572017-03-17 16:50:07 +00002642template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2643template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2644template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2645template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2646
Ben Dunbobbin73eabf22017-09-29 09:08:26 +00002647template void elf::createCommonSections<ELF32LE>();
2648template void elf::createCommonSections<ELF32BE>();
2649template void elf::createCommonSections<ELF64LE>();
2650template void elf::createCommonSections<ELF64BE>();
2651
Rafael Espindola6119b862017-03-06 20:23:56 +00002652template MergeInputSection *elf::createCommentSection<ELF32LE>();
2653template MergeInputSection *elf::createCommentSection<ELF32BE>();
2654template MergeInputSection *elf::createCommentSection<ELF64LE>();
2655template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002656
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002657template class elf::MipsAbiFlagsSection<ELF32LE>;
2658template class elf::MipsAbiFlagsSection<ELF32BE>;
2659template class elf::MipsAbiFlagsSection<ELF64LE>;
2660template class elf::MipsAbiFlagsSection<ELF64BE>;
2661
Simon Atanasyance02cf02016-11-09 21:36:56 +00002662template class elf::MipsOptionsSection<ELF32LE>;
2663template class elf::MipsOptionsSection<ELF32BE>;
2664template class elf::MipsOptionsSection<ELF64LE>;
2665template class elf::MipsOptionsSection<ELF64BE>;
2666
2667template class elf::MipsReginfoSection<ELF32LE>;
2668template class elf::MipsReginfoSection<ELF32BE>;
2669template class elf::MipsReginfoSection<ELF64LE>;
2670template class elf::MipsReginfoSection<ELF64BE>;
2671
Eugene Leviant6380ce22016-11-15 12:26:55 +00002672template class elf::DynamicSection<ELF32LE>;
2673template class elf::DynamicSection<ELF32BE>;
2674template class elf::DynamicSection<ELF64LE>;
2675template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002676
2677template class elf::RelocationSection<ELF32LE>;
2678template class elf::RelocationSection<ELF32BE>;
2679template class elf::RelocationSection<ELF64LE>;
2680template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002681
Peter Collingbourne5c54f152017-10-27 17:49:40 +00002682template class elf::AndroidPackedRelocationSection<ELF32LE>;
2683template class elf::AndroidPackedRelocationSection<ELF32BE>;
2684template class elf::AndroidPackedRelocationSection<ELF64LE>;
2685template class elf::AndroidPackedRelocationSection<ELF64BE>;
2686
Eugene Leviant9230db92016-11-17 09:16:34 +00002687template class elf::SymbolTableSection<ELF32LE>;
2688template class elf::SymbolTableSection<ELF32BE>;
2689template class elf::SymbolTableSection<ELF64LE>;
2690template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002691
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002692template class elf::VersionTableSection<ELF32LE>;
2693template class elf::VersionTableSection<ELF32BE>;
2694template class elf::VersionTableSection<ELF64LE>;
2695template class elf::VersionTableSection<ELF64BE>;
2696
2697template class elf::VersionNeedSection<ELF32LE>;
2698template class elf::VersionNeedSection<ELF32BE>;
2699template class elf::VersionNeedSection<ELF64LE>;
2700template class elf::VersionNeedSection<ELF64BE>;
2701
2702template class elf::VersionDefinitionSection<ELF32LE>;
2703template class elf::VersionDefinitionSection<ELF32BE>;
2704template class elf::VersionDefinitionSection<ELF64LE>;
2705template class elf::VersionDefinitionSection<ELF64BE>;