blob: 80a80c40fcea100a3dbb4a9980b9ca6bc7badbb7 [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"
19#include "Error.h"
20#include "InputFiles.h"
Eugene Leviant17b7a572016-11-22 17:49:14 +000021#include "LinkerScript.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000022#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000023#include "OutputSections.h"
24#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000025#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000026#include "Target.h"
Rui Ueyama244a4352016-12-03 21:24:51 +000027#include "Threads.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000028#include "Writer.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000029#include "lld/Config/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 Ueyama6dc7fcb2016-11-01 20:28:21 +000040
41using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000042using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000043using namespace llvm::ELF;
44using namespace llvm::object;
45using namespace llvm::support;
46using namespace llvm::support::endian;
47
48using namespace lld;
49using namespace lld::elf;
50
Rui Ueyama9320cb02017-02-27 02:56:02 +000051uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000052 if (OutputSection *Sec = getParent())
53 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000054 return 0;
55}
56
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000057std::vector<InputSection *> elf::createCommonSections() {
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000058 if (!Config->DefineCommon)
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000059 return {};
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000060
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000061 std::vector<InputSection *> Ret;
62 for (Symbol *S : Symtab->getSymbols()) {
63 auto *Sym = dyn_cast<DefinedCommon>(S->body());
64 if (!Sym || !Sym->Live)
65 continue;
George Rimar176d6062017-03-17 13:31:07 +000066
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000067 Sym->Section = make<BssSection>("COMMON");
Rafael Espindola67df57a2017-09-12 21:19:09 +000068 size_t Pos = Sym->Section->reserveSpace(Sym->Size, Sym->Alignment);
69 assert(Pos == 0);
70 (void)Pos;
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000071 Sym->Section->File = Sym->getFile();
72 Ret.push_back(Sym->Section);
73 }
74 return Ret;
Rui Ueyamae8a61022016-11-05 23:05:47 +000075}
76
Rui Ueyama3da3f062016-11-10 20:20:37 +000077// Returns an LLD version string.
78static ArrayRef<uint8_t> getVersion() {
79 // Check LLD_VERSION first for ease of testing.
80 // You can get consitent output by using the environment variable.
81 // This is only for testing.
82 StringRef S = getenv("LLD_VERSION");
83 if (S.empty())
84 S = Saver.save(Twine("Linker: ") + getLLDVersion());
85
86 // +1 to include the terminating '\0'.
87 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000088}
Rui Ueyama3da3f062016-11-10 20:20:37 +000089
90// Creates a .comment section containing LLD version info.
91// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000092// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +000093// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +000094template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +000095 typename ELFT::Shdr Hdr = {};
96 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
97 Hdr.sh_type = SHT_PROGBITS;
98 Hdr.sh_entsize = 1;
99 Hdr.sh_addralign = 1;
100
Rafael Espindola6119b862017-03-06 20:23:56 +0000101 auto *Ret =
Rui Ueyama709fb2bb12017-07-26 22:13:32 +0000102 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000103 Ret->Data = getVersion();
Rui Ueyama3da3f062016-11-10 20:20:37 +0000104 return Ret;
105}
106
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000107// .MIPS.abiflags section.
108template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000109MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000110 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000111 Flags(Flags) {
112 this->Entsize = sizeof(Elf_Mips_ABIFlags);
113}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000114
115template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
116 memcpy(Buf, &Flags, sizeof(Flags));
117}
118
119template <class ELFT>
120MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
121 Elf_Mips_ABIFlags Flags = {};
122 bool Create = false;
123
Rui Ueyama536a2672017-02-27 02:32:08 +0000124 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000125 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000126 continue;
127 Sec->Live = false;
128 Create = true;
129
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000130 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000131 const size_t Size = Sec->Data.size();
132 // Older version of BFD (such as the default FreeBSD linker) concatenate
133 // .MIPS.abiflags instead of merging. To allow for this case (or potential
134 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
135 if (Size < sizeof(Elf_Mips_ABIFlags)) {
136 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
137 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000138 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000139 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000140 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000141 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000142 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000143 Twine(S->version));
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
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000147 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
148 // select the highest number of ISA/Rev/Ext.
149 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
150 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
151 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
152 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
153 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
154 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
155 Flags.ases |= S->ases;
156 Flags.flags1 |= S->flags1;
157 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000158 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000159 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000160
Rui Ueyama12f2da82016-11-22 03:57:06 +0000161 if (Create)
162 return make<MipsAbiFlagsSection<ELFT>>(Flags);
163 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000164}
165
Simon Atanasyance02cf02016-11-09 21:36:56 +0000166// .MIPS.options section.
167template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000168MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000169 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000170 Reginfo(Reginfo) {
171 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
172}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000173
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000174template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
175 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
176 Options->kind = ODK_REGINFO;
177 Options->size = getSize();
178
179 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000180 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000181 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000182}
183
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000184template <class ELFT>
185MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
186 // N64 ABI only.
187 if (!ELFT::Is64Bits)
188 return nullptr;
189
190 Elf_Mips_RegInfo Reginfo = {};
191 bool Create = false;
192
Rui Ueyama536a2672017-02-27 02:32:08 +0000193 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000194 if (Sec->Type != SHT_MIPS_OPTIONS)
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000195 continue;
196 Sec->Live = false;
197 Create = true;
198
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000199 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000200 ArrayRef<uint8_t> D = Sec->Data;
201
202 while (!D.empty()) {
203 if (D.size() < sizeof(Elf_Mips_Options)) {
204 error(Filename + ": invalid size of .MIPS.options section");
205 break;
206 }
207
208 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
209 if (Opt->kind == ODK_REGINFO) {
210 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
211 error(Filename + ": unsupported non-zero ri_gp_value");
212 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000213 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000214 break;
215 }
216
217 if (!Opt->size)
218 fatal(Filename + ": zero option descriptor size");
219 D = D.slice(Opt->size);
220 }
221 };
222
223 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000224 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000225 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000226}
227
228// MIPS .reginfo section.
229template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000230MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000231 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000232 Reginfo(Reginfo) {
233 this->Entsize = sizeof(Elf_Mips_RegInfo);
234}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000235
Rui Ueyamab71cae92016-11-22 03:57:08 +0000236template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000237 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000238 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000239 memcpy(Buf, &Reginfo, sizeof(Reginfo));
240}
241
242template <class ELFT>
243MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
244 // Section should be alive for O32 and N32 ABIs only.
245 if (ELFT::Is64Bits)
246 return nullptr;
247
248 Elf_Mips_RegInfo Reginfo = {};
249 bool Create = false;
250
Rui Ueyama536a2672017-02-27 02:32:08 +0000251 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000252 if (Sec->Type != SHT_MIPS_REGINFO)
Rui Ueyamab71cae92016-11-22 03:57:08 +0000253 continue;
254 Sec->Live = false;
255 Create = true;
256
257 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000258 error(toString(Sec->getFile<ELFT>()) +
259 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000260 return nullptr;
261 }
262 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
263 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000264 error(toString(Sec->getFile<ELFT>()) +
265 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000266
267 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000268 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000269 };
270
271 if (Create)
272 return make<MipsReginfoSection<ELFT>>(Reginfo);
273 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000274}
275
Rui Ueyama3255a522017-02-27 02:32:49 +0000276InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000277 // StringSaver guarantees that the returned string ends with '\0'.
278 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000279 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
280
281 auto *Sec =
282 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
283 Sec->Live = true;
284 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000285}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000286
Rui Ueyama65316d72017-02-23 03:15:57 +0000287SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
288 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000289 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
Rafael Espindola6e93d052017-08-04 22:31:42 +0000290 Value, Size, Section);
George Rimar69b17c32017-05-16 10:04:42 +0000291 if (InX::SymTab)
292 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000293 return S;
294}
295
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000296static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000297 switch (Config->BuildId) {
298 case BuildIdKind::Fast:
299 return 8;
300 case BuildIdKind::Md5:
301 case BuildIdKind::Uuid:
302 return 16;
303 case BuildIdKind::Sha1:
304 return 20;
305 case BuildIdKind::Hexstring:
306 return Config->BuildIdVector.size();
307 default:
308 llvm_unreachable("unknown BuildIdKind");
309 }
310}
311
George Rimar6c2949d2017-03-20 16:40:21 +0000312BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000313 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000314 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000315
George Rimar6c2949d2017-03-20 16:40:21 +0000316void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000317 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000318 write32(Buf, 4, E); // Name size
319 write32(Buf + 4, HashSize, E); // Content size
320 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000321 memcpy(Buf + 12, "GNU", 4); // Name string
322 HashBuf = Buf + 16;
323}
324
Rui Ueyama35e00752016-11-10 00:12:28 +0000325// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000326static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
327 size_t ChunkSize) {
328 std::vector<ArrayRef<uint8_t>> Ret;
329 while (Arr.size() > ChunkSize) {
330 Ret.push_back(Arr.take_front(ChunkSize));
331 Arr = Arr.drop_front(ChunkSize);
332 }
333 if (!Arr.empty())
334 Ret.push_back(Arr);
335 return Ret;
336}
337
Rui Ueyama35e00752016-11-10 00:12:28 +0000338// Computes a hash value of Data using a given hash function.
339// In order to utilize multiple cores, we first split data into 1MB
340// chunks, compute a hash for each chunk, and then compute a hash value
341// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000342void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000343 llvm::ArrayRef<uint8_t> Data,
344 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000345 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000346 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000347
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000348 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000349 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000350 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
351 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000352
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000353 // Write to the final output buffer.
354 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000355}
356
George Rimar1ab9cf42017-03-17 10:14:53 +0000357BssSection::BssSection(StringRef Name)
358 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
359
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000360size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000361 if (OutputSection *Sec = getParent())
362 Sec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000363 this->Size = alignTo(this->Size, Alignment) + Size;
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000364 this->Alignment = std::max(this->Alignment, Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000365 return this->Size - Size;
366}
Peter Smithebfe9942017-02-09 10:27:57 +0000367
George Rimar6c2949d2017-03-20 16:40:21 +0000368void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000369 switch (Config->BuildId) {
370 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000371 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000372 write64le(Dest, xxHash64(toStringRef(Arr)));
373 });
374 break;
375 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000376 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000377 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000378 });
379 break;
380 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000381 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000382 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000383 });
384 break;
385 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000386 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000387 error("entropy source failure");
388 break;
389 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000390 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000391 break;
392 default:
393 llvm_unreachable("unknown BuildIdKind");
394 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000395}
396
Eugene Leviant41ca3272016-11-10 09:48:29 +0000397template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000398EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000399 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000400
401// Search for an existing CIE record or create a new one.
402// CIE records from input object files are uniquified by their contents
403// and where their relocations point to.
404template <class ELFT>
405template <class RelTy>
406CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
407 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000408 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000409 const endianness E = ELFT::TargetEndianness;
410 if (read32<E>(Piece.data().data() + 4) != 0)
411 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
412
413 SymbolBody *Personality = nullptr;
414 unsigned FirstRelI = Piece.FirstRelocation;
415 if (FirstRelI != (unsigned)-1)
416 Personality =
417 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
418
419 // Search for an existing CIE by CIE contents/relocation target pair.
420 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
421
422 // If not found, create a new one.
423 if (Cie->Piece == nullptr) {
424 Cie->Piece = &Piece;
425 Cies.push_back(Cie);
426 }
427 return Cie;
428}
429
430// There is one FDE per function. Returns true if a given FDE
431// points to a live function.
432template <class ELFT>
433template <class RelTy>
434bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
435 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000436 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000437 unsigned FirstRelI = Piece.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000438
439 // An FDE should point to some function because FDEs are to describe
440 // functions. That's however not always the case due to an issue of
441 // ld.gold with -r. ld.gold may discard only functions and leave their
442 // corresponding FDEs, which results in creating bad .eh_frame sections.
443 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000444 if (FirstRelI == (unsigned)-1)
445 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000446
Rafael Espindola66b4e212017-02-23 22:06:28 +0000447 const RelTy &Rel = Rels[FirstRelI];
448 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000449 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000450 if (!D || !D->Section)
451 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000452 auto *Target =
453 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000454 return Target && Target->Live;
455}
456
457// .eh_frame is a sequence of CIE or FDE records. In general, there
458// is one CIE record per input object file which is followed by
459// a list of FDEs. This function searches an existing CIE or create a new
460// one and associates FDEs to the CIE.
461template <class ELFT>
462template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000463void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000464 ArrayRef<RelTy> Rels) {
465 const endianness E = ELFT::TargetEndianness;
466
467 DenseMap<size_t, CieRecord *> OffsetToCie;
468 for (EhSectionPiece &Piece : Sec->Pieces) {
469 // The empty record is the end marker.
470 if (Piece.size() == 4)
471 return;
472
473 size_t Offset = Piece.InputOff;
474 uint32_t ID = read32<E>(Piece.data().data() + 4);
475 if (ID == 0) {
476 OffsetToCie[Offset] = addCie(Piece, Rels);
477 continue;
478 }
479
480 uint32_t CieOffset = Offset + 4 - ID;
481 CieRecord *Cie = OffsetToCie[CieOffset];
482 if (!Cie)
483 fatal(toString(Sec) + ": invalid CIE reference");
484
485 if (!isFdeLive(Piece, Rels))
486 continue;
487 Cie->FdePieces.push_back(&Piece);
488 NumFdes++;
489 }
490}
491
492template <class ELFT>
493void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000494 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000495 Sec->Parent = this;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000496 updateAlignment(Sec->Alignment);
497 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000498 for (auto *DS : Sec->DependentSections)
499 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000500
501 // .eh_frame is a sequence of CIE or FDE records. This function
502 // splits it into pieces so that we can call
503 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000504 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000505 if (Sec->Pieces.empty())
506 return;
507
508 if (Sec->NumRelocations) {
509 if (Sec->AreRelocsRela)
510 addSectionAux(Sec, Sec->template relas<ELFT>());
511 else
512 addSectionAux(Sec, Sec->template rels<ELFT>());
513 return;
514 }
515 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
516}
517
518template <class ELFT>
519static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
520 memcpy(Buf, D.data(), D.size());
521
Andrew Ng6dee7362017-09-07 08:43:56 +0000522 size_t Aligned = alignTo(D.size(), sizeof(typename ELFT::uint));
523
524 // Zero-clear trailing padding if it exists.
525 memset(Buf + D.size(), 0, Aligned - D.size());
526
Rafael Espindola66b4e212017-02-23 22:06:28 +0000527 // Fix the size field. -4 since size does not include the size field itself.
528 const endianness E = ELFT::TargetEndianness;
Andrew Ng6dee7362017-09-07 08:43:56 +0000529 write32<E>(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000530}
531
Rui Ueyama945055a2017-02-27 03:07:41 +0000532template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000533 if (this->Size)
534 return; // Already finalized.
535
536 size_t Off = 0;
537 for (CieRecord *Cie : Cies) {
538 Cie->Piece->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000539 Off += alignTo(Cie->Piece->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000540
541 for (EhSectionPiece *Fde : Cie->FdePieces) {
542 Fde->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000543 Off += alignTo(Fde->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000544 }
545 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000546
547 // The LSB standard does not allow a .eh_frame section with zero
548 // Call Frame Information records. Therefore add a CIE record length
549 // 0 as a terminator if this .eh_frame section is empty.
550 if (Off == 0)
551 Off = 4;
552
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000553 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000554}
555
556template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
557 const endianness E = ELFT::TargetEndianness;
558 switch (Size) {
559 case DW_EH_PE_udata2:
560 return read16<E>(Buf);
561 case DW_EH_PE_udata4:
562 return read32<E>(Buf);
563 case DW_EH_PE_udata8:
564 return read64<E>(Buf);
565 case DW_EH_PE_absptr:
566 if (ELFT::Is64Bits)
567 return read64<E>(Buf);
568 return read32<E>(Buf);
569 }
570 fatal("unknown FDE size encoding");
571}
572
573// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
574// We need it to create .eh_frame_hdr section.
575template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000576uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
577 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000578 // The starting address to which this FDE applies is
579 // stored at FDE + 8 byte.
580 size_t Off = FdeOff + 8;
581 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
582 if ((Enc & 0x70) == DW_EH_PE_absptr)
583 return Addr;
584 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000585 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000586 fatal("unknown FDE size relative encoding");
587}
588
589template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
590 const endianness E = ELFT::TargetEndianness;
591 for (CieRecord *Cie : Cies) {
592 size_t CieOffset = Cie->Piece->OutputOff;
593 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
594
595 for (EhSectionPiece *Fde : Cie->FdePieces) {
596 size_t Off = Fde->OutputOff;
597 writeCieFde<ELFT>(Buf + Off, Fde->data());
598
599 // FDE's second word should have the offset to an associated CIE.
600 // Write it.
601 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
602 }
603 }
604
Rafael Espindola5c02b742017-03-06 21:17:18 +0000605 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000606 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000607
608 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
609 // to get a FDE from an address to which FDE is applied. So here
610 // we obtain two addresses and pass them to EhFrameHdr object.
611 if (In<ELFT>::EhFrameHdr) {
612 for (CieRecord *Cie : Cies) {
613 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
614 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000615 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000616 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000617 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
618 }
619 }
620 }
621}
622
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000623GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000624 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
625 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000626
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000627void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000628 Sym.GotIndex = NumEntries;
629 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000630}
631
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000632bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000633 if (Sym.GlobalDynIndex != -1U)
634 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000635 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000636 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000637 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000638 return true;
639}
640
641// Reserves TLS entries for a TLS module ID and a TLS block offset.
642// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000643bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000644 if (TlsIndexOff != uint32_t(-1))
645 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000646 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000647 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000648 return true;
649}
650
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000651uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000652 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000653}
654
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000655uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000656 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000657}
658
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000659void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000660
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000661bool GotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000662 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
663 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000664 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000665}
666
Igor Kudrin202a9f62017-07-14 08:10:45 +0000667void GotSection::writeTo(uint8_t *Buf) {
668 // Buf points to the start of this section's buffer,
669 // whereas InputSectionBase::relocateAlloc() expects its argument
670 // to point to the start of the output section.
671 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
672}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000673
George Rimar14534eb2017-03-20 16:44:28 +0000674MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000675 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
676 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000677
George Rimar14534eb2017-03-20 16:44:28 +0000678void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000679 // For "true" local symbols which can be referenced from the same module
680 // only compiler creates two instructions for address loading:
681 //
682 // lw $8, 0($gp) # R_MIPS_GOT16
683 // addi $8, $8, 0 # R_MIPS_LO16
684 //
685 // The first instruction loads high 16 bits of the symbol address while
686 // the second adds an offset. That allows to reduce number of required
687 // GOT entries because only one global offset table entry is necessary
688 // for every 64 KBytes of local data. So for local symbols we need to
689 // allocate number of GOT entries to hold all required "page" addresses.
690 //
691 // All global symbols (hidden and regular) considered by compiler uniformly.
692 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
693 // to load address of the symbol. So for each such symbol we need to
694 // allocate dedicated GOT entry to store its address.
695 //
696 // If a symbol is preemptible we need help of dynamic linker to get its
697 // final address. The corresponding GOT entries are allocated in the
698 // "global" part of GOT. Entries for non preemptible global symbol allocated
699 // in the "local" part of GOT.
700 //
701 // See "Global Offset Table" in Chapter 5:
702 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
703 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
704 // At this point we do not know final symbol value so to reduce number
705 // of allocated GOT entries do the following trick. Save all output
706 // sections referenced by GOT relocations. Then later in the `finalize`
707 // method calculate number of "pages" required to cover all saved output
708 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000709 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000710 return;
711 }
712 if (Sym.isTls()) {
713 // GOT entries created for MIPS TLS relocations behave like
714 // almost GOT entries from other ABIs. They go to the end
715 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000716 Sym.GotIndex = TlsEntries.size();
717 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 return;
719 }
George Rimar14534eb2017-03-20 16:44:28 +0000720 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000721 if (S.isInGot() && !A)
722 return;
723 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000724 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000725 return;
726 Items.emplace_back(&S, A);
727 if (!A)
728 S.GotIndex = NewIndex;
729 };
730 if (Sym.isPreemptible()) {
731 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000732 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000733 Sym.IsInGlobalMipsGot = true;
734 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000735 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000736 Sym.Is32BitMipsGot = true;
737 } else {
738 // Hold local GOT entries accessed via a 16-bit index separately.
739 // That allows to write them in the beginning of the GOT and keep
740 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000741 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000742 }
743}
744
George Rimar14534eb2017-03-20 16:44:28 +0000745bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000746 if (Sym.GlobalDynIndex != -1U)
747 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000748 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000749 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000750 TlsEntries.push_back(nullptr);
751 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000752 return true;
753}
754
755// Reserves TLS entries for a TLS module ID and a TLS block offset.
756// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000757bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000758 if (TlsIndexOff != uint32_t(-1))
759 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000760 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000761 TlsEntries.push_back(nullptr);
762 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000763 return true;
764}
765
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000766static uint64_t getMipsPageAddr(uint64_t Addr) {
767 return (Addr + 0x8000) & ~0xffff;
768}
769
770static uint64_t getMipsPageCount(uint64_t Size) {
771 return (Size + 0xfffe) / 0xffff + 1;
772}
773
George Rimar14534eb2017-03-20 16:44:28 +0000774uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
775 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000776 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000777 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
778 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
779 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000780 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000781 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000782}
783
George Rimar14534eb2017-03-20 16:44:28 +0000784uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
785 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000786 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000787 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000788 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000789 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000791 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000792 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 Index += LocalEntries.size();
794 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000795 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000796 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000797 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000798 auto It = EntryIndexMap.find({&B, Addend});
799 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000800 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000801 }
George Rimar14534eb2017-03-20 16:44:28 +0000802 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000803}
804
George Rimar14534eb2017-03-20 16:44:28 +0000805uint64_t MipsGotSection::getTlsOffset() const {
806 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000807}
808
George Rimar14534eb2017-03-20 16:44:28 +0000809uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
810 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000811}
812
George Rimar14534eb2017-03-20 16:44:28 +0000813const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000814 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000815}
816
George Rimar14534eb2017-03-20 16:44:28 +0000817unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000818 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
819 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000820}
821
George Rimar67c60722017-07-18 11:55:35 +0000822void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000823
George Rimar14534eb2017-03-20 16:44:28 +0000824void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000825 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000826 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000827 // For each output section referenced by GOT page relocations calculate
828 // and save into PageIndexMap an upper bound of MIPS GOT entries required
829 // to store page addresses of local symbols. We assume the worst case -
830 // each 64kb page of the output section has at least one GOT relocation
831 // against it. And take in account the case when the section intersects
832 // page boundaries.
833 P.second = PageEntriesNum;
834 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000835 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000836 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000837 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000838}
839
George Rimar14534eb2017-03-20 16:44:28 +0000840bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000841 // We add the .got section to the result for dynamic MIPS target because
842 // its address and properties are mentioned in the .dynamic section.
843 return Config->Relocatable;
844}
845
George Rimar67c60722017-07-18 11:55:35 +0000846uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000847
George Rimar5f73bc92017-03-29 15:23:28 +0000848static uint64_t readUint(uint8_t *Buf) {
849 if (Config->Is64)
850 return read64(Buf, Config->Endianness);
851 return read32(Buf, Config->Endianness);
852}
853
George Rimar14534eb2017-03-20 16:44:28 +0000854static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000855 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000856 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000857 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000858 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000859}
860
George Rimar14534eb2017-03-20 16:44:28 +0000861void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000862 // Set the MSB of the second GOT slot. This is not required by any
863 // MIPS ABI documentation, though.
864 //
865 // There is a comment in glibc saying that "The MSB of got[1] of a
866 // gnu object is set to identify gnu objects," and in GNU gold it
867 // says "the second entry will be used by some runtime loaders".
868 // But how this field is being used is unclear.
869 //
870 // We are not really willing to mimic other linkers behaviors
871 // without understanding why they do that, but because all files
872 // generated by GNU tools have this special GOT value, and because
873 // we've been doing this for years, it is probably a safe bet to
874 // keep doing this for now. We really need to revisit this to see
875 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000876 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
877 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000878 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000879 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000880 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000881 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000882 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000883 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
884 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000885 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000886 }
George Rimar14534eb2017-03-20 16:44:28 +0000887 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000888 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000889 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000890 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000891 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000892 uint64_t VA = Body->getVA(SA.second);
893 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000894 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000895 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
896 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
897 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000898 // Initialize TLS-related GOT entries. If the entry has a corresponding
899 // dynamic relocations, leave it initialized by zero. Write down adjusted
900 // TLS symbol's values otherwise. To calculate the adjustments use offsets
901 // for thread-local storage.
902 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000903 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000904 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000905 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000906 if (!B || B->isPreemptible())
907 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000908 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000909 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000910 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
911 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000912 }
913 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000914 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
915 writeUint(Entry, 1);
916 Entry += Config->Wordsize;
917 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000918 }
919 }
920}
921
George Rimar10f74fc2017-03-15 09:12:56 +0000922GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000923 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
924 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000925
George Rimar10f74fc2017-03-15 09:12:56 +0000926void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000927 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
928 Entries.push_back(&Sym);
929}
930
George Rimar10f74fc2017-03-15 09:12:56 +0000931size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000932 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
933 Target->GotPltEntrySize;
934}
935
George Rimar10f74fc2017-03-15 09:12:56 +0000936void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000937 Target->writeGotPltHeader(Buf);
938 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
939 for (const SymbolBody *B : Entries) {
940 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000941 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000942 }
943}
944
Peter Smithbaffdb82016-12-08 12:58:55 +0000945// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
946// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000947IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000948 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
949 Target->GotPltEntrySize,
950 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000951
George Rimar10f74fc2017-03-15 09:12:56 +0000952void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000953 Sym.IsInIgot = true;
954 Sym.GotPltIndex = Entries.size();
955 Entries.push_back(&Sym);
956}
957
George Rimar10f74fc2017-03-15 09:12:56 +0000958size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000959 return Entries.size() * Target->GotPltEntrySize;
960}
961
George Rimar10f74fc2017-03-15 09:12:56 +0000962void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000963 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000964 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000965 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000966 }
967}
968
George Rimar49648002017-03-15 09:32:36 +0000969StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
970 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000971 Dynamic(Dynamic) {
972 // ELF string tables start with a NUL byte.
973 addString("");
974}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000975
976// Adds a string to the string table. If HashIt is true we hash and check for
977// duplicates. It is optional because the name of global symbols are already
978// uniqued and hashing them again has a big cost for a small value: uniquing
979// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000980unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000981 if (HashIt) {
982 auto R = StringMap.insert(std::make_pair(S, this->Size));
983 if (!R.second)
984 return R.first->second;
985 }
986 unsigned Ret = this->Size;
987 this->Size = this->Size + S.size() + 1;
988 Strings.push_back(S);
989 return Ret;
990}
991
George Rimar49648002017-03-15 09:32:36 +0000992void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000993 for (StringRef S : Strings) {
994 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000995 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000996 Buf += S.size() + 1;
997 }
998}
999
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001000// Returns the number of version definition entries. Because the first entry
1001// is for the version definition itself, it is the number of versioned symbols
1002// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001003static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1004
1005template <class ELFT>
1006DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001007 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001008 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001009 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001010
Petr Hosekffa786f2017-05-26 19:12:38 +00001011 // .dynamic section is not writable on MIPS and on Fuchsia OS
1012 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001013 // See "Special Section" in Chapter 4 in the following document:
1014 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001015 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001016 this->Flags = SHF_ALLOC;
1017
1018 addEntries();
1019}
1020
1021// There are some dynamic entries that don't depend on other sections.
1022// Such entries can be set early.
1023template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1024 // Add strings to .dynstr early so that .dynstr's size will be
1025 // fixed early.
George Rimarf525c922017-07-17 09:43:18 +00001026 for (StringRef S : Config->FilterList)
1027 add({DT_FILTER, InX::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001028 for (StringRef S : Config->AuxiliaryList)
Rafael Espindola895aea62017-05-11 22:02:41 +00001029 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001030 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001031 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001032 InX::DynStrTab->addString(Config->Rpath)});
Rafael Espindola244ef982017-07-26 18:42:48 +00001033 for (SharedFile<ELFT> *F : SharedFile<ELFT>::Instances)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001034 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001035 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001036 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001037 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001038
1039 // Set DT_FLAGS and DT_FLAGS_1.
1040 uint32_t DtFlags = 0;
1041 uint32_t DtFlags1 = 0;
1042 if (Config->Bsymbolic)
1043 DtFlags |= DF_SYMBOLIC;
1044 if (Config->ZNodelete)
1045 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001046 if (Config->ZNodlopen)
1047 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001048 if (Config->ZNow) {
1049 DtFlags |= DF_BIND_NOW;
1050 DtFlags1 |= DF_1_NOW;
1051 }
1052 if (Config->ZOrigin) {
1053 DtFlags |= DF_ORIGIN;
1054 DtFlags1 |= DF_1_ORIGIN;
1055 }
1056
1057 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001058 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001059 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001060 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001061
Petr Hosekffa786f2017-05-26 19:12:38 +00001062 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1063 // need it for each process, so we don't write it for DSOs. The loader writes
1064 // the pointer into this entry.
1065 //
1066 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1067 // systems (currently only Fuchsia OS) provide other means to give the
1068 // debugger this information. Such systems may choose make .dynamic read-only.
1069 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1070 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001071 add({DT_DEBUG, (uint64_t)0});
1072}
1073
1074// Add remaining entries to complete .dynamic contents.
1075template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1076 if (this->Size)
1077 return; // Already finalized.
1078
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001079 this->Link = InX::DynStrTab->getParent()->SectionIndex;
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001080 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001081 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001082 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001083 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent(),
1084 Entry::SecSize});
Rui Ueyama729ac792016-11-17 04:10:09 +00001085 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001086 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001087
1088 // MIPS dynamic loader does not support RELCOUNT tag.
1089 // The problem is in the tight relation between dynamic
1090 // relocations and GOT. So do not emit this tag on MIPS.
1091 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001092 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001093 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001094 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001095 }
1096 }
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001097 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001098 add({DT_JMPREL, In<ELFT>::RelaPlt});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001099 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent(), Entry::SecSize});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001100 switch (Config->EMachine) {
1101 case EM_MIPS:
1102 add({DT_MIPS_PLTGOT, In<ELFT>::GotPlt});
1103 break;
1104 case EM_SPARCV9:
1105 add({DT_PLTGOT, In<ELFT>::Plt});
1106 break;
1107 default:
1108 add({DT_PLTGOT, In<ELFT>::GotPlt});
1109 break;
1110 }
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001111 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001112 }
1113
George Rimar69b17c32017-05-16 10:04:42 +00001114 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001115 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001116 add({DT_STRTAB, InX::DynStrTab});
1117 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001118 if (!Config->ZText)
1119 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001120 if (InX::GnuHashTab)
1121 add({DT_GNU_HASH, InX::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001122 if (In<ELFT>::HashTab)
1123 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001124
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001125 if (Out::PreinitArray) {
1126 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1127 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001128 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001129 if (Out::InitArray) {
1130 add({DT_INIT_ARRAY, Out::InitArray});
1131 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001132 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001133 if (Out::FiniArray) {
1134 add({DT_FINI_ARRAY, Out::FiniArray});
1135 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001136 }
1137
Rui Ueyama43099e42017-08-15 16:03:11 +00001138 if (SymbolBody *B = Symtab->find(Config->Init))
1139 if (B->isInCurrentDSO())
1140 add({DT_INIT, B});
1141 if (SymbolBody *B = Symtab->find(Config->Fini))
1142 if (B->isInCurrentDSO())
1143 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001144
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001145 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1146 if (HasVerNeed || In<ELFT>::VerDef)
1147 add({DT_VERSYM, In<ELFT>::VerSym});
1148 if (In<ELFT>::VerDef) {
1149 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001150 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001151 }
1152 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001153 add({DT_VERNEED, In<ELFT>::VerNeed});
1154 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001155 }
1156
1157 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001158 add({DT_MIPS_RLD_VERSION, 1});
1159 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1160 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
George Rimar69b17c32017-05-16 10:04:42 +00001161 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001162 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1163 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001164 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001165 else
George Rimar69b17c32017-05-16 10:04:42 +00001166 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001167 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001168 if (InX::MipsRldMap)
1169 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001170 }
1171
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001172 getParent()->Link = this->Link;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001173
1174 // +1 for DT_NULL
1175 this->Size = (Entries.size() + 1) * this->Entsize;
1176}
1177
1178template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1179 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1180
1181 for (const Entry &E : Entries) {
1182 P->d_tag = E.Tag;
1183 switch (E.Kind) {
1184 case Entry::SecAddr:
1185 P->d_un.d_ptr = E.OutSec->Addr;
1186 break;
1187 case Entry::InSecAddr:
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001188 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001189 break;
1190 case Entry::SecSize:
1191 P->d_un.d_val = E.OutSec->Size;
1192 break;
1193 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001194 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001195 break;
1196 case Entry::PlainInt:
1197 P->d_un.d_val = E.Val;
1198 break;
1199 }
1200 ++P;
1201 }
1202}
1203
George Rimar97def8c2017-03-17 12:07:44 +00001204uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001205 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001206}
1207
George Rimar97def8c2017-03-17 12:07:44 +00001208int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001209 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001210 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001211 return Addend;
1212}
1213
George Rimar97def8c2017-03-17 12:07:44 +00001214uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001215 if (Sym && !UseSymVA)
1216 return Sym->DynsymIndex;
1217 return 0;
1218}
1219
1220template <class ELFT>
1221RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001222 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001223 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001224 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001225 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001226}
1227
1228template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001229void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001230 if (Reloc.Type == Target->RelativeRel)
1231 ++NumRelativeRelocs;
1232 Relocs.push_back(Reloc);
1233}
1234
1235template <class ELFT, class RelTy>
1236static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001237 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1238 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001239 if (AIsRel != BIsRel)
1240 return AIsRel;
1241
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001242 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001243}
1244
1245template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1246 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001247 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001248 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001249 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001250
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001251 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001252 P->r_addend = Rel.getAddend();
1253 P->r_offset = Rel.getOffset();
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001254 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001255 // Dynamic relocation against MIPS GOT section make deal TLS entries
1256 // allocated in the end of the GOT. We need to adjust the offset to take
1257 // in account 'local' and 'global' GOT entries.
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001258 P->r_offset += InX::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001259 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001260 }
1261
1262 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001263 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001264 std::stable_sort((Elf_Rela *)BufBegin,
1265 (Elf_Rela *)BufBegin + Relocs.size(),
1266 compRelocations<ELFT, Elf_Rela>);
1267 else
1268 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1269 compRelocations<ELFT, Elf_Rel>);
1270 }
1271}
1272
1273template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1274 return this->Entsize * Relocs.size();
1275}
1276
Rui Ueyama945055a2017-02-27 03:07:41 +00001277template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001278 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex
1279 : InX::SymTab->getParent()->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001280
1281 // Set required output section properties.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001282 getParent()->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001283}
1284
George Rimarf45f6812017-05-16 08:53:30 +00001285SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001286 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001287 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001288 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001289 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001290 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001291
1292// Orders symbols according to their positions in the GOT,
1293// in compliance with MIPS ABI rules.
1294// See "Global Offset Table" in Chapter 5 in the following document
1295// for detailed description:
1296// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001297static bool sortMipsSymbols(const SymbolTableEntry &L,
1298 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001299 // Sort entries related to non-local preemptible symbols by GOT indexes.
1300 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001301 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1302 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001303 if (LIsInLocalGot || RIsInLocalGot)
1304 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001305 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001306}
1307
Rui Ueyamabb07d102017-02-27 03:31:19 +00001308// Finalize a symbol table. The ELF spec requires that all local
1309// symbols precede global symbols, so we sort symbol entries in this
1310// function. (For .dynsym, we don't do that because symbols for
1311// dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001312void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001313 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001314
Rui Ueyama6e967342017-02-28 03:29:12 +00001315 // If it is a .dynsym, there should be no local symbols, but we need
1316 // to do a few things for the dynamic linker.
1317 if (this->Type == SHT_DYNSYM) {
1318 // Section's Info field has the index of the first non-local symbol.
1319 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001320 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001321
George Rimarf45f6812017-05-16 08:53:30 +00001322 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001323 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001324 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001325 } else if (Config->EMachine == EM_MIPS) {
1326 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1327 }
1328
1329 size_t I = 0;
1330 for (const SymbolTableEntry &S : Symbols)
1331 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001332 return;
Peter Smith55865432017-02-20 11:12:33 +00001333 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001334}
Peter Smith55865432017-02-20 11:12:33 +00001335
George Rimarf45f6812017-05-16 08:53:30 +00001336void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001337 if (this->Type == SHT_DYNSYM)
1338 return;
1339 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001340 auto It = std::stable_partition(
1341 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1342 return S.Symbol->isLocal() ||
1343 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1344 });
1345 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001346 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001347}
1348
George Rimarf45f6812017-05-16 08:53:30 +00001349void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001350 // Adding a local symbol to a .dynsym is a bug.
1351 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001352
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001353 bool HashIt = B->isLocal();
1354 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001355}
1356
George Rimarf45f6812017-05-16 08:53:30 +00001357size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001358 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1359 if (E.Symbol == Body)
1360 return true;
1361 // This is used for -r, so we have to handle multiple section
1362 // symbols being combined.
1363 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola0dc25102017-05-31 19:26:37 +00001364 return Body->getOutputSection() == E.Symbol->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001365 return false;
1366 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001367 if (I == Symbols.end())
1368 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001369 return I - Symbols.begin() + 1;
1370}
1371
George Rimarf45f6812017-05-16 08:53:30 +00001372template <class ELFT>
1373SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1374 : SymbolTableBaseSection(StrTabSec) {
1375 this->Entsize = sizeof(Elf_Sym);
1376}
1377
Rui Ueyama1f032532017-02-28 01:56:36 +00001378// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001379template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001380 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001381 Buf += sizeof(Elf_Sym);
1382
Eugene Leviant9230db92016-11-17 09:16:34 +00001383 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001384
Rui Ueyama1f032532017-02-28 01:56:36 +00001385 for (SymbolTableEntry &Ent : Symbols) {
1386 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001387
Rui Ueyama1b003182017-02-28 19:22:09 +00001388 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001389 if (Body->isLocal()) {
1390 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1391 } else {
1392 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1393 ESym->setVisibility(Body->symbol()->Visibility);
1394 }
1395
1396 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001397
Rui Ueyama1b003182017-02-28 19:22:09 +00001398 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001399 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001400 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001401 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001402 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001403 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001404 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001405
George Rimardbe843d2017-06-28 09:51:33 +00001406 // Copy symbol size if it is a defined symbol. st_size is not significant
1407 // for undefined symbols, so whether copying it or not is up to us if that's
1408 // the case. We'll leave it as zero because by not setting a value, we can
1409 // get the exact same outputs for two sets of input files that differ only
1410 // in undefined symbol size in DSOs.
1411 if (ESym->st_shndx != SHN_UNDEF)
1412 ESym->st_size = Body->getSize<ELFT>();
1413
Rui Ueyama1b003182017-02-28 19:22:09 +00001414 // st_value is usually an address of a symbol, but that has a
1415 // special meaining for uninstantiated common symbols (this can
1416 // occur if -r is given).
1417 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001418 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001419 else
George Rimarf64618a2017-03-17 11:56:54 +00001420 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001421
Rui Ueyama1f032532017-02-28 01:56:36 +00001422 ++ESym;
1423 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001424
Rui Ueyama1f032532017-02-28 01:56:36 +00001425 // On MIPS we need to mark symbol which has a PLT entry and requires
1426 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1427 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1428 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1429 if (Config->EMachine == EM_MIPS) {
1430 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1431
1432 for (SymbolTableEntry &Ent : Symbols) {
1433 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001434 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001435 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001436
1437 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001438 if (auto *D = dyn_cast<DefinedRegular>(Body))
1439 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001440 ESym->st_other |= STO_MIPS_PIC;
1441 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001442 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001443 }
1444}
1445
Rui Ueyamae4120632017-02-28 22:05:13 +00001446// .hash and .gnu.hash sections contain on-disk hash tables that map
1447// symbol names to their dynamic symbol table indices. Their purpose
1448// is to help the dynamic linker resolve symbols quickly. If ELF files
1449// don't have them, the dynamic linker has to do linear search on all
1450// dynamic symbols, which makes programs slower. Therefore, a .hash
1451// section is added to a DSO by default. A .gnu.hash is added if you
1452// give the -hash-style=gnu or -hash-style=both option.
1453//
1454// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1455// Each ELF file has a list of DSOs that the ELF file depends on and a
1456// list of dynamic symbols that need to be resolved from any of the
1457// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1458// where m is the number of DSOs and n is the number of dynamic
1459// symbols. For modern large programs, both m and n are large. So
1460// making each step faster by using hash tables substiantially
1461// improves time to load programs.
1462//
1463// (Note that this is not the only way to design the shared library.
1464// For instance, the Windows DLL takes a different approach. On
1465// Windows, each dynamic symbol has a name of DLL from which the symbol
1466// has to be resolved. That makes the cost of symbol resolution O(n).
1467// This disables some hacky techniques you can use on Unix such as
1468// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1469//
1470// Due to historical reasons, we have two different hash tables, .hash
1471// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1472// and better version of .hash. .hash is just an on-disk hash table, but
1473// .gnu.hash has a bloom filter in addition to a hash table to skip
1474// DSOs very quickly. If you are sure that your dynamic linker knows
1475// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1476// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001477GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001478 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1479}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001480
George Rimarf45f6812017-05-16 08:53:30 +00001481void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001482 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001483
1484 // Computes bloom filter size in word size. We want to allocate 8
1485 // bits for each symbol. It must be a power of two.
1486 if (Symbols.empty())
1487 MaskWords = 1;
1488 else
George Rimar5f73bc92017-03-29 15:23:28 +00001489 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001490
George Rimar5f73bc92017-03-29 15:23:28 +00001491 Size = 16; // Header
1492 Size += Config->Wordsize * MaskWords; // Bloom filter
1493 Size += NBuckets * 4; // Hash buckets
1494 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001495}
1496
George Rimarf45f6812017-05-16 08:53:30 +00001497void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001498 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001499 write32(Buf, NBuckets, Config->Endianness);
George Rimarf45f6812017-05-16 08:53:30 +00001500 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
George Rimar5f73bc92017-03-29 15:23:28 +00001501 Config->Endianness);
1502 write32(Buf + 8, MaskWords, Config->Endianness);
1503 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001504 Buf += 16;
1505
Rui Ueyama7986b452017-03-01 18:09:09 +00001506 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001507 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001508 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001509 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001510}
1511
Rui Ueyama7986b452017-03-01 18:09:09 +00001512// This function writes a 2-bit bloom filter. This bloom filter alone
1513// usually filters out 80% or more of all symbol lookups [1].
1514// The dynamic linker uses the hash table only when a symbol is not
1515// filtered out by a bloom filter.
1516//
1517// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1518// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001519void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001520 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001521 for (const Entry &Sym : Symbols) {
1522 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001523 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1524 Val |= uint64_t(1) << (Sym.Hash % C);
1525 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1526 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001527 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001528}
1529
George Rimarf45f6812017-05-16 08:53:30 +00001530void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001531 // Group symbols by hash value.
1532 std::vector<std::vector<Entry>> Syms(NBuckets);
1533 for (const Entry &Ent : Symbols)
1534 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001535
Rui Ueyamae13373b2017-03-01 02:51:42 +00001536 // Write hash buckets. Hash buckets contain indices in the following
1537 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001538 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001539 for (size_t I = 0; I < NBuckets; ++I)
1540 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001541 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001542
1543 // Write a hash value table. It represents a sequence of chains that
1544 // share the same hash modulo value. The last element of each chain
1545 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001546 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001547 size_t I = 0;
1548 for (std::vector<Entry> &Vec : Syms) {
1549 if (Vec.empty())
1550 continue;
1551 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001552 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1553 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001554 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001555}
1556
1557static uint32_t hashGnu(StringRef Name) {
1558 uint32_t H = 5381;
1559 for (uint8_t C : Name)
1560 H = (H << 5) + H + C;
1561 return H;
1562}
1563
Rui Ueyamae13373b2017-03-01 02:51:42 +00001564// Returns a number of hash buckets to accomodate given number of elements.
1565// We want to choose a moderate number that is not too small (which
1566// causes too many hash collisions) and not too large (which wastes
1567// disk space.)
1568//
1569// We return a prime number because it (is believed to) achieve good
1570// hash distribution.
1571static size_t getBucketSize(size_t NumSymbols) {
1572 // List of largest prime numbers that are not greater than 2^n + 1.
1573 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1574 251, 127, 61, 31, 13, 7, 3, 1})
1575 if (N <= NumSymbols)
1576 return N;
1577 return 0;
1578}
1579
Eugene Leviantbe809a72016-11-18 06:44:18 +00001580// Add symbols to this symbol hash table. Note that this function
1581// destructively sort a given vector -- which is needed because
1582// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001583void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001584 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1585 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001586 std::vector<SymbolTableEntry>::iterator Mid =
1587 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1588 return S.Symbol->isUndefined();
1589 });
1590 if (Mid == V.end())
1591 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001592
1593 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1594 SymbolBody *B = Ent.Symbol;
1595 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001596 }
1597
Rui Ueyamae13373b2017-03-01 02:51:42 +00001598 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001599 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001600 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001601 return L.Hash % NBuckets < R.Hash % NBuckets;
1602 });
1603
1604 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001605 for (const Entry &Ent : Symbols)
1606 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001607}
1608
Eugene Leviantb96e8092016-11-18 09:06:47 +00001609template <class ELFT>
1610HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001611 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1612 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001613}
1614
Rui Ueyama945055a2017-02-27 03:07:41 +00001615template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001616 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001617
George Rimar67c60722017-07-18 11:55:35 +00001618 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001619 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001620
1621 // Create as many buckets as there are symbols.
1622 // FIXME: This is simplistic. We can try to optimize it, but implementing
1623 // support for SHT_GNU_HASH is probably even more profitable.
George Rimar69b17c32017-05-16 10:04:42 +00001624 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001625 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001626}
1627
1628template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001629 // A 32-bit integer type in the target endianness.
1630 typedef typename ELFT::Word Elf_Word;
1631
George Rimar69b17c32017-05-16 10:04:42 +00001632 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001633
Eugene Leviantb96e8092016-11-18 09:06:47 +00001634 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1635 *P++ = NumSymbols; // nbucket
1636 *P++ = NumSymbols; // nchain
1637
1638 Elf_Word *Buckets = P;
1639 Elf_Word *Chains = P + NumSymbols;
1640
George Rimar69b17c32017-05-16 10:04:42 +00001641 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001642 SymbolBody *Body = S.Symbol;
1643 StringRef Name = Body->getName();
1644 unsigned I = Body->DynsymIndex;
1645 uint32_t Hash = hashSysV(Name) % NumSymbols;
1646 Chains[I] = Buckets[Hash];
1647 Buckets[Hash] = I;
1648 }
1649}
1650
George Rimardfc020e2017-03-17 11:01:57 +00001651PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001652 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001653 HeaderSize(S) {
1654 // The PLT needs to be writable on SPARC as the dynamic linker will
1655 // modify the instructions in the PLT entries.
1656 if (Config->EMachine == EM_SPARCV9)
1657 this->Flags |= SHF_WRITE;
1658}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001659
George Rimardfc020e2017-03-17 11:01:57 +00001660void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001661 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1662 // linker to resolve dynsyms at runtime. Write such code.
1663 if (HeaderSize != 0)
1664 Target->writePltHeader(Buf);
1665 size_t Off = HeaderSize;
1666 // The IPlt is immediately after the Plt, account for this in RelOff
1667 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001668
1669 for (auto &I : Entries) {
1670 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001671 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001672 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001673 uint64_t Plt = this->getVA() + Off;
1674 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1675 Off += Target->PltEntrySize;
1676 }
1677}
1678
George Rimardfc020e2017-03-17 11:01:57 +00001679template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001680 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001681 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1682 if (HeaderSize == 0) {
1683 PltRelocSection = In<ELFT>::RelaIplt;
1684 Sym.IsInIplt = true;
1685 }
1686 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001687 Entries.push_back(std::make_pair(&Sym, RelOff));
1688}
1689
George Rimardfc020e2017-03-17 11:01:57 +00001690size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001691 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001692}
1693
Peter Smith96943762017-01-25 10:31:16 +00001694// Some architectures such as additional symbols in the PLT section. For
1695// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001696void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001697 // The PLT may have symbols defined for the Header, the IPLT has no header
1698 if (HeaderSize != 0)
1699 Target->addPltHeaderSymbols(this);
1700 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001701 for (size_t I = 0; I < Entries.size(); ++I) {
1702 Target->addPltSymbols(this, Off);
1703 Off += Target->PltEntrySize;
1704 }
1705}
1706
George Rimardfc020e2017-03-17 11:01:57 +00001707unsigned PltSection::getPltRelocOff() const {
1708 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001709}
1710
Rui Ueyama2114cab2017-08-15 17:01:17 +00001711// The hash function used for .gdb_index version 5 or above.
1712static uint32_t gdbHash(StringRef Str) {
George Rimarec02b8d2016-12-15 12:07:53 +00001713 uint32_t R = 0;
1714 for (uint8_t C : Str)
1715 R = R * 67 + tolower(C) - 113;
1716 return R;
1717}
1718
Rafael Espindola300b3862017-07-12 23:56:53 +00001719static std::vector<CompilationUnitEntry> readCuList(DWARFContext &Dwarf) {
George Rimar86665622017-06-07 16:59:11 +00001720 std::vector<CompilationUnitEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001721 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
Rafael Espindola300b3862017-07-12 23:56:53 +00001722 Ret.push_back({CU->getOffset(), CU->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001723 return Ret;
1724}
1725
George Rimar86665622017-06-07 16:59:11 +00001726static std::vector<AddressEntry> readAddressArea(DWARFContext &Dwarf,
1727 InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001728 std::vector<AddressEntry> Ret;
1729
George Rimar86665622017-06-07 16:59:11 +00001730 uint32_t CurrentCu = 0;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001731 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1732 DWARFAddressRangesVector Ranges;
1733 CU->collectAddressRanges(Ranges);
1734
George Rimar35e846e2017-03-21 08:19:34 +00001735 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001736 for (DWARFAddressRange &R : Ranges) {
1737 InputSectionBase *S = Sections[R.SectionIndex];
1738 if (!S || S == &InputSection::Discarded || !S->Live)
1739 continue;
1740 // Range list with zero size has no effect.
1741 if (R.LowPC == R.HighPC)
1742 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001743 auto *IS = cast<InputSection>(S);
1744 uint64_t Offset = IS->getOffsetInFile();
1745 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CurrentCu});
George Rimar0641b8b2017-06-07 10:52:02 +00001746 }
George Rimar86665622017-06-07 16:59:11 +00001747 ++CurrentCu;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001748 }
1749 return Ret;
1750}
1751
George Rimar86665622017-06-07 16:59:11 +00001752static std::vector<NameTypeEntry> readPubNamesAndTypes(DWARFContext &Dwarf,
1753 bool IsLE) {
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001754 StringRef Data[] = {Dwarf.getDWARFObj().getGnuPubNamesSection(),
1755 Dwarf.getDWARFObj().getGnuPubTypesSection()};
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001756
George Rimar86665622017-06-07 16:59:11 +00001757 std::vector<NameTypeEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001758 for (StringRef D : Data) {
1759 DWARFDebugPubTable PubTable(D, IsLE, true);
1760 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1761 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1762 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1763 }
1764 return Ret;
1765}
1766
George Rimar86665622017-06-07 16:59:11 +00001767static std::vector<InputSection *> getDebugInfoSections() {
1768 std::vector<InputSection *> Ret;
1769 for (InputSectionBase *S : InputSections)
1770 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001771 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001772 Ret.push_back(IS);
1773 return Ret;
1774}
1775
1776void GdbIndexSection::buildIndex() {
Rafael Espindola300b3862017-07-12 23:56:53 +00001777 if (Chunks.empty())
George Rimar86665622017-06-07 16:59:11 +00001778 return;
1779
George Rimar86665622017-06-07 16:59:11 +00001780 uint32_t CuId = 0;
1781 for (GdbIndexChunk &D : Chunks) {
1782 for (AddressEntry &E : D.AddressArea)
1783 E.CuIndex += CuId;
1784
1785 // Populate constant pool area.
1786 for (NameTypeEntry &NameType : D.NamesAndTypes) {
Rui Ueyama2114cab2017-08-15 17:01:17 +00001787 uint32_t Hash = gdbHash(NameType.Name);
George Rimar86665622017-06-07 16:59:11 +00001788 size_t Offset = StringPool.add(NameType.Name);
1789
1790 bool IsNew;
1791 GdbSymbol *Sym;
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001792 std::tie(IsNew, Sym) = HashTab.add(Hash, Offset);
George Rimar86665622017-06-07 16:59:11 +00001793 if (IsNew) {
1794 Sym->CuVectorIndex = CuVectors.size();
George Rimarb4b7b742017-06-09 04:48:56 +00001795 CuVectors.resize(CuVectors.size() + 1);
George Rimar86665622017-06-07 16:59:11 +00001796 }
1797
1798 CuVectors[Sym->CuVectorIndex].insert(CuId | (NameType.Type << 24));
1799 }
1800
1801 CuId += D.CompilationUnits.size();
1802 }
1803}
1804
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001805static GdbIndexChunk readDwarf(DWARFContext &Dwarf, InputSection *Sec) {
George Rimar86665622017-06-07 16:59:11 +00001806 GdbIndexChunk Ret;
Rafael Espindola300b3862017-07-12 23:56:53 +00001807 Ret.DebugInfoSec = Sec;
1808 Ret.CompilationUnits = readCuList(Dwarf);
George Rimar86665622017-06-07 16:59:11 +00001809 Ret.AddressArea = readAddressArea(Dwarf, Sec);
1810 Ret.NamesAndTypes = readPubNamesAndTypes(Dwarf, Config->IsLE);
1811 return Ret;
1812}
George Rimar8b547392016-12-15 09:08:13 +00001813
Rafael Espindola300b3862017-07-12 23:56:53 +00001814template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
George Rimar2d23da02017-08-01 14:57:13 +00001815 std::vector<InputSection *> Sections = getDebugInfoSections();
1816 std::vector<GdbIndexChunk> Chunks(Sections.size());
1817 parallelForEachN(0, Chunks.size(), [&](size_t I) {
1818 ObjFile<ELFT> *F = Sections[I]->getFile<ELFT>();
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001819 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(F));
George Rimar2d23da02017-08-01 14:57:13 +00001820 Chunks[I] = readDwarf(Dwarf, Sections[I]);
1821 });
Rafael Espindola300b3862017-07-12 23:56:53 +00001822 return make<GdbIndexSection>(std::move(Chunks));
1823}
1824
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001825static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001826 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001827 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00001828 Ret += D.CompilationUnits.size();
1829 return Ret;
1830}
George Rimarec02b8d2016-12-15 12:07:53 +00001831
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001832static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001833 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001834 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00001835 Ret += D.AddressArea.size();
1836 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00001837}
1838
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001839GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
1840 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
1841 StringPool(llvm::StringTableBuilder::ELF), Chunks(std::move(C)) {
George Rimar86665622017-06-07 16:59:11 +00001842 buildIndex();
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001843 HashTab.finalizeContents();
Eugene Levianta113a412016-11-21 09:24:43 +00001844
1845 // GdbIndex header consist from version fields
1846 // and 5 more fields with different kinds of offsets.
George Rimar86665622017-06-07 16:59:11 +00001847 CuTypesOffset = CuListOffset + getCuSize(Chunks) * CompilationUnitSize;
1848 SymTabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * AddressEntrySize;
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001849 ConstantPoolOffset = SymTabOffset + HashTab.getCapacity() * SymTabEntrySize;
George Rimarec02b8d2016-12-15 12:07:53 +00001850
George Rimarc1a03642017-05-26 12:09:26 +00001851 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001852 CuVectorsOffset.push_back(CuVectorsSize);
1853 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1854 }
1855 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
George Rimarec02b8d2016-12-15 12:07:53 +00001856 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001857}
1858
George Rimar35e846e2017-03-21 08:19:34 +00001859size_t GdbIndexSection::getSize() const {
George Rimarec02b8d2016-12-15 12:07:53 +00001860 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001861}
1862
George Rimar35e846e2017-03-21 08:19:34 +00001863void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001864 write32le(Buf, 7); // Write version
1865 write32le(Buf + 4, CuListOffset); // CU list offset
1866 write32le(Buf + 8, CuTypesOffset); // Types CU list offset
1867 write32le(Buf + 12, CuTypesOffset); // Address area offset
1868 write32le(Buf + 16, SymTabOffset); // Symbol table offset
1869 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset
Eugene Levianta113a412016-11-21 09:24:43 +00001870 Buf += 24;
1871
1872 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00001873 for (GdbIndexChunk &D : Chunks) {
1874 for (CompilationUnitEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00001875 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00001876 write64le(Buf + 8, Cu.CuLength);
1877 Buf += 16;
1878 }
Eugene Levianta113a412016-11-21 09:24:43 +00001879 }
George Rimar8b547392016-12-15 09:08:13 +00001880
1881 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00001882 for (GdbIndexChunk &D : Chunks) {
1883 for (AddressEntry &E : D.AddressArea) {
1884 uint64_t BaseAddr =
1885 E.Section->getParent()->Addr + E.Section->getOffset(0);
1886 write64le(Buf, BaseAddr + E.LowAddress);
1887 write64le(Buf + 8, BaseAddr + E.HighAddress);
1888 write32le(Buf + 16, E.CuIndex);
1889 Buf += 20;
1890 }
George Rimar8b547392016-12-15 09:08:13 +00001891 }
George Rimarec02b8d2016-12-15 12:07:53 +00001892
1893 // Write the symbol table.
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001894 for (size_t I = 0; I < HashTab.getCapacity(); ++I) {
1895 GdbSymbol *Sym = HashTab.getSymbol(I);
George Rimarec02b8d2016-12-15 12:07:53 +00001896 if (Sym) {
1897 size_t NameOffset =
1898 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1899 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1900 write32le(Buf, NameOffset);
1901 write32le(Buf + 4, CuVectorOffset);
1902 }
1903 Buf += 8;
1904 }
1905
1906 // Write the CU vectors into the constant pool.
George Rimarc1a03642017-05-26 12:09:26 +00001907 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001908 write32le(Buf, CuVec.size());
1909 Buf += 4;
George Rimar5f5905e2017-05-26 12:01:40 +00001910 for (uint32_t Val : CuVec) {
1911 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00001912 Buf += 4;
1913 }
1914 }
1915
1916 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001917}
1918
George Rimar67c60722017-07-18 11:55:35 +00001919bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00001920
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001921template <class ELFT>
1922EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001923 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001924
1925// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1926// Each entry of the search table consists of two values,
1927// the starting PC from where FDEs covers, and the FDE's address.
1928// It is sorted by PC.
1929template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1930 const endianness E = ELFT::TargetEndianness;
1931
1932 // Sort the FDE list by their PC and uniqueify. Usually there is only
1933 // one FDE for a PC (i.e. function), but if ICF merges two functions
1934 // into one, there can be more than one FDEs pointing to the address.
1935 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1936 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1937 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1938 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1939
1940 Buf[0] = 1;
1941 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1942 Buf[2] = DW_EH_PE_udata4;
1943 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001944 write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001945 write32<E>(Buf + 8, Fdes.size());
1946 Buf += 12;
1947
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001948 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001949 for (FdeData &Fde : Fdes) {
1950 write32<E>(Buf, Fde.Pc - VA);
1951 write32<E>(Buf + 4, Fde.FdeVA - VA);
1952 Buf += 8;
1953 }
1954}
1955
1956template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1957 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001958 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001959}
1960
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001961template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001962void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1963 Fdes.push_back({Pc, FdeVA});
1964}
1965
George Rimar11992c862016-11-25 08:05:41 +00001966template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001967 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001968}
1969
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001970template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001971VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001972 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1973 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001974
1975static StringRef getFileDefName() {
1976 if (!Config->SoName.empty())
1977 return Config->SoName;
1978 return Config->OutputFile;
1979}
1980
Rui Ueyama945055a2017-02-27 03:07:41 +00001981template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00001982 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001983 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00001984 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001985
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001986 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001987
1988 // sh_info should be set to the number of definitions. This fact is missed in
1989 // documentation, but confirmed by binutils community:
1990 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001991 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001992}
1993
1994template <class ELFT>
1995void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1996 StringRef Name, size_t NameOff) {
1997 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1998 Verdef->vd_version = 1;
1999 Verdef->vd_cnt = 1;
2000 Verdef->vd_aux = sizeof(Elf_Verdef);
2001 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2002 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2003 Verdef->vd_ndx = Index;
2004 Verdef->vd_hash = hashSysV(Name);
2005
2006 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2007 Verdaux->vda_name = NameOff;
2008 Verdaux->vda_next = 0;
2009}
2010
2011template <class ELFT>
2012void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2013 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2014
2015 for (VersionDefinition &V : Config->VersionDefinitions) {
2016 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2017 writeOne(Buf, V.Id, V.Name, V.NameOff);
2018 }
2019
2020 // Need to terminate the last version definition.
2021 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2022 Verdef->vd_next = 0;
2023}
2024
2025template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2026 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2027}
2028
2029template <class ELFT>
2030VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002031 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002032 ".gnu.version") {
2033 this->Entsize = sizeof(Elf_Versym);
2034}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002035
Rui Ueyama945055a2017-02-27 03:07:41 +00002036template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002037 // At the moment of june 2016 GNU docs does not mention that sh_link field
2038 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002039 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002040}
2041
2042template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002043 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002044}
2045
2046template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2047 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002048 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002049 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2050 ++OutVersym;
2051 }
2052}
2053
George Rimar11992c862016-11-25 08:05:41 +00002054template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2055 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2056}
2057
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002058template <class ELFT>
2059VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002060 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2061 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002062 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2063 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2064 // First identifiers are reserved by verdef section if it exist.
2065 NextIndex = getVerDefNum() + 1;
2066}
2067
2068template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002069void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2070 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2071 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002072 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2073 return;
2074 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002075
Rafael Espindola6e93d052017-08-04 22:31:42 +00002076 SharedFile<ELFT> *File = SS->getFile<ELFT>();
Rui Ueyama4076fa12017-02-26 23:35:34 +00002077
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002078 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2079 // to create one by adding it to our needed list and creating a dynstr entry
2080 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002081 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002082 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002083 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002084 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2085 // prepare to create one by allocating a version identifier and creating a
2086 // dynstr entry for the version name.
2087 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002088 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2089 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002090 NV.Index = NextIndex++;
2091 }
2092 SS->symbol()->VersionId = NV.Index;
2093}
2094
2095template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2096 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2097 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2098 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2099
2100 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2101 // Create an Elf_Verneed for this DSO.
2102 Verneed->vn_version = 1;
2103 Verneed->vn_cnt = P.first->VerdefMap.size();
2104 Verneed->vn_file = P.second;
2105 Verneed->vn_aux =
2106 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2107 Verneed->vn_next = sizeof(Elf_Verneed);
2108 ++Verneed;
2109
2110 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2111 // VerdefMap, which will only contain references to needed version
2112 // definitions. Each Elf_Vernaux is based on the information contained in
2113 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2114 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2115 // data structures within a single input file.
2116 for (auto &NV : P.first->VerdefMap) {
2117 Vernaux->vna_hash = NV.first->vd_hash;
2118 Vernaux->vna_flags = 0;
2119 Vernaux->vna_other = NV.second.Index;
2120 Vernaux->vna_name = NV.second.StrTab;
2121 Vernaux->vna_next = sizeof(Elf_Vernaux);
2122 ++Vernaux;
2123 }
2124
2125 Vernaux[-1].vna_next = 0;
2126 }
2127 Verneed[-1].vn_next = 0;
2128}
2129
Rui Ueyama945055a2017-02-27 03:07:41 +00002130template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002131 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2132 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002133}
2134
2135template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2136 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2137 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2138 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2139 return Size;
2140}
2141
George Rimar11992c862016-11-25 08:05:41 +00002142template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2143 return getNeedNum() == 0;
2144}
2145
Rafael Espindola6119b862017-03-06 20:23:56 +00002146MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002147 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002148 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002149 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002150
Rafael Espindola6119b862017-03-06 20:23:56 +00002151void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002152 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002153 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002154}
2155
Rafael Espindola6119b862017-03-06 20:23:56 +00002156void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002157
Rafael Espindola6119b862017-03-06 20:23:56 +00002158bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002159 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2160}
2161
Rafael Espindola6119b862017-03-06 20:23:56 +00002162void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002163 // Add all string pieces to the string table builder to create section
2164 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002165 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002166 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2167 if (Sec->Pieces[I].Live)
2168 Builder.add(Sec->getData(I));
2169
2170 // Fix the string table content. After this, the contents will never change.
2171 Builder.finalize();
2172
2173 // finalize() fixed tail-optimized strings, so we can now get
2174 // offsets of strings. Get an offset for each string and save it
2175 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002176 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002177 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2178 if (Sec->Pieces[I].Live)
2179 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2180}
2181
Rafael Espindola6119b862017-03-06 20:23:56 +00002182void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002183 // Add all string pieces to the string table builder to create section
2184 // contents. Because we are not tail-optimizing, offsets of strings are
2185 // fixed when they are added to the builder (string table builder contains
2186 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002187 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002188 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2189 if (Sec->Pieces[I].Live)
2190 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2191
2192 Builder.finalizeInOrder();
2193}
2194
Rafael Espindola6119b862017-03-06 20:23:56 +00002195void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002196 if (shouldTailMerge())
2197 finalizeTailMerge();
2198 else
2199 finalizeNoTailMerge();
2200}
2201
George Rimar67c60722017-07-18 11:55:35 +00002202size_t MergeSyntheticSection::getSize() const { return Builder.getSize(); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002203
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002204// This function decompresses compressed sections and scans over the input
2205// sections to create mergeable synthetic sections. It removes
2206// MergeInputSections from the input section array and adds new synthetic
2207// sections at the location of the first input section that it replaces. It then
2208// finalizes each synthetic section in order to compute an output offset for
2209// each piece of each input section.
2210void elf::decompressAndMergeSections() {
2211 // splitIntoPieces needs to be called on each MergeInputSection before calling
2212 // finalizeContents(). Do that first.
George Rimara9b07142017-08-04 08:30:16 +00002213 parallelForEach(InputSections, [](InputSectionBase *S) {
2214 if (!S->Live)
2215 return;
2216 if (Decompressor::isCompressedELFSection(S->Flags, S->Name))
2217 S->uncompress();
2218 if (auto *MS = dyn_cast<MergeInputSection>(S))
2219 MS->splitIntoPieces();
2220 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002221
2222 std::vector<MergeSyntheticSection *> MergeSections;
2223 for (InputSectionBase *&S : InputSections) {
2224 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2225 if (!MS)
2226 continue;
2227
2228 // We do not want to handle sections that are not alive, so just remove
2229 // them instead of trying to merge.
2230 if (!MS->Live)
2231 continue;
2232
2233 StringRef OutsecName = getOutputSectionName(MS->Name);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002234 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2235
2236 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002237 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002238 Sec->Alignment == Alignment;
2239 });
2240 if (I == MergeSections.end()) {
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002241 MergeSyntheticSection *Syn = make<MergeSyntheticSection>(
2242 OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002243 MergeSections.push_back(Syn);
2244 I = std::prev(MergeSections.end());
2245 S = Syn;
2246 } else {
2247 S = nullptr;
2248 }
2249 (*I)->addSection(MS);
2250 }
2251 for (auto *MS : MergeSections)
2252 MS->finalizeContents();
2253
2254 std::vector<InputSectionBase *> &V = InputSections;
2255 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2256}
2257
George Rimar42886c42017-03-15 12:02:31 +00002258MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002259 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2260 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002261
George Rimar90a528b2017-03-21 09:01:39 +00002262ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002263 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002264 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002265
2266// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2267// This section will have been sorted last in the .ARM.exidx table.
2268// This table entry will have the form:
2269// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002270// The sentinel must have the PREL31 value of an address higher than any
2271// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002272void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002273 // The Sections are sorted in order of ascending PREL31 address with the
2274 // sentinel last. We need to find the InputSection that precedes the
2275 // sentinel. By construction the Sentinel is in the last
2276 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +00002277 OutputSection *C = getParent();
Peter Smithea79b212017-05-31 09:02:21 +00002278 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
2279 [](const BaseCommand *Base) {
2280 return isa<InputSectionDescription>(Base);
2281 });
2282 auto L = cast<InputSectionDescription>(*ISD);
2283 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002284 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002285 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002286 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002287 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2288 write32le(Buf + 4, 0x1);
2289}
2290
George Rimar7b827042017-03-16 10:40:50 +00002291ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002292 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002293 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002294 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002295 this->OutSecOff = Off;
2296}
2297
George Rimar7b827042017-03-16 10:40:50 +00002298void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002299 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002300 T->Offset = Off;
2301 Thunks.push_back(T);
2302 T->addSymbols(*this);
2303 Size = Off + T->size();
2304}
2305
George Rimar7b827042017-03-16 10:40:50 +00002306void ThunkSection::writeTo(uint8_t *Buf) {
2307 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002308 T->writeTo(Buf + T->Offset, *this);
2309}
2310
George Rimar7b827042017-03-16 10:40:50 +00002311InputSection *ThunkSection::getTargetInputSection() const {
2312 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002313 return T->getTargetInputSection();
2314}
2315
George Rimar9782ca52017-03-15 15:29:29 +00002316InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002317BssSection *InX::Bss;
2318BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002319BuildIdSection *InX::BuildId;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002320SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002321StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002322SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002323InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002324GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002325GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002326GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002327GnuHashTableSection *InX::GnuHashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002328IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002329MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002330MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002331PltSection *InX::Plt;
2332PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002333StringTableSection *InX::ShStrTab;
2334StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002335SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002336
Rafael Espindola300b3862017-07-12 23:56:53 +00002337template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2338template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2339template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2340template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2341
George Rimara9189572017-03-17 16:50:07 +00002342template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2343template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2344template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2345template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2346
Rafael Espindola6119b862017-03-06 20:23:56 +00002347template MergeInputSection *elf::createCommentSection<ELF32LE>();
2348template MergeInputSection *elf::createCommentSection<ELF32BE>();
2349template MergeInputSection *elf::createCommentSection<ELF64LE>();
2350template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002351
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002352template class elf::MipsAbiFlagsSection<ELF32LE>;
2353template class elf::MipsAbiFlagsSection<ELF32BE>;
2354template class elf::MipsAbiFlagsSection<ELF64LE>;
2355template class elf::MipsAbiFlagsSection<ELF64BE>;
2356
Simon Atanasyance02cf02016-11-09 21:36:56 +00002357template class elf::MipsOptionsSection<ELF32LE>;
2358template class elf::MipsOptionsSection<ELF32BE>;
2359template class elf::MipsOptionsSection<ELF64LE>;
2360template class elf::MipsOptionsSection<ELF64BE>;
2361
2362template class elf::MipsReginfoSection<ELF32LE>;
2363template class elf::MipsReginfoSection<ELF32BE>;
2364template class elf::MipsReginfoSection<ELF64LE>;
2365template class elf::MipsReginfoSection<ELF64BE>;
2366
Eugene Leviant6380ce22016-11-15 12:26:55 +00002367template class elf::DynamicSection<ELF32LE>;
2368template class elf::DynamicSection<ELF32BE>;
2369template class elf::DynamicSection<ELF64LE>;
2370template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002371
2372template class elf::RelocationSection<ELF32LE>;
2373template class elf::RelocationSection<ELF32BE>;
2374template class elf::RelocationSection<ELF64LE>;
2375template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002376
2377template class elf::SymbolTableSection<ELF32LE>;
2378template class elf::SymbolTableSection<ELF32BE>;
2379template class elf::SymbolTableSection<ELF64LE>;
2380template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002381
Eugene Leviantb96e8092016-11-18 09:06:47 +00002382template class elf::HashTableSection<ELF32LE>;
2383template class elf::HashTableSection<ELF32BE>;
2384template class elf::HashTableSection<ELF64LE>;
2385template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002386
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002387template class elf::EhFrameHeader<ELF32LE>;
2388template class elf::EhFrameHeader<ELF32BE>;
2389template class elf::EhFrameHeader<ELF64LE>;
2390template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002391
2392template class elf::VersionTableSection<ELF32LE>;
2393template class elf::VersionTableSection<ELF32BE>;
2394template class elf::VersionTableSection<ELF64LE>;
2395template class elf::VersionTableSection<ELF64BE>;
2396
2397template class elf::VersionNeedSection<ELF32LE>;
2398template class elf::VersionNeedSection<ELF32BE>;
2399template class elf::VersionNeedSection<ELF64LE>;
2400template class elf::VersionNeedSection<ELF64BE>;
2401
2402template class elf::VersionDefinitionSection<ELF32LE>;
2403template class elf::VersionDefinitionSection<ELF32BE>;
2404template class elf::VersionDefinitionSection<ELF64LE>;
2405template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002406
Rafael Espindola66b4e212017-02-23 22:06:28 +00002407template class elf::EhFrameSection<ELF32LE>;
2408template class elf::EhFrameSection<ELF32BE>;
2409template class elf::EhFrameSection<ELF64LE>;
2410template class elf::EhFrameSection<ELF64BE>;