blob: bd3549ae30739fb1ffddf671fde4d1136cd1dacc [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"
18#include "Config.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000019#include "InputFiles.h"
Eugene Leviant17b7a572016-11-22 17:49:14 +000020#include "LinkerScript.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000021#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000022#include "OutputSections.h"
23#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000024#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000025#include "Target.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000026#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000027#include "lld/Common/ErrorHandler.h"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000028#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000029#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000031#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000032#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000033#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000034#include "llvm/Support/Endian.h"
35#include "llvm/Support/MD5.h"
36#include "llvm/Support/RandomNumberGenerator.h"
37#include "llvm/Support/SHA1.h"
38#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000039#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000040#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000041
42using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000043using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000044using namespace llvm::ELF;
45using namespace llvm::object;
46using namespace llvm::support;
47using namespace llvm::support::endian;
48
49using namespace lld;
50using namespace lld::elf;
51
NAKAMURA Takumi70947e22017-09-30 13:40:22 +000052constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000053
Rui Ueyama9320cb02017-02-27 02:56:02 +000054uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000055 if (OutputSection *Sec = getParent())
56 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000057 return 0;
58}
59
Rui Ueyama0fda1d72017-10-06 04:32:08 +000060// Create a .bss section for each common symbol and replace the common symbol
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000061// with a DefinedRegular symbol.
62template <class ELFT> void elf::createCommonSections() {
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000063 for (Symbol *S : Symtab->getSymbols()) {
64 auto *Sym = dyn_cast<DefinedCommon>(S->body());
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000065
66 if (!Sym)
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000067 continue;
George Rimar176d6062017-03-17 13:31:07 +000068
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000069 // Create a synthetic section for the common data.
Rui Ueyama732f4e22017-10-04 00:21:17 +000070 auto *Section = make<BssSection>("COMMON", Sym->Size, Sym->Alignment);
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000071 Section->File = Sym->getFile();
72 Section->Live = !Config->GcSections;
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000073 InputSections.push_back(Section);
74
75 // Replace all DefinedCommon symbols with DefinedRegular symbols so that we
76 // don't have to care about DefinedCommon symbols beyond this point.
77 replaceBody<DefinedRegular>(S, Sym->getFile(), Sym->getName(),
Rui Ueyama662bb002017-10-13 03:37:26 +000078 static_cast<bool>(Sym->isLocal()), Sym->StOther,
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000079 Sym->Type, 0, Sym->getSize<ELFT>(), Section);
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000080 }
Rui Ueyamae8a61022016-11-05 23:05:47 +000081}
82
Rui Ueyama3da3f062016-11-10 20:20:37 +000083// Returns an LLD version string.
84static ArrayRef<uint8_t> getVersion() {
85 // Check LLD_VERSION first for ease of testing.
86 // You can get consitent output by using the environment variable.
87 // This is only for testing.
88 StringRef S = getenv("LLD_VERSION");
89 if (S.empty())
90 S = Saver.save(Twine("Linker: ") + getLLDVersion());
91
92 // +1 to include the terminating '\0'.
93 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000094}
Rui Ueyama3da3f062016-11-10 20:20:37 +000095
96// Creates a .comment section containing LLD version info.
97// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000098// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000099// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000100template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000101 typename ELFT::Shdr Hdr = {};
102 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
103 Hdr.sh_type = SHT_PROGBITS;
104 Hdr.sh_entsize = 1;
105 Hdr.sh_addralign = 1;
106
Rafael Espindola6119b862017-03-06 20:23:56 +0000107 auto *Ret =
Rui Ueyama709fb2bb12017-07-26 22:13:32 +0000108 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000109 Ret->Data = getVersion();
Rui Ueyama3da3f062016-11-10 20:20:37 +0000110 return Ret;
111}
112
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000113// .MIPS.abiflags section.
114template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000115MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000116 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000117 Flags(Flags) {
118 this->Entsize = sizeof(Elf_Mips_ABIFlags);
119}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000120
121template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
122 memcpy(Buf, &Flags, sizeof(Flags));
123}
124
125template <class ELFT>
126MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
127 Elf_Mips_ABIFlags Flags = {};
128 bool Create = false;
129
Rui Ueyama536a2672017-02-27 02:32:08 +0000130 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000131 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000132 continue;
133 Sec->Live = false;
134 Create = true;
135
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000136 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000137 const size_t Size = Sec->Data.size();
138 // Older version of BFD (such as the default FreeBSD linker) concatenate
139 // .MIPS.abiflags instead of merging. To allow for this case (or potential
140 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
141 if (Size < sizeof(Elf_Mips_ABIFlags)) {
142 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
143 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000144 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000145 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000146 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000147 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000148 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000149 Twine(S->version));
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
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000153 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000154 // select the highest number of ISA/Rev/Ext.
155 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
156 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
157 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
158 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
159 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
160 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
161 Flags.ases |= S->ases;
162 Flags.flags1 |= S->flags1;
163 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000164 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000165 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000166
Rui Ueyama12f2da82016-11-22 03:57:06 +0000167 if (Create)
168 return make<MipsAbiFlagsSection<ELFT>>(Flags);
169 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000170}
171
Simon Atanasyance02cf02016-11-09 21:36:56 +0000172// .MIPS.options section.
173template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000174MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000175 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000176 Reginfo(Reginfo) {
177 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
178}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000179
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000180template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
181 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
182 Options->kind = ODK_REGINFO;
183 Options->size = getSize();
184
185 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000186 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000187 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000188}
189
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000190template <class ELFT>
191MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
192 // N64 ABI only.
193 if (!ELFT::Is64Bits)
194 return nullptr;
195
196 Elf_Mips_RegInfo Reginfo = {};
197 bool Create = false;
198
Rui Ueyama536a2672017-02-27 02:32:08 +0000199 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000200 if (Sec->Type != SHT_MIPS_OPTIONS)
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000201 continue;
202 Sec->Live = false;
203 Create = true;
204
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000205 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000206 ArrayRef<uint8_t> D = Sec->Data;
207
208 while (!D.empty()) {
209 if (D.size() < sizeof(Elf_Mips_Options)) {
210 error(Filename + ": invalid size of .MIPS.options section");
211 break;
212 }
213
214 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
215 if (Opt->kind == ODK_REGINFO) {
216 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
217 error(Filename + ": unsupported non-zero ri_gp_value");
218 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000219 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000220 break;
221 }
222
223 if (!Opt->size)
224 fatal(Filename + ": zero option descriptor size");
225 D = D.slice(Opt->size);
226 }
227 };
228
229 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000230 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000231 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000232}
233
234// MIPS .reginfo section.
235template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000236MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000237 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000238 Reginfo(Reginfo) {
239 this->Entsize = sizeof(Elf_Mips_RegInfo);
240}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000241
Rui Ueyamab71cae92016-11-22 03:57:08 +0000242template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000243 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000244 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000245 memcpy(Buf, &Reginfo, sizeof(Reginfo));
246}
247
248template <class ELFT>
249MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
250 // Section should be alive for O32 and N32 ABIs only.
251 if (ELFT::Is64Bits)
252 return nullptr;
253
254 Elf_Mips_RegInfo Reginfo = {};
255 bool Create = false;
256
Rui Ueyama536a2672017-02-27 02:32:08 +0000257 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000258 if (Sec->Type != SHT_MIPS_REGINFO)
Rui Ueyamab71cae92016-11-22 03:57:08 +0000259 continue;
260 Sec->Live = false;
261 Create = true;
262
263 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000264 error(toString(Sec->getFile<ELFT>()) +
265 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000266 return nullptr;
267 }
268 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
269 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000270 error(toString(Sec->getFile<ELFT>()) +
271 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000272
273 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000274 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000275 };
276
277 if (Create)
278 return make<MipsReginfoSection<ELFT>>(Reginfo);
279 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000280}
281
Rui Ueyama3255a522017-02-27 02:32:49 +0000282InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000283 // StringSaver guarantees that the returned string ends with '\0'.
284 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000285 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
286
287 auto *Sec =
288 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
289 Sec->Live = true;
290 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000291}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000292
Rui Ueyama65316d72017-02-23 03:15:57 +0000293SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
294 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000295 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
Rafael Espindola6e93d052017-08-04 22:31:42 +0000296 Value, Size, Section);
George Rimar69b17c32017-05-16 10:04:42 +0000297 if (InX::SymTab)
298 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000299 return S;
300}
301
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000302static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000303 switch (Config->BuildId) {
304 case BuildIdKind::Fast:
305 return 8;
306 case BuildIdKind::Md5:
307 case BuildIdKind::Uuid:
308 return 16;
309 case BuildIdKind::Sha1:
310 return 20;
311 case BuildIdKind::Hexstring:
312 return Config->BuildIdVector.size();
313 default:
314 llvm_unreachable("unknown BuildIdKind");
315 }
316}
317
George Rimar6c2949d2017-03-20 16:40:21 +0000318BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000319 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000320 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000321
George Rimar6c2949d2017-03-20 16:40:21 +0000322void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000323 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000324 write32(Buf, 4, E); // Name size
325 write32(Buf + 4, HashSize, E); // Content size
326 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000327 memcpy(Buf + 12, "GNU", 4); // Name string
328 HashBuf = Buf + 16;
329}
330
Rui Ueyama35e00752016-11-10 00:12:28 +0000331// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000332static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
333 size_t ChunkSize) {
334 std::vector<ArrayRef<uint8_t>> Ret;
335 while (Arr.size() > ChunkSize) {
336 Ret.push_back(Arr.take_front(ChunkSize));
337 Arr = Arr.drop_front(ChunkSize);
338 }
339 if (!Arr.empty())
340 Ret.push_back(Arr);
341 return Ret;
342}
343
Rui Ueyama35e00752016-11-10 00:12:28 +0000344// Computes a hash value of Data using a given hash function.
345// In order to utilize multiple cores, we first split data into 1MB
346// chunks, compute a hash for each chunk, and then compute a hash value
347// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000348void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000349 llvm::ArrayRef<uint8_t> Data,
350 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000351 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000352 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000353
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000354 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000355 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000356 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
357 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000358
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000359 // Write to the final output buffer.
360 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000361}
362
Rui Ueyama732f4e22017-10-04 00:21:17 +0000363BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
364 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000365 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000366 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000367 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000368}
Peter Smithebfe9942017-02-09 10:27:57 +0000369
George Rimar6c2949d2017-03-20 16:40:21 +0000370void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000371 switch (Config->BuildId) {
372 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000373 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000374 write64le(Dest, xxHash64(toStringRef(Arr)));
375 });
376 break;
377 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000378 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000379 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000380 });
381 break;
382 case BuildIdKind::Sha1:
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, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000385 });
386 break;
387 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000388 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000389 error("entropy source failure");
390 break;
391 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000392 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000393 break;
394 default:
395 llvm_unreachable("unknown BuildIdKind");
396 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000397}
398
Eugene Leviant41ca3272016-11-10 09:48:29 +0000399template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000400EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000401 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000402
403// Search for an existing CIE record or create a new one.
404// CIE records from input object files are uniquified by their contents
405// and where their relocations point to.
406template <class ELFT>
407template <class RelTy>
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000408CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Cie,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000409 ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000410 auto *Sec = cast<EhInputSection>(Cie.Sec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000411 const endianness E = ELFT::TargetEndianness;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000412 if (read32<E>(Cie.data().data() + 4) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000413 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
414
415 SymbolBody *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000416 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000417 if (FirstRelI != (unsigned)-1)
418 Personality =
419 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
420
421 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000422 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000423
424 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000425 if (!Rec) {
426 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000427 Rec->Cie = &Cie;
428 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000429 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000430 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000431}
432
433// There is one FDE per function. Returns true if a given FDE
434// points to a live function.
435template <class ELFT>
436template <class RelTy>
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000437bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Fde,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000438 ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000439 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000440 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000441
442 // An FDE should point to some function because FDEs are to describe
443 // functions. That's however not always the case due to an issue of
444 // ld.gold with -r. ld.gold may discard only functions and leave their
445 // corresponding FDEs, which results in creating bad .eh_frame sections.
446 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000447 if (FirstRelI == (unsigned)-1)
448 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000449
Rafael Espindola66b4e212017-02-23 22:06:28 +0000450 const RelTy &Rel = Rels[FirstRelI];
451 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama27a357c2017-09-18 19:15:54 +0000452 if (auto *D = dyn_cast<DefinedRegular>(&B))
453 if (D->Section)
454 return cast<InputSectionBase>(D->Section)->Repl->Live;
455 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000456}
457
458// .eh_frame is a sequence of CIE or FDE records. In general, there
459// is one CIE record per input object file which is followed by
460// a list of FDEs. This function searches an existing CIE or create a new
461// one and associates FDEs to the CIE.
462template <class ELFT>
463template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000464void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000465 ArrayRef<RelTy> Rels) {
466 const endianness E = ELFT::TargetEndianness;
467
468 DenseMap<size_t, CieRecord *> OffsetToCie;
469 for (EhSectionPiece &Piece : Sec->Pieces) {
470 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000471 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000472 return;
473
474 size_t Offset = Piece.InputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000475 uint32_t ID = read32<E>(Piece.data().data() + 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000476 if (ID == 0) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000477 OffsetToCie[Offset] = addCie(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000478 continue;
479 }
480
481 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000482 CieRecord *Rec = OffsetToCie[CieOffset];
483 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000484 fatal(toString(Sec) + ": invalid CIE reference");
485
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000486 if (!isFdeLive(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000487 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000488 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000489 NumFdes++;
490 }
491}
492
493template <class ELFT>
494void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000495 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000496 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000497
498 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000499 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000500
Petr Hosek7b793212017-03-10 20:00:42 +0000501 for (auto *DS : Sec->DependentSections)
502 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000503
504 // .eh_frame is a sequence of CIE or FDE records. This function
505 // splits it into pieces so that we can call
506 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000507 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000508 if (Sec->Pieces.empty())
509 return;
510
Rui Ueyamafaa38022017-09-19 20:28:03 +0000511 if (Sec->NumRelocations == 0)
512 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
513 else if (Sec->AreRelocsRela)
514 addSectionAux(Sec, Sec->template relas<ELFT>());
515 else
516 addSectionAux(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000517}
518
519template <class ELFT>
520static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
521 memcpy(Buf, D.data(), D.size());
522
Andrew Ng6dee7362017-09-07 08:43:56 +0000523 size_t Aligned = alignTo(D.size(), sizeof(typename ELFT::uint));
524
525 // Zero-clear trailing padding if it exists.
526 memset(Buf + D.size(), 0, Aligned - D.size());
527
Rafael Espindola66b4e212017-02-23 22:06:28 +0000528 // Fix the size field. -4 since size does not include the size field itself.
529 const endianness E = ELFT::TargetEndianness;
Andrew Ng6dee7362017-09-07 08:43:56 +0000530 write32<E>(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000531}
532
Rui Ueyama945055a2017-02-27 03:07:41 +0000533template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000534 if (this->Size)
535 return; // Already finalized.
536
537 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000538 for (CieRecord *Rec : CieRecords) {
539 Rec->Cie->OutputOff = Off;
540 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000541
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000542 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000543 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000544 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000545 }
546 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000547
548 // The LSB standard does not allow a .eh_frame section with zero
549 // Call Frame Information records. Therefore add a CIE record length
550 // 0 as a terminator if this .eh_frame section is empty.
551 if (Off == 0)
552 Off = 4;
553
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000554 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000555}
556
557template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
558 const endianness E = ELFT::TargetEndianness;
559 switch (Size) {
560 case DW_EH_PE_udata2:
561 return read16<E>(Buf);
562 case DW_EH_PE_udata4:
563 return read32<E>(Buf);
564 case DW_EH_PE_udata8:
565 return read64<E>(Buf);
566 case DW_EH_PE_absptr:
567 if (ELFT::Is64Bits)
568 return read64<E>(Buf);
569 return read32<E>(Buf);
570 }
571 fatal("unknown FDE size encoding");
572}
573
574// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
575// We need it to create .eh_frame_hdr section.
576template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000577uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
578 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000579 // The starting address to which this FDE applies is
580 // stored at FDE + 8 byte.
581 size_t Off = FdeOff + 8;
582 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
583 if ((Enc & 0x70) == DW_EH_PE_absptr)
584 return Addr;
585 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000586 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000587 fatal("unknown FDE size relative encoding");
588}
589
590template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
591 const endianness E = ELFT::TargetEndianness;
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000592
593 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000594 for (CieRecord *Rec : CieRecords) {
595 size_t CieOffset = Rec->Cie->OutputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000596 writeCieFde<ELFT>(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000597
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000598 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000599 size_t Off = Fde->OutputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000600 writeCieFde<ELFT>(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000601
602 // FDE's second word should have the offset to an associated CIE.
603 // Write it.
604 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
605 }
606 }
607
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000608 // Apply relocations. .eh_frame section contents are not contiguous
609 // in the output buffer, but relocateAlloc() still works because
610 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000611 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000612 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000613
614 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
615 // to get a FDE from an address to which FDE is applied. So here
616 // we obtain two addresses and pass them to EhFrameHdr object.
617 if (In<ELFT>::EhFrameHdr) {
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000618 for (CieRecord *Rec : CieRecords) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000619 uint8_t Enc = getFdeEncoding<ELFT>(Rec->Cie);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000620 for (EhSectionPiece *Fde : Rec->Fdes) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000621 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000622 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000623 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
624 }
625 }
626 }
627}
628
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000629GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000630 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
631 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000632
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000633void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000634 Sym.GotIndex = NumEntries;
635 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000636}
637
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000638bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000639 if (Sym.GlobalDynIndex != -1U)
640 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000641 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000642 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000643 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000644 return true;
645}
646
647// Reserves TLS entries for a TLS module ID and a TLS block offset.
648// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000649bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000650 if (TlsIndexOff != uint32_t(-1))
651 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000652 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000653 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000654 return true;
655}
656
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000657uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000658 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000659}
660
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000661uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000662 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000663}
664
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000665void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000666
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000667bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000668 // We need to emit a GOT even if it's empty if there's a relocation that is
669 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
670 // (i.e. _GLOBAL_OFFSET_TABLE_).
671 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
George Rimar11992c862016-11-25 08:05:41 +0000672}
673
Igor Kudrin202a9f62017-07-14 08:10:45 +0000674void GotSection::writeTo(uint8_t *Buf) {
675 // Buf points to the start of this section's buffer,
676 // whereas InputSectionBase::relocateAlloc() expects its argument
677 // to point to the start of the output section.
678 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
679}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000680
George Rimar14534eb2017-03-20 16:44:28 +0000681MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000682 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
683 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000684
George Rimar14534eb2017-03-20 16:44:28 +0000685void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000686 // For "true" local symbols which can be referenced from the same module
687 // only compiler creates two instructions for address loading:
688 //
689 // lw $8, 0($gp) # R_MIPS_GOT16
690 // addi $8, $8, 0 # R_MIPS_LO16
691 //
692 // The first instruction loads high 16 bits of the symbol address while
693 // the second adds an offset. That allows to reduce number of required
694 // GOT entries because only one global offset table entry is necessary
695 // for every 64 KBytes of local data. So for local symbols we need to
696 // allocate number of GOT entries to hold all required "page" addresses.
697 //
698 // All global symbols (hidden and regular) considered by compiler uniformly.
699 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
700 // to load address of the symbol. So for each such symbol we need to
701 // allocate dedicated GOT entry to store its address.
702 //
703 // If a symbol is preemptible we need help of dynamic linker to get its
704 // final address. The corresponding GOT entries are allocated in the
705 // "global" part of GOT. Entries for non preemptible global symbol allocated
706 // in the "local" part of GOT.
707 //
708 // See "Global Offset Table" in Chapter 5:
709 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
710 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
711 // At this point we do not know final symbol value so to reduce number
712 // of allocated GOT entries do the following trick. Save all output
713 // sections referenced by GOT relocations. Then later in the `finalize`
714 // method calculate number of "pages" required to cover all saved output
715 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000716 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000717 return;
718 }
719 if (Sym.isTls()) {
720 // GOT entries created for MIPS TLS relocations behave like
721 // almost GOT entries from other ABIs. They go to the end
722 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000723 Sym.GotIndex = TlsEntries.size();
724 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000725 return;
726 }
George Rimar14534eb2017-03-20 16:44:28 +0000727 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000728 if (S.isInGot() && !A)
729 return;
730 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000731 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000732 return;
733 Items.emplace_back(&S, A);
734 if (!A)
735 S.GotIndex = NewIndex;
736 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000737 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000738 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000739 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000740 Sym.IsInGlobalMipsGot = true;
741 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000742 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000743 Sym.Is32BitMipsGot = true;
744 } else {
745 // Hold local GOT entries accessed via a 16-bit index separately.
746 // That allows to write them in the beginning of the GOT and keep
747 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000748 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000749 }
750}
751
George Rimar14534eb2017-03-20 16:44:28 +0000752bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000753 if (Sym.GlobalDynIndex != -1U)
754 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000755 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000756 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000757 TlsEntries.push_back(nullptr);
758 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000759 return true;
760}
761
762// Reserves TLS entries for a TLS module ID and a TLS block offset.
763// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000764bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000765 if (TlsIndexOff != uint32_t(-1))
766 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000767 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000768 TlsEntries.push_back(nullptr);
769 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000770 return true;
771}
772
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000773static uint64_t getMipsPageAddr(uint64_t Addr) {
774 return (Addr + 0x8000) & ~0xffff;
775}
776
777static uint64_t getMipsPageCount(uint64_t Size) {
778 return (Size + 0xfffe) / 0xffff + 1;
779}
780
George Rimar14534eb2017-03-20 16:44:28 +0000781uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
782 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000783 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000784 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
785 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
786 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000787 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000788 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000789}
790
George Rimar14534eb2017-03-20 16:44:28 +0000791uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
792 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000793 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000794 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000795 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000796 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000797 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000798 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000799 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000800 Index += LocalEntries.size();
801 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000802 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000803 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000805 auto It = EntryIndexMap.find({&B, Addend});
806 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000807 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000808 }
George Rimar14534eb2017-03-20 16:44:28 +0000809 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000810}
811
George Rimar14534eb2017-03-20 16:44:28 +0000812uint64_t MipsGotSection::getTlsOffset() const {
813 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000814}
815
George Rimar14534eb2017-03-20 16:44:28 +0000816uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
817 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000818}
819
George Rimar14534eb2017-03-20 16:44:28 +0000820const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000821 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000822}
823
George Rimar14534eb2017-03-20 16:44:28 +0000824unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000825 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
826 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000827}
828
George Rimar67c60722017-07-18 11:55:35 +0000829void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000830
George Rimar14534eb2017-03-20 16:44:28 +0000831void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000832 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000833 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000834 // For each output section referenced by GOT page relocations calculate
835 // and save into PageIndexMap an upper bound of MIPS GOT entries required
836 // to store page addresses of local symbols. We assume the worst case -
837 // each 64kb page of the output section has at least one GOT relocation
838 // against it. And take in account the case when the section intersects
839 // page boundaries.
840 P.second = PageEntriesNum;
841 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000842 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000843 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000844 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000845}
846
George Rimar14534eb2017-03-20 16:44:28 +0000847bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000848 // We add the .got section to the result for dynamic MIPS target because
849 // its address and properties are mentioned in the .dynamic section.
850 return Config->Relocatable;
851}
852
George Rimar67c60722017-07-18 11:55:35 +0000853uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000854
George Rimar5f73bc92017-03-29 15:23:28 +0000855static uint64_t readUint(uint8_t *Buf) {
856 if (Config->Is64)
857 return read64(Buf, Config->Endianness);
858 return read32(Buf, Config->Endianness);
859}
860
George Rimar14534eb2017-03-20 16:44:28 +0000861static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000862 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000863 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000864 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000865 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000866}
867
George Rimar14534eb2017-03-20 16:44:28 +0000868void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000869 // Set the MSB of the second GOT slot. This is not required by any
870 // MIPS ABI documentation, though.
871 //
872 // There is a comment in glibc saying that "The MSB of got[1] of a
873 // gnu object is set to identify gnu objects," and in GNU gold it
874 // says "the second entry will be used by some runtime loaders".
875 // But how this field is being used is unclear.
876 //
877 // We are not really willing to mimic other linkers behaviors
878 // without understanding why they do that, but because all files
879 // generated by GNU tools have this special GOT value, and because
880 // we've been doing this for years, it is probably a safe bet to
881 // keep doing this for now. We really need to revisit this to see
882 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000883 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
884 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000885 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000886 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000887 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000888 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000889 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000890 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
891 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000892 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000893 }
George Rimar14534eb2017-03-20 16:44:28 +0000894 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000895 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000896 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000897 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000898 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000899 uint64_t VA = Body->getVA(SA.second);
900 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000901 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000902 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
903 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
904 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000905 // Initialize TLS-related GOT entries. If the entry has a corresponding
906 // dynamic relocations, leave it initialized by zero. Write down adjusted
907 // TLS symbol's values otherwise. To calculate the adjustments use offsets
908 // for thread-local storage.
909 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000910 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000911 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000912 for (const SymbolBody *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000913 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000914 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000915 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000916 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000917 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
918 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000919 }
920 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000921 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
922 writeUint(Entry, 1);
923 Entry += Config->Wordsize;
924 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000925 }
926 }
927}
928
George Rimar10f74fc2017-03-15 09:12:56 +0000929GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000930 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
931 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000932
George Rimar10f74fc2017-03-15 09:12:56 +0000933void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000934 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
935 Entries.push_back(&Sym);
936}
937
George Rimar10f74fc2017-03-15 09:12:56 +0000938size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000939 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
940 Target->GotPltEntrySize;
941}
942
George Rimar10f74fc2017-03-15 09:12:56 +0000943void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000944 Target->writeGotPltHeader(Buf);
945 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
946 for (const SymbolBody *B : Entries) {
947 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000948 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000949 }
950}
951
Peter Smithbaffdb82016-12-08 12:58:55 +0000952// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
953// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000954IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000955 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
956 Target->GotPltEntrySize,
957 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000958
George Rimar10f74fc2017-03-15 09:12:56 +0000959void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000960 Sym.IsInIgot = true;
961 Sym.GotPltIndex = Entries.size();
962 Entries.push_back(&Sym);
963}
964
George Rimar10f74fc2017-03-15 09:12:56 +0000965size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000966 return Entries.size() * Target->GotPltEntrySize;
967}
968
George Rimar10f74fc2017-03-15 09:12:56 +0000969void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000970 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000971 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000972 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000973 }
974}
975
George Rimar49648002017-03-15 09:32:36 +0000976StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
977 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000978 Dynamic(Dynamic) {
979 // ELF string tables start with a NUL byte.
980 addString("");
981}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000982
983// Adds a string to the string table. If HashIt is true we hash and check for
984// duplicates. It is optional because the name of global symbols are already
985// uniqued and hashing them again has a big cost for a small value: uniquing
986// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000987unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000988 if (HashIt) {
989 auto R = StringMap.insert(std::make_pair(S, this->Size));
990 if (!R.second)
991 return R.first->second;
992 }
993 unsigned Ret = this->Size;
994 this->Size = this->Size + S.size() + 1;
995 Strings.push_back(S);
996 return Ret;
997}
998
George Rimar49648002017-03-15 09:32:36 +0000999void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +00001000 for (StringRef S : Strings) {
1001 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +00001002 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +00001003 Buf += S.size() + 1;
1004 }
1005}
1006
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001007// Returns the number of version definition entries. Because the first entry
1008// is for the version definition itself, it is the number of versioned symbols
1009// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001010static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1011
1012template <class ELFT>
1013DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001014 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001015 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001016 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001017
Petr Hosekffa786f2017-05-26 19:12:38 +00001018 // .dynamic section is not writable on MIPS and on Fuchsia OS
1019 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001020 // See "Special Section" in Chapter 4 in the following document:
1021 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001022 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001023 this->Flags = SHF_ALLOC;
1024
1025 addEntries();
1026}
1027
1028// There are some dynamic entries that don't depend on other sections.
1029// Such entries can be set early.
1030template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1031 // Add strings to .dynstr early so that .dynstr's size will be
1032 // fixed early.
George Rimarf525c922017-07-17 09:43:18 +00001033 for (StringRef S : Config->FilterList)
1034 add({DT_FILTER, InX::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001035 for (StringRef S : Config->AuxiliaryList)
Rafael Espindola895aea62017-05-11 22:02:41 +00001036 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001037 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001038 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001039 InX::DynStrTab->addString(Config->Rpath)});
George Rimar696a7f92017-09-19 09:20:54 +00001040 for (InputFile *File : SharedFiles) {
1041 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001042 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001043 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
George Rimar696a7f92017-09-19 09:20:54 +00001044 }
Eugene Leviant6380ce22016-11-15 12:26:55 +00001045 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001046 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001047
1048 // Set DT_FLAGS and DT_FLAGS_1.
1049 uint32_t DtFlags = 0;
1050 uint32_t DtFlags1 = 0;
1051 if (Config->Bsymbolic)
1052 DtFlags |= DF_SYMBOLIC;
1053 if (Config->ZNodelete)
1054 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001055 if (Config->ZNodlopen)
1056 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001057 if (Config->ZNow) {
1058 DtFlags |= DF_BIND_NOW;
1059 DtFlags1 |= DF_1_NOW;
1060 }
1061 if (Config->ZOrigin) {
1062 DtFlags |= DF_ORIGIN;
1063 DtFlags1 |= DF_1_ORIGIN;
1064 }
1065
1066 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001067 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001068 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001069 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001070
Petr Hosekffa786f2017-05-26 19:12:38 +00001071 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1072 // need it for each process, so we don't write it for DSOs. The loader writes
1073 // the pointer into this entry.
1074 //
1075 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1076 // systems (currently only Fuchsia OS) provide other means to give the
1077 // debugger this information. Such systems may choose make .dynamic read-only.
1078 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1079 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001080 add({DT_DEBUG, (uint64_t)0});
1081}
1082
1083// Add remaining entries to complete .dynamic contents.
1084template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1085 if (this->Size)
1086 return; // Already finalized.
1087
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001088 this->Link = InX::DynStrTab->getParent()->SectionIndex;
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001089 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001090 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001091 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001092 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent(),
1093 Entry::SecSize});
Rui Ueyama729ac792016-11-17 04:10:09 +00001094 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001095 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001096
1097 // MIPS dynamic loader does not support RELCOUNT tag.
1098 // The problem is in the tight relation between dynamic
1099 // relocations and GOT. So do not emit this tag on MIPS.
1100 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001101 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001102 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001103 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001104 }
1105 }
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001106 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001107 add({DT_JMPREL, In<ELFT>::RelaPlt});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001108 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent(), Entry::SecSize});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001109 switch (Config->EMachine) {
1110 case EM_MIPS:
1111 add({DT_MIPS_PLTGOT, In<ELFT>::GotPlt});
1112 break;
1113 case EM_SPARCV9:
1114 add({DT_PLTGOT, In<ELFT>::Plt});
1115 break;
1116 default:
1117 add({DT_PLTGOT, In<ELFT>::GotPlt});
1118 break;
1119 }
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001120 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001121 }
1122
George Rimar69b17c32017-05-16 10:04:42 +00001123 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001124 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001125 add({DT_STRTAB, InX::DynStrTab});
1126 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001127 if (!Config->ZText)
1128 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001129 if (InX::GnuHashTab)
1130 add({DT_GNU_HASH, InX::GnuHashTab});
George Rimaraaf54712017-09-27 09:14:59 +00001131 if (InX::HashTab)
1132 add({DT_HASH, InX::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001133
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001134 if (Out::PreinitArray) {
1135 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1136 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001137 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001138 if (Out::InitArray) {
1139 add({DT_INIT_ARRAY, Out::InitArray});
1140 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001141 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001142 if (Out::FiniArray) {
1143 add({DT_FINI_ARRAY, Out::FiniArray});
1144 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001145 }
1146
Rui Ueyama43099e42017-08-15 16:03:11 +00001147 if (SymbolBody *B = Symtab->find(Config->Init))
1148 if (B->isInCurrentDSO())
1149 add({DT_INIT, B});
1150 if (SymbolBody *B = Symtab->find(Config->Fini))
1151 if (B->isInCurrentDSO())
1152 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001153
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001154 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1155 if (HasVerNeed || In<ELFT>::VerDef)
1156 add({DT_VERSYM, In<ELFT>::VerSym});
1157 if (In<ELFT>::VerDef) {
1158 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001159 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001160 }
1161 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001162 add({DT_VERNEED, In<ELFT>::VerNeed});
1163 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001164 }
1165
1166 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001167 add({DT_MIPS_RLD_VERSION, 1});
1168 add({DT_MIPS_FLAGS, RHF_NOTPOT});
James Hendersonb5ca92e2017-10-10 10:09:35 +00001169 add({DT_MIPS_BASE_ADDRESS, Target->getImageBase()});
George Rimar69b17c32017-05-16 10:04:42 +00001170 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001171 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1172 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001173 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001174 else
George Rimar69b17c32017-05-16 10:04:42 +00001175 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001176 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001177 if (InX::MipsRldMap)
1178 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001179 }
1180
George Rimar8f3a6c82017-10-06 10:06:13 +00001181 add({DT_NULL, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001182
George Rimar8f3a6c82017-10-06 10:06:13 +00001183 getParent()->Link = this->Link;
1184 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001185}
1186
1187template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1188 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1189
1190 for (const Entry &E : Entries) {
1191 P->d_tag = E.Tag;
1192 switch (E.Kind) {
1193 case Entry::SecAddr:
1194 P->d_un.d_ptr = E.OutSec->Addr;
1195 break;
1196 case Entry::InSecAddr:
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001197 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001198 break;
1199 case Entry::SecSize:
1200 P->d_un.d_val = E.OutSec->Size;
1201 break;
1202 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001203 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001204 break;
1205 case Entry::PlainInt:
1206 P->d_un.d_val = E.Val;
1207 break;
1208 }
1209 ++P;
1210 }
1211}
1212
George Rimar97def8c2017-03-17 12:07:44 +00001213uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001214 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001215}
1216
George Rimar97def8c2017-03-17 12:07:44 +00001217int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001218 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001219 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001220 return Addend;
1221}
1222
George Rimar97def8c2017-03-17 12:07:44 +00001223uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001224 if (Sym && !UseSymVA)
1225 return Sym->DynsymIndex;
1226 return 0;
1227}
1228
1229template <class ELFT>
1230RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001231 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001232 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001233 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001234 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001235}
1236
1237template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001238void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001239 if (Reloc.Type == Target->RelativeRel)
1240 ++NumRelativeRelocs;
1241 Relocs.push_back(Reloc);
1242}
1243
1244template <class ELFT, class RelTy>
1245static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001246 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1247 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001248 if (AIsRel != BIsRel)
1249 return AIsRel;
1250
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001251 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001252}
1253
1254template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1255 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001256 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001257 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001258 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001259
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001260 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001261 P->r_addend = Rel.getAddend();
1262 P->r_offset = Rel.getOffset();
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001263 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001264 // Dynamic relocation against MIPS GOT section make deal TLS entries
1265 // allocated in the end of the GOT. We need to adjust the offset to take
1266 // in account 'local' and 'global' GOT entries.
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001267 P->r_offset += InX::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001268 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001269 }
1270
1271 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001272 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001273 std::stable_sort((Elf_Rela *)BufBegin,
1274 (Elf_Rela *)BufBegin + Relocs.size(),
1275 compRelocations<ELFT, Elf_Rela>);
1276 else
1277 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1278 compRelocations<ELFT, Elf_Rel>);
1279 }
1280}
1281
1282template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1283 return this->Entsize * Relocs.size();
1284}
1285
Rui Ueyama945055a2017-02-27 03:07:41 +00001286template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Rafael Espindola49419bb2017-10-12 15:05:04 +00001287 // If all relocations are *RELATIVE they don't refer to any
1288 // dynamic symbol and we don't need a dynamic symbol table. If that
1289 // is the case, just use 0 as the link.
1290 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Eugene Levianta96d9022016-11-16 10:02:27 +00001291
1292 // Set required output section properties.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001293 getParent()->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001294}
1295
George Rimarf45f6812017-05-16 08:53:30 +00001296SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001297 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001298 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001299 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001300 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001301 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001302
1303// Orders symbols according to their positions in the GOT,
1304// in compliance with MIPS ABI rules.
1305// See "Global Offset Table" in Chapter 5 in the following document
1306// for detailed description:
1307// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001308static bool sortMipsSymbols(const SymbolTableEntry &L,
1309 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001310 // Sort entries related to non-local preemptible symbols by GOT indexes.
1311 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001312 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1313 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001314 if (LIsInLocalGot || RIsInLocalGot)
1315 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001316 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001317}
1318
George Rimarf45f6812017-05-16 08:53:30 +00001319void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001320 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001321
Rui Ueyama6e967342017-02-28 03:29:12 +00001322 // If it is a .dynsym, there should be no local symbols, but we need
1323 // to do a few things for the dynamic linker.
1324 if (this->Type == SHT_DYNSYM) {
1325 // Section's Info field has the index of the first non-local symbol.
1326 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001327 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001328
George Rimarf45f6812017-05-16 08:53:30 +00001329 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001330 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001331 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001332 } else if (Config->EMachine == EM_MIPS) {
1333 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1334 }
1335
1336 size_t I = 0;
1337 for (const SymbolTableEntry &S : Symbols)
1338 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001339 return;
Peter Smith55865432017-02-20 11:12:33 +00001340 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001341}
Peter Smith55865432017-02-20 11:12:33 +00001342
George Rimar0d6f30e2017-10-18 13:06:18 +00001343// The ELF spec requires that all local symbols precede global symbols, so we
1344// sort symbol entries in this function. (For .dynsym, we don't do that because
1345// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001346void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001347 if (this->Type == SHT_DYNSYM)
1348 return;
1349 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001350 auto It = std::stable_partition(
1351 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1352 return S.Symbol->isLocal() ||
1353 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1354 });
1355 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001356 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001357}
1358
George Rimarf45f6812017-05-16 08:53:30 +00001359void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001360 // Adding a local symbol to a .dynsym is a bug.
1361 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001362
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001363 bool HashIt = B->isLocal();
1364 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001365}
1366
George Rimarf45f6812017-05-16 08:53:30 +00001367size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
George Rimar5d6efd12017-09-27 09:08:53 +00001368 // Initializes symbol lookup tables lazily. This is used only
1369 // for -r or -emit-relocs.
1370 llvm::call_once(OnceFlag, [&] {
1371 SymbolIndexMap.reserve(Symbols.size());
1372 size_t I = 0;
1373 for (const SymbolTableEntry &E : Symbols) {
1374 if (E.Symbol->Type == STT_SECTION)
1375 SectionIndexMap[E.Symbol->getOutputSection()] = ++I;
1376 else
1377 SymbolIndexMap[E.Symbol] = ++I;
1378 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001379 });
George Rimar5d6efd12017-09-27 09:08:53 +00001380
1381 // Section symbols are mapped based on their output sections
1382 // to maintain their semantics.
1383 if (Body->Type == STT_SECTION)
1384 return SectionIndexMap.lookup(Body->getOutputSection());
1385 return SymbolIndexMap.lookup(Body);
George Rimar190bac52017-01-23 14:07:23 +00001386}
1387
George Rimarf45f6812017-05-16 08:53:30 +00001388template <class ELFT>
1389SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1390 : SymbolTableBaseSection(StrTabSec) {
1391 this->Entsize = sizeof(Elf_Sym);
1392}
1393
Rui Ueyama1f032532017-02-28 01:56:36 +00001394// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001395template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001396 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001397 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001398 Buf += sizeof(Elf_Sym);
1399
Eugene Leviant9230db92016-11-17 09:16:34 +00001400 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001401
Rui Ueyama1f032532017-02-28 01:56:36 +00001402 for (SymbolTableEntry &Ent : Symbols) {
1403 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001404
Rui Ueyama1b003182017-02-28 19:22:09 +00001405 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001406 ESym->st_other = 0;
Rui Ueyama1f032532017-02-28 01:56:36 +00001407 if (Body->isLocal()) {
1408 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1409 } else {
1410 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1411 ESym->setVisibility(Body->symbol()->Visibility);
1412 }
1413
1414 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001415
Rui Ueyama1b003182017-02-28 19:22:09 +00001416 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001417 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001418 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001419 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001420 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001421 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001422 ESym->st_shndx = SHN_COMMON;
George Rimar2727ce22017-10-06 09:56:24 +00001423 else
1424 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001425
George Rimardbe843d2017-06-28 09:51:33 +00001426 // Copy symbol size if it is a defined symbol. st_size is not significant
1427 // for undefined symbols, so whether copying it or not is up to us if that's
1428 // the case. We'll leave it as zero because by not setting a value, we can
1429 // get the exact same outputs for two sets of input files that differ only
1430 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001431 if (ESym->st_shndx == SHN_UNDEF)
1432 ESym->st_size = 0;
1433 else
George Rimardbe843d2017-06-28 09:51:33 +00001434 ESym->st_size = Body->getSize<ELFT>();
1435
Rui Ueyama1b003182017-02-28 19:22:09 +00001436 // st_value is usually an address of a symbol, but that has a
1437 // special meaining for uninstantiated common symbols (this can
1438 // occur if -r is given).
1439 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001440 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001441 else
George Rimarf64618a2017-03-17 11:56:54 +00001442 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001443
Rui Ueyama1f032532017-02-28 01:56:36 +00001444 ++ESym;
1445 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001446
Rui Ueyama1f032532017-02-28 01:56:36 +00001447 // On MIPS we need to mark symbol which has a PLT entry and requires
1448 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1449 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1450 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1451 if (Config->EMachine == EM_MIPS) {
1452 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1453
1454 for (SymbolTableEntry &Ent : Symbols) {
1455 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001456 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001457 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001458
1459 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001460 if (auto *D = dyn_cast<DefinedRegular>(Body))
1461 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001462 ESym->st_other |= STO_MIPS_PIC;
1463 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001464 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001465 }
1466}
1467
Rui Ueyamae4120632017-02-28 22:05:13 +00001468// .hash and .gnu.hash sections contain on-disk hash tables that map
1469// symbol names to their dynamic symbol table indices. Their purpose
1470// is to help the dynamic linker resolve symbols quickly. If ELF files
1471// don't have them, the dynamic linker has to do linear search on all
1472// dynamic symbols, which makes programs slower. Therefore, a .hash
1473// section is added to a DSO by default. A .gnu.hash is added if you
1474// give the -hash-style=gnu or -hash-style=both option.
1475//
1476// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1477// Each ELF file has a list of DSOs that the ELF file depends on and a
1478// list of dynamic symbols that need to be resolved from any of the
1479// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1480// where m is the number of DSOs and n is the number of dynamic
1481// symbols. For modern large programs, both m and n are large. So
1482// making each step faster by using hash tables substiantially
1483// improves time to load programs.
1484//
1485// (Note that this is not the only way to design the shared library.
1486// For instance, the Windows DLL takes a different approach. On
1487// Windows, each dynamic symbol has a name of DLL from which the symbol
1488// has to be resolved. That makes the cost of symbol resolution O(n).
1489// This disables some hacky techniques you can use on Unix such as
1490// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1491//
1492// Due to historical reasons, we have two different hash tables, .hash
1493// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1494// and better version of .hash. .hash is just an on-disk hash table, but
1495// .gnu.hash has a bloom filter in addition to a hash table to skip
1496// DSOs very quickly. If you are sure that your dynamic linker knows
1497// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1498// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001499GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001500 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1501}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001502
George Rimarf45f6812017-05-16 08:53:30 +00001503void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001504 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001505
1506 // Computes bloom filter size in word size. We want to allocate 8
1507 // bits for each symbol. It must be a power of two.
1508 if (Symbols.empty())
1509 MaskWords = 1;
1510 else
George Rimar5f73bc92017-03-29 15:23:28 +00001511 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001512
George Rimar5f73bc92017-03-29 15:23:28 +00001513 Size = 16; // Header
1514 Size += Config->Wordsize * MaskWords; // Bloom filter
1515 Size += NBuckets * 4; // Hash buckets
1516 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001517}
1518
George Rimarf45f6812017-05-16 08:53:30 +00001519void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001520 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001521 write32(Buf, NBuckets, Config->Endianness);
George Rimarf45f6812017-05-16 08:53:30 +00001522 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
George Rimar5f73bc92017-03-29 15:23:28 +00001523 Config->Endianness);
1524 write32(Buf + 8, MaskWords, Config->Endianness);
1525 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001526 Buf += 16;
1527
Rui Ueyama7986b452017-03-01 18:09:09 +00001528 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001529 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001530 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001531 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001532}
1533
Rui Ueyama7986b452017-03-01 18:09:09 +00001534// This function writes a 2-bit bloom filter. This bloom filter alone
1535// usually filters out 80% or more of all symbol lookups [1].
1536// The dynamic linker uses the hash table only when a symbol is not
1537// filtered out by a bloom filter.
1538//
1539// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1540// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001541void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001542 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001543 for (const Entry &Sym : Symbols) {
1544 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001545 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1546 Val |= uint64_t(1) << (Sym.Hash % C);
1547 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1548 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001549 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001550}
1551
George Rimarf45f6812017-05-16 08:53:30 +00001552void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001553 // Group symbols by hash value.
1554 std::vector<std::vector<Entry>> Syms(NBuckets);
1555 for (const Entry &Ent : Symbols)
1556 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001557
Rui Ueyamae13373b2017-03-01 02:51:42 +00001558 // Write hash buckets. Hash buckets contain indices in the following
1559 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001560 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001561 for (size_t I = 0; I < NBuckets; ++I)
1562 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001563 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001564
1565 // Write a hash value table. It represents a sequence of chains that
1566 // share the same hash modulo value. The last element of each chain
1567 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001568 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001569 size_t I = 0;
1570 for (std::vector<Entry> &Vec : Syms) {
1571 if (Vec.empty())
1572 continue;
1573 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001574 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1575 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001576 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001577}
1578
1579static uint32_t hashGnu(StringRef Name) {
1580 uint32_t H = 5381;
1581 for (uint8_t C : Name)
1582 H = (H << 5) + H + C;
1583 return H;
1584}
1585
Rui Ueyamae13373b2017-03-01 02:51:42 +00001586// Returns a number of hash buckets to accomodate given number of elements.
1587// We want to choose a moderate number that is not too small (which
1588// causes too many hash collisions) and not too large (which wastes
1589// disk space.)
1590//
1591// We return a prime number because it (is believed to) achieve good
1592// hash distribution.
1593static size_t getBucketSize(size_t NumSymbols) {
1594 // List of largest prime numbers that are not greater than 2^n + 1.
1595 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1596 251, 127, 61, 31, 13, 7, 3, 1})
1597 if (N <= NumSymbols)
1598 return N;
1599 return 0;
1600}
1601
Eugene Leviantbe809a72016-11-18 06:44:18 +00001602// Add symbols to this symbol hash table. Note that this function
1603// destructively sort a given vector -- which is needed because
1604// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001605void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001606 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1607 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001608 std::vector<SymbolTableEntry>::iterator Mid =
1609 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001610 // Shared symbols that this executable preempts are special. The dynamic
1611 // linker has to look them up, so they have to be in the hash table.
1612 if (auto *SS = dyn_cast<SharedSymbol>(S.Symbol))
1613 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
1614 return !S.Symbol->isInCurrentDSO();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001615 });
1616 if (Mid == V.end())
1617 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001618
1619 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1620 SymbolBody *B = Ent.Symbol;
1621 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001622 }
1623
Rui Ueyamae13373b2017-03-01 02:51:42 +00001624 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001625 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001626 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001627 return L.Hash % NBuckets < R.Hash % NBuckets;
1628 });
1629
1630 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001631 for (const Entry &Ent : Symbols)
1632 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001633}
1634
George Rimaraaf54712017-09-27 09:14:59 +00001635HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001636 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1637 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001638}
1639
George Rimaraaf54712017-09-27 09:14:59 +00001640void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001641 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001642
George Rimar67c60722017-07-18 11:55:35 +00001643 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001644 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001645
1646 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001647 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001648 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001649}
1650
George Rimaraaf54712017-09-27 09:14:59 +00001651void HashTableSection::writeTo(uint8_t *Buf) {
George Rimar69b17c32017-05-16 10:04:42 +00001652 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001653
George Rimaraaf54712017-09-27 09:14:59 +00001654 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
1655 write32(P++, NumSymbols, Config->Endianness); // nbucket
1656 write32(P++, NumSymbols, Config->Endianness); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001657
George Rimaraaf54712017-09-27 09:14:59 +00001658 uint32_t *Buckets = P;
1659 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001660
George Rimar69b17c32017-05-16 10:04:42 +00001661 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001662 SymbolBody *Body = S.Symbol;
1663 StringRef Name = Body->getName();
1664 unsigned I = Body->DynsymIndex;
1665 uint32_t Hash = hashSysV(Name) % NumSymbols;
1666 Chains[I] = Buckets[Hash];
George Rimaraaf54712017-09-27 09:14:59 +00001667 write32(Buckets + Hash, I, Config->Endianness);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001668 }
1669}
1670
George Rimardfc020e2017-03-17 11:01:57 +00001671PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001672 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001673 HeaderSize(S) {
1674 // The PLT needs to be writable on SPARC as the dynamic linker will
1675 // modify the instructions in the PLT entries.
1676 if (Config->EMachine == EM_SPARCV9)
1677 this->Flags |= SHF_WRITE;
1678}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001679
George Rimardfc020e2017-03-17 11:01:57 +00001680void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001681 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1682 // linker to resolve dynsyms at runtime. Write such code.
1683 if (HeaderSize != 0)
1684 Target->writePltHeader(Buf);
1685 size_t Off = HeaderSize;
1686 // The IPlt is immediately after the Plt, account for this in RelOff
1687 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001688
1689 for (auto &I : Entries) {
1690 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001691 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001692 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001693 uint64_t Plt = this->getVA() + Off;
1694 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1695 Off += Target->PltEntrySize;
1696 }
1697}
1698
George Rimardfc020e2017-03-17 11:01:57 +00001699template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001700 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001701 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1702 if (HeaderSize == 0) {
1703 PltRelocSection = In<ELFT>::RelaIplt;
1704 Sym.IsInIplt = true;
1705 }
1706 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001707 Entries.push_back(std::make_pair(&Sym, RelOff));
1708}
1709
George Rimardfc020e2017-03-17 11:01:57 +00001710size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001711 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001712}
1713
Peter Smith96943762017-01-25 10:31:16 +00001714// Some architectures such as additional symbols in the PLT section. For
1715// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001716void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001717 // The PLT may have symbols defined for the Header, the IPLT has no header
1718 if (HeaderSize != 0)
1719 Target->addPltHeaderSymbols(this);
1720 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001721 for (size_t I = 0; I < Entries.size(); ++I) {
1722 Target->addPltSymbols(this, Off);
1723 Off += Target->PltEntrySize;
1724 }
1725}
1726
George Rimardfc020e2017-03-17 11:01:57 +00001727unsigned PltSection::getPltRelocOff() const {
1728 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001729}
1730
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001731// The string hash function for .gdb_index.
1732static uint32_t computeGdbHash(StringRef S) {
1733 uint32_t H = 0;
1734 for (uint8_t C : S)
1735 H = H * 67 + tolower(C) - 113;
1736 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001737}
1738
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001739static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1740 std::vector<GdbIndexChunk::CuEntry> Ret;
1741 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1742 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001743 return Ret;
1744}
1745
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001746static std::vector<GdbIndexChunk::AddressEntry>
1747readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1748 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001749
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001750 uint32_t CuIdx = 0;
1751 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001752 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001753 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001754
George Rimar35e846e2017-03-21 08:19:34 +00001755 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001756 for (DWARFAddressRange &R : Ranges) {
1757 InputSectionBase *S = Sections[R.SectionIndex];
1758 if (!S || S == &InputSection::Discarded || !S->Live)
1759 continue;
1760 // Range list with zero size has no effect.
1761 if (R.LowPC == R.HighPC)
1762 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001763 auto *IS = cast<InputSection>(S);
1764 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001765 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001766 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001767 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001768 }
1769 return Ret;
1770}
1771
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001772static std::vector<GdbIndexChunk::NameTypeEntry>
1773readPubNamesAndTypes(DWARFContext &Dwarf) {
1774 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1775 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001776
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001777 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1778 for (StringRef Sec : {Sec1, Sec2}) {
1779 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001780 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1781 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1782 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1783 Ret.push_back({S, Ent.Descriptor.toBits()});
1784 }
1785 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001786 }
1787 return Ret;
1788}
1789
George Rimar86665622017-06-07 16:59:11 +00001790static std::vector<InputSection *> getDebugInfoSections() {
1791 std::vector<InputSection *> Ret;
1792 for (InputSectionBase *S : InputSections)
1793 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001794 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001795 Ret.push_back(IS);
1796 return Ret;
1797}
1798
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001799void GdbIndexSection::fixCuIndex() {
1800 uint32_t Idx = 0;
1801 for (GdbIndexChunk &Chunk : Chunks) {
1802 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1803 Ent.CuIndex += Idx;
1804 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00001805 }
1806}
1807
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001808std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
1809 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001810 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001811 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001812
1813 for (GdbIndexChunk &Chunk : Chunks) {
1814 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001815 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001816 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001817 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
1818 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001819 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001820 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00001821
1822 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
1823 // duplicate entries, so we want to dedup them.
1824 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
1825 uint32_t Val = (Ent.Type << 24) | Idx;
1826 if (Vec.empty() || Vec.back() != Val)
1827 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001828 }
1829 Idx += Chunk.CompilationUnits.size();
1830 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001831
1832 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00001833 return Ret;
1834}
George Rimar8b547392016-12-15 09:08:13 +00001835
Rafael Espindola300b3862017-07-12 23:56:53 +00001836template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00001837 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00001838 std::vector<InputSection *> Sections = getDebugInfoSections();
1839 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001840
George Rimar2d23da02017-08-01 14:57:13 +00001841 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001842 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
1843 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
1844
1845 Chunks[I].DebugInfoSec = Sections[I];
1846 Chunks[I].CompilationUnits = readCuList(Dwarf);
1847 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
1848 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00001849 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001850
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00001851 // .debug_gnu_pub{names,types} are useless in executables.
1852 // They are present in input object files solely for creating
1853 // a .gdb_index. So we can remove it from the output.
1854 for (InputSectionBase *S : InputSections)
1855 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
1856 S->Live = false;
1857
1858 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00001859 return make<GdbIndexSection>(std::move(Chunks));
1860}
1861
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001862static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001863 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001864 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00001865 Ret += D.CompilationUnits.size();
1866 return Ret;
1867}
George Rimarec02b8d2016-12-15 12:07:53 +00001868
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001869static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001870 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001871 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001872 Ret += D.AddressAreas.size();
1873 return Ret;
1874}
1875
1876std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001877 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
1878 if (Size < 1024)
1879 Size = 1024;
1880
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001881 uint32_t Mask = Size - 1;
1882 std::vector<GdbSymbol *> Ret(Size);
1883
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001884 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001885 GdbSymbol *Sym = KV.second;
1886 uint32_t I = Sym->NameHash & Mask;
1887 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
1888
1889 while (Ret[I])
1890 I = (I + Step) & Mask;
1891 Ret[I] = Sym;
1892 }
George Rimar86665622017-06-07 16:59:11 +00001893 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00001894}
1895
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001896GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001897 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001898 fixCuIndex();
1899 CuVectors = createCuVectors();
1900 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00001901
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001902 // Compute offsets early to know the section size.
1903 // Each chunk size needs to be in sync with what we write in writeTo.
1904 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
1905 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
1906 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00001907
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001908 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001909 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001910 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001911 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00001912 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001913 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00001914}
1915
George Rimar35e846e2017-03-21 08:19:34 +00001916size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001917 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00001918}
1919
George Rimar35e846e2017-03-21 08:19:34 +00001920void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001921 // Write the section header.
1922 write32le(Buf, 7);
1923 write32le(Buf + 4, CuListOffset);
1924 write32le(Buf + 8, CuTypesOffset);
1925 write32le(Buf + 12, CuTypesOffset);
1926 write32le(Buf + 16, SymtabOffset);
1927 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00001928 Buf += 24;
1929
1930 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00001931 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001932 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00001933 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00001934 write64le(Buf + 8, Cu.CuLength);
1935 Buf += 16;
1936 }
Eugene Levianta113a412016-11-21 09:24:43 +00001937 }
George Rimar8b547392016-12-15 09:08:13 +00001938
1939 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00001940 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001941 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00001942 uint64_t BaseAddr =
1943 E.Section->getParent()->Addr + E.Section->getOffset(0);
1944 write64le(Buf, BaseAddr + E.LowAddress);
1945 write64le(Buf + 8, BaseAddr + E.HighAddress);
1946 write32le(Buf + 16, E.CuIndex);
1947 Buf += 20;
1948 }
George Rimar8b547392016-12-15 09:08:13 +00001949 }
George Rimarec02b8d2016-12-15 12:07:53 +00001950
1951 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001952 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00001953 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001954 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
1955 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00001956 }
1957 Buf += 8;
1958 }
1959
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001960 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001961 for (ArrayRef<uint32_t> Vec : CuVectors) {
1962 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00001963 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001964 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00001965 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00001966 Buf += 4;
1967 }
1968 }
1969
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001970 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001971 for (auto &KV : Symbols) {
1972 CachedHashStringRef S = KV.first;
1973 GdbSymbol *Sym = KV.second;
1974 size_t Off = Sym->NameOffset;
1975 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00001976 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001977 }
Eugene Levianta113a412016-11-21 09:24:43 +00001978}
1979
George Rimar67c60722017-07-18 11:55:35 +00001980bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00001981
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001982template <class ELFT>
1983EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001984 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001985
1986// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1987// Each entry of the search table consists of two values,
1988// the starting PC from where FDEs covers, and the FDE's address.
1989// It is sorted by PC.
1990template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1991 const endianness E = ELFT::TargetEndianness;
1992
1993 // Sort the FDE list by their PC and uniqueify. Usually there is only
1994 // one FDE for a PC (i.e. function), but if ICF merges two functions
1995 // into one, there can be more than one FDEs pointing to the address.
1996 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1997 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1998 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1999 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
2000
2001 Buf[0] = 1;
2002 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
2003 Buf[2] = DW_EH_PE_udata4;
2004 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002005 write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002006 write32<E>(Buf + 8, Fdes.size());
2007 Buf += 12;
2008
Rui Ueyamac49bdd62017-04-14 01:34:45 +00002009 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002010 for (FdeData &Fde : Fdes) {
2011 write32<E>(Buf, Fde.Pc - VA);
2012 write32<E>(Buf + 4, Fde.FdeVA - VA);
2013 Buf += 8;
2014 }
2015}
2016
2017template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
2018 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00002019 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002020}
2021
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002022template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002023void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
2024 Fdes.push_back({Pc, FdeVA});
2025}
2026
George Rimar11992c862016-11-25 08:05:41 +00002027template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00002028 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00002029}
2030
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002031template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002032VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002033 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2034 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002035
2036static StringRef getFileDefName() {
2037 if (!Config->SoName.empty())
2038 return Config->SoName;
2039 return Config->OutputFile;
2040}
2041
Rui Ueyama945055a2017-02-27 03:07:41 +00002042template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002043 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002044 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002045 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002046
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002047 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002048
2049 // sh_info should be set to the number of definitions. This fact is missed in
2050 // documentation, but confirmed by binutils community:
2051 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002052 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002053}
2054
2055template <class ELFT>
2056void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2057 StringRef Name, size_t NameOff) {
2058 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2059 Verdef->vd_version = 1;
2060 Verdef->vd_cnt = 1;
2061 Verdef->vd_aux = sizeof(Elf_Verdef);
2062 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2063 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2064 Verdef->vd_ndx = Index;
2065 Verdef->vd_hash = hashSysV(Name);
2066
2067 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2068 Verdaux->vda_name = NameOff;
2069 Verdaux->vda_next = 0;
2070}
2071
2072template <class ELFT>
2073void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2074 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2075
2076 for (VersionDefinition &V : Config->VersionDefinitions) {
2077 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2078 writeOne(Buf, V.Id, V.Name, V.NameOff);
2079 }
2080
2081 // Need to terminate the last version definition.
2082 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2083 Verdef->vd_next = 0;
2084}
2085
2086template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2087 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2088}
2089
2090template <class ELFT>
2091VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002092 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002093 ".gnu.version") {
2094 this->Entsize = sizeof(Elf_Versym);
2095}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002096
Rui Ueyama945055a2017-02-27 03:07:41 +00002097template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002098 // At the moment of june 2016 GNU docs does not mention that sh_link field
2099 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002100 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002101}
2102
2103template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002104 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002105}
2106
2107template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2108 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002109 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002110 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2111 ++OutVersym;
2112 }
2113}
2114
George Rimar11992c862016-11-25 08:05:41 +00002115template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2116 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2117}
2118
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002119template <class ELFT>
2120VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002121 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2122 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002123 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2124 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2125 // First identifiers are reserved by verdef section if it exist.
2126 NextIndex = getVerDefNum() + 1;
2127}
2128
2129template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002130void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2131 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2132 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002133 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2134 return;
2135 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002136
Rafael Espindola6e93d052017-08-04 22:31:42 +00002137 SharedFile<ELFT> *File = SS->getFile<ELFT>();
Rui Ueyama4076fa12017-02-26 23:35:34 +00002138
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002139 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2140 // to create one by adding it to our needed list and creating a dynstr entry
2141 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002142 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002143 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002144 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002145 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2146 // prepare to create one by allocating a version identifier and creating a
2147 // dynstr entry for the version name.
2148 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002149 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2150 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002151 NV.Index = NextIndex++;
2152 }
2153 SS->symbol()->VersionId = NV.Index;
2154}
2155
2156template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2157 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2158 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2159 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2160
2161 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2162 // Create an Elf_Verneed for this DSO.
2163 Verneed->vn_version = 1;
2164 Verneed->vn_cnt = P.first->VerdefMap.size();
2165 Verneed->vn_file = P.second;
2166 Verneed->vn_aux =
2167 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2168 Verneed->vn_next = sizeof(Elf_Verneed);
2169 ++Verneed;
2170
2171 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2172 // VerdefMap, which will only contain references to needed version
2173 // definitions. Each Elf_Vernaux is based on the information contained in
2174 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2175 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2176 // data structures within a single input file.
2177 for (auto &NV : P.first->VerdefMap) {
2178 Vernaux->vna_hash = NV.first->vd_hash;
2179 Vernaux->vna_flags = 0;
2180 Vernaux->vna_other = NV.second.Index;
2181 Vernaux->vna_name = NV.second.StrTab;
2182 Vernaux->vna_next = sizeof(Elf_Vernaux);
2183 ++Vernaux;
2184 }
2185
2186 Vernaux[-1].vna_next = 0;
2187 }
2188 Verneed[-1].vn_next = 0;
2189}
2190
Rui Ueyama945055a2017-02-27 03:07:41 +00002191template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002192 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2193 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002194}
2195
2196template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2197 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2198 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2199 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2200 return Size;
2201}
2202
George Rimar11992c862016-11-25 08:05:41 +00002203template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2204 return getNeedNum() == 0;
2205}
2206
Rafael Espindola6119b862017-03-06 20:23:56 +00002207void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002208 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002209 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002210}
2211
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002212MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2213 uint64_t Flags, uint32_t Alignment)
2214 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2215 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002216
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002217size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2218
2219void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002220
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002221void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002222 // Add all string pieces to the string table builder to create section
2223 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002224 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002225 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2226 if (Sec->Pieces[I].Live)
2227 Builder.add(Sec->getData(I));
2228
2229 // Fix the string table content. After this, the contents will never change.
2230 Builder.finalize();
2231
2232 // finalize() fixed tail-optimized strings, so we can now get
2233 // offsets of strings. Get an offset for each string and save it
2234 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002235 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002236 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2237 if (Sec->Pieces[I].Live)
2238 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2239}
2240
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002241void MergeNoTailSection::writeTo(uint8_t *Buf) {
2242 for (size_t I = 0; I < NumShards; ++I)
2243 Shards[I].write(Buf + ShardOffsets[I]);
2244}
2245
2246// This function is very hot (i.e. it can take several seconds to finish)
2247// because sometimes the number of inputs is in an order of magnitude of
2248// millions. So, we use multi-threading.
2249//
2250// For any strings S and T, we know S is not mergeable with T if S's hash
2251// value is different from T's. If that's the case, we can safely put S and
2252// T into different string builders without worrying about merge misses.
2253// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002254void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002255 // Initializes string table builders.
2256 for (size_t I = 0; I < NumShards; ++I)
2257 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2258
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002259 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2260 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002261 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002262 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002263 Concurrency =
2264 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002265
2266 // Add section pieces to the builders.
2267 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2268 for (MergeInputSection *Sec : Sections) {
2269 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2270 if (!Sec->Pieces[I].Live)
2271 continue;
Rui Ueyama95bf5092017-10-21 23:20:13 +00002272 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002273 if ((ShardId & (Concurrency - 1)) == ThreadId)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002274 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002275 }
2276 }
2277 });
2278
2279 // Compute an in-section offset for each shard.
2280 size_t Off = 0;
2281 for (size_t I = 0; I < NumShards; ++I) {
2282 Shards[I].finalizeInOrder();
2283 if (Shards[I].getSize() > 0)
2284 Off = alignTo(Off, Alignment);
2285 ShardOffsets[I] = Off;
2286 Off += Shards[I].getSize();
2287 }
2288 Size = Off;
2289
2290 // So far, section pieces have offsets from beginning of shards, but
2291 // we want offsets from beginning of the whole section. Fix them.
2292 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002293 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2294 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002295 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002296 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002297 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002298}
2299
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002300static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2301 uint32_t Type,
2302 uint64_t Flags,
2303 uint32_t Alignment) {
2304 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2305 if (ShouldTailMerge)
2306 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2307 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002308}
2309
Rui Ueyama2b714b52017-10-11 03:12:53 +00002310// Debug sections may be compressed by zlib. Uncompress if exists.
2311void elf::decompressSections() {
2312 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2313 if (Sec->Live)
2314 Sec->maybeUncompress();
2315 });
2316}
2317
2318// This function scans over the inputsections to create mergeable
2319// synthetic sections.
2320//
2321// It removes MergeInputSections from the input section array and adds
2322// new synthetic sections at the location of the first input section
2323// that it replaces. It then finalizes each synthetic section in order
2324// to compute an output offset for each piece of each input section.
2325void elf::mergeSections() {
2326 // splitIntoPieces needs to be called on each MergeInputSection
2327 // before calling finalizeContents(). Do that first.
2328 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2329 if (Sec->Live)
2330 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2331 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002332 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002333
2334 std::vector<MergeSyntheticSection *> MergeSections;
2335 for (InputSectionBase *&S : InputSections) {
2336 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2337 if (!MS)
2338 continue;
2339
2340 // We do not want to handle sections that are not alive, so just remove
2341 // them instead of trying to merge.
2342 if (!MS->Live)
2343 continue;
2344
2345 StringRef OutsecName = getOutputSectionName(MS->Name);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002346 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2347
2348 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002349 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002350 Sec->Alignment == Alignment;
2351 });
2352 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002353 MergeSyntheticSection *Syn =
2354 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002355 MergeSections.push_back(Syn);
2356 I = std::prev(MergeSections.end());
2357 S = Syn;
2358 } else {
2359 S = nullptr;
2360 }
2361 (*I)->addSection(MS);
2362 }
2363 for (auto *MS : MergeSections)
2364 MS->finalizeContents();
2365
2366 std::vector<InputSectionBase *> &V = InputSections;
2367 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2368}
2369
George Rimar42886c42017-03-15 12:02:31 +00002370MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002371 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2372 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002373
George Rimar90a528b2017-03-21 09:01:39 +00002374ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002375 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002376 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002377
2378// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2379// This section will have been sorted last in the .ARM.exidx table.
2380// This table entry will have the form:
2381// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002382// The sentinel must have the PREL31 value of an address higher than any
2383// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002384void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002385 // The Sections are sorted in order of ascending PREL31 address with the
2386 // sentinel last. We need to find the InputSection that precedes the
2387 // sentinel. By construction the Sentinel is in the last
2388 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +00002389 OutputSection *C = getParent();
Rui Ueyama6b394ca2017-10-11 01:50:56 +00002390 auto ISD =
2391 std::find_if(C->SectionCommands.rbegin(), C->SectionCommands.rend(),
2392 [](const BaseCommand *Base) {
2393 return isa<InputSectionDescription>(Base);
2394 });
Peter Smithea79b212017-05-31 09:02:21 +00002395 auto L = cast<InputSectionDescription>(*ISD);
2396 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002397 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002398 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002399 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002400 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2401 write32le(Buf + 4, 0x1);
2402}
2403
George Rimar7b827042017-03-16 10:40:50 +00002404ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002405 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002406 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002407 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002408 this->OutSecOff = Off;
2409}
2410
George Rimar7b827042017-03-16 10:40:50 +00002411void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002412 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002413 T->Offset = Off;
2414 Thunks.push_back(T);
2415 T->addSymbols(*this);
2416 Size = Off + T->size();
2417}
2418
George Rimar7b827042017-03-16 10:40:50 +00002419void ThunkSection::writeTo(uint8_t *Buf) {
2420 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002421 T->writeTo(Buf + T->Offset, *this);
2422}
2423
George Rimar7b827042017-03-16 10:40:50 +00002424InputSection *ThunkSection::getTargetInputSection() const {
2425 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002426 return T->getTargetInputSection();
2427}
2428
George Rimar9782ca52017-03-15 15:29:29 +00002429InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002430BssSection *InX::Bss;
2431BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002432BuildIdSection *InX::BuildId;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002433SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002434StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002435SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002436InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002437GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002438GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002439GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002440GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002441HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002442IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002443MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002444MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002445PltSection *InX::Plt;
2446PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002447StringTableSection *InX::ShStrTab;
2448StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002449SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002450
Rafael Espindola300b3862017-07-12 23:56:53 +00002451template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2452template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2453template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2454template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2455
George Rimara9189572017-03-17 16:50:07 +00002456template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2457template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2458template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2459template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2460
Ben Dunbobbin73eabf22017-09-29 09:08:26 +00002461template void elf::createCommonSections<ELF32LE>();
2462template void elf::createCommonSections<ELF32BE>();
2463template void elf::createCommonSections<ELF64LE>();
2464template void elf::createCommonSections<ELF64BE>();
2465
Rafael Espindola6119b862017-03-06 20:23:56 +00002466template MergeInputSection *elf::createCommentSection<ELF32LE>();
2467template MergeInputSection *elf::createCommentSection<ELF32BE>();
2468template MergeInputSection *elf::createCommentSection<ELF64LE>();
2469template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002470
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002471template class elf::MipsAbiFlagsSection<ELF32LE>;
2472template class elf::MipsAbiFlagsSection<ELF32BE>;
2473template class elf::MipsAbiFlagsSection<ELF64LE>;
2474template class elf::MipsAbiFlagsSection<ELF64BE>;
2475
Simon Atanasyance02cf02016-11-09 21:36:56 +00002476template class elf::MipsOptionsSection<ELF32LE>;
2477template class elf::MipsOptionsSection<ELF32BE>;
2478template class elf::MipsOptionsSection<ELF64LE>;
2479template class elf::MipsOptionsSection<ELF64BE>;
2480
2481template class elf::MipsReginfoSection<ELF32LE>;
2482template class elf::MipsReginfoSection<ELF32BE>;
2483template class elf::MipsReginfoSection<ELF64LE>;
2484template class elf::MipsReginfoSection<ELF64BE>;
2485
Eugene Leviant6380ce22016-11-15 12:26:55 +00002486template class elf::DynamicSection<ELF32LE>;
2487template class elf::DynamicSection<ELF32BE>;
2488template class elf::DynamicSection<ELF64LE>;
2489template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002490
2491template class elf::RelocationSection<ELF32LE>;
2492template class elf::RelocationSection<ELF32BE>;
2493template class elf::RelocationSection<ELF64LE>;
2494template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002495
2496template class elf::SymbolTableSection<ELF32LE>;
2497template class elf::SymbolTableSection<ELF32BE>;
2498template class elf::SymbolTableSection<ELF64LE>;
2499template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002500
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002501template class elf::EhFrameHeader<ELF32LE>;
2502template class elf::EhFrameHeader<ELF32BE>;
2503template class elf::EhFrameHeader<ELF64LE>;
2504template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002505
2506template class elf::VersionTableSection<ELF32LE>;
2507template class elf::VersionTableSection<ELF32BE>;
2508template class elf::VersionTableSection<ELF64LE>;
2509template class elf::VersionTableSection<ELF64BE>;
2510
2511template class elf::VersionNeedSection<ELF32LE>;
2512template class elf::VersionNeedSection<ELF32BE>;
2513template class elf::VersionNeedSection<ELF64LE>;
2514template class elf::VersionNeedSection<ELF64BE>;
2515
2516template class elf::VersionDefinitionSection<ELF32LE>;
2517template class elf::VersionDefinitionSection<ELF32BE>;
2518template class elf::VersionDefinitionSection<ELF64LE>;
2519template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002520
Rafael Espindola66b4e212017-02-23 22:06:28 +00002521template class elf::EhFrameSection<ELF32LE>;
2522template class elf::EhFrameSection<ELF32BE>;
2523template class elf::EhFrameSection<ELF64LE>;
2524template class elf::EhFrameSection<ELF64BE>;