blob: 995d05692ee284e55e1e0a69b0f0d55067e78a53 [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
Rui Ueyamae8a61022016-11-05 23:05:47 +000057template <class ELFT> static std::vector<DefinedCommon *> getCommonSymbols() {
58 std::vector<DefinedCommon *> V;
59 for (Symbol *S : Symtab<ELFT>::X->getSymbols())
60 if (auto *B = dyn_cast<DefinedCommon>(S->body()))
61 V.push_back(B);
62 return V;
63}
64
65// Find all common symbols and allocate space for them.
Rafael Espindola774ea7d2017-02-23 16:49:07 +000066template <class ELFT> InputSection *elf::createCommonSection() {
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000067 if (!Config->DefineCommon)
George Rimar176d6062017-03-17 13:31:07 +000068 return nullptr;
Rui Ueyamab2a23cf2017-01-24 03:41:20 +000069
Rui Ueyamae8a61022016-11-05 23:05:47 +000070 // Sort the common symbols by alignment as an heuristic to pack them better.
71 std::vector<DefinedCommon *> Syms = getCommonSymbols<ELFT>();
George Rimar176d6062017-03-17 13:31:07 +000072 if (Syms.empty())
73 return nullptr;
74
Rui Ueyamae8a61022016-11-05 23:05:47 +000075 std::stable_sort(Syms.begin(), Syms.end(),
76 [](const DefinedCommon *A, const DefinedCommon *B) {
77 return A->Alignment > B->Alignment;
78 });
79
Rui Ueyamac95671b2017-03-29 00:49:29 +000080 BssSection *Sec = make<BssSection>("COMMON");
81 for (DefinedCommon *Sym : Syms)
82 Sym->Offset = Sec->reserveSpace(Sym->Size, Sym->Alignment);
83 return Sec;
Rui Ueyamae8a61022016-11-05 23:05:47 +000084}
85
Rui Ueyama3da3f062016-11-10 20:20:37 +000086// Returns an LLD version string.
87static ArrayRef<uint8_t> getVersion() {
88 // Check LLD_VERSION first for ease of testing.
89 // You can get consitent output by using the environment variable.
90 // This is only for testing.
91 StringRef S = getenv("LLD_VERSION");
92 if (S.empty())
93 S = Saver.save(Twine("Linker: ") + getLLDVersion());
94
95 // +1 to include the terminating '\0'.
96 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000097}
Rui Ueyama3da3f062016-11-10 20:20:37 +000098
99// Creates a .comment section containing LLD version info.
100// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +0000101// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +0000102// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000103template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000104 typename ELFT::Shdr Hdr = {};
105 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
106 Hdr.sh_type = SHT_PROGBITS;
107 Hdr.sh_entsize = 1;
108 Hdr.sh_addralign = 1;
109
Rafael Espindola6119b862017-03-06 20:23:56 +0000110 auto *Ret =
111 make<MergeInputSection>((ObjectFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000112 Ret->Data = getVersion();
113 Ret->splitIntoPieces();
114 return Ret;
115}
116
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000117// .MIPS.abiflags section.
118template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000119MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000120 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000121 Flags(Flags) {
122 this->Entsize = sizeof(Elf_Mips_ABIFlags);
123}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000124
125template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
126 memcpy(Buf, &Flags, sizeof(Flags));
127}
128
129template <class ELFT>
130MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
131 Elf_Mips_ABIFlags Flags = {};
132 bool Create = false;
133
Rui Ueyama536a2672017-02-27 02:32:08 +0000134 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000135 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000136 continue;
137 Sec->Live = false;
138 Create = true;
139
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000140 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000141 const size_t Size = Sec->Data.size();
142 // Older version of BFD (such as the default FreeBSD linker) concatenate
143 // .MIPS.abiflags instead of merging. To allow for this case (or potential
144 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
145 if (Size < sizeof(Elf_Mips_ABIFlags)) {
146 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
147 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000148 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000149 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000150 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000151 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000152 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000153 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000154 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000155 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000156
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000157 // LLD checks ISA compatibility in getMipsEFlags(). Here we just
158 // select the highest number of ISA/Rev/Ext.
159 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
160 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
161 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
162 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
163 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
164 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
165 Flags.ases |= S->ases;
166 Flags.flags1 |= S->flags1;
167 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000168 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000169 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000170
Rui Ueyama12f2da82016-11-22 03:57:06 +0000171 if (Create)
172 return make<MipsAbiFlagsSection<ELFT>>(Flags);
173 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000174}
175
Simon Atanasyance02cf02016-11-09 21:36:56 +0000176// .MIPS.options section.
177template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000178MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000179 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000180 Reginfo(Reginfo) {
181 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
182}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000183
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000184template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
185 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
186 Options->kind = ODK_REGINFO;
187 Options->size = getSize();
188
189 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000190 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000191 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000192}
193
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000194template <class ELFT>
195MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
196 // N64 ABI only.
197 if (!ELFT::Is64Bits)
198 return nullptr;
199
200 Elf_Mips_RegInfo Reginfo = {};
201 bool Create = false;
202
Rui Ueyama536a2672017-02-27 02:32:08 +0000203 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000204 if (Sec->Type != SHT_MIPS_OPTIONS)
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000205 continue;
206 Sec->Live = false;
207 Create = true;
208
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000209 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000210 ArrayRef<uint8_t> D = Sec->Data;
211
212 while (!D.empty()) {
213 if (D.size() < sizeof(Elf_Mips_Options)) {
214 error(Filename + ": invalid size of .MIPS.options section");
215 break;
216 }
217
218 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
219 if (Opt->kind == ODK_REGINFO) {
220 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
221 error(Filename + ": unsupported non-zero ri_gp_value");
222 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000223 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000224 break;
225 }
226
227 if (!Opt->size)
228 fatal(Filename + ": zero option descriptor size");
229 D = D.slice(Opt->size);
230 }
231 };
232
233 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000234 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000235 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000236}
237
238// MIPS .reginfo section.
239template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000240MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000241 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000242 Reginfo(Reginfo) {
243 this->Entsize = sizeof(Elf_Mips_RegInfo);
244}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000245
Rui Ueyamab71cae92016-11-22 03:57:08 +0000246template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000247 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000248 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000249 memcpy(Buf, &Reginfo, sizeof(Reginfo));
250}
251
252template <class ELFT>
253MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
254 // Section should be alive for O32 and N32 ABIs only.
255 if (ELFT::Is64Bits)
256 return nullptr;
257
258 Elf_Mips_RegInfo Reginfo = {};
259 bool Create = false;
260
Rui Ueyama536a2672017-02-27 02:32:08 +0000261 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000262 if (Sec->Type != SHT_MIPS_REGINFO)
Rui Ueyamab71cae92016-11-22 03:57:08 +0000263 continue;
264 Sec->Live = false;
265 Create = true;
266
267 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000268 error(toString(Sec->getFile<ELFT>()) +
269 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000270 return nullptr;
271 }
272 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
273 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000274 error(toString(Sec->getFile<ELFT>()) +
275 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000276
277 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000278 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000279 };
280
281 if (Create)
282 return make<MipsReginfoSection<ELFT>>(Reginfo);
283 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000284}
285
Rui Ueyama3255a522017-02-27 02:32:49 +0000286InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000287 // StringSaver guarantees that the returned string ends with '\0'.
288 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000289 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
290
291 auto *Sec =
292 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
293 Sec->Live = true;
294 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000295}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000296
Rui Ueyama65316d72017-02-23 03:15:57 +0000297SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
298 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000299 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
300 Value, Size, Section, nullptr);
George Rimar69b17c32017-05-16 10:04:42 +0000301 if (InX::SymTab)
302 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000303 return S;
304}
305
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000306static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000307 switch (Config->BuildId) {
308 case BuildIdKind::Fast:
309 return 8;
310 case BuildIdKind::Md5:
311 case BuildIdKind::Uuid:
312 return 16;
313 case BuildIdKind::Sha1:
314 return 20;
315 case BuildIdKind::Hexstring:
316 return Config->BuildIdVector.size();
317 default:
318 llvm_unreachable("unknown BuildIdKind");
319 }
320}
321
George Rimar6c2949d2017-03-20 16:40:21 +0000322BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000323 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000324 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000325
George Rimar6c2949d2017-03-20 16:40:21 +0000326void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000327 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000328 write32(Buf, 4, E); // Name size
329 write32(Buf + 4, HashSize, E); // Content size
330 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000331 memcpy(Buf + 12, "GNU", 4); // Name string
332 HashBuf = Buf + 16;
333}
334
Rui Ueyama35e00752016-11-10 00:12:28 +0000335// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000336static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
337 size_t ChunkSize) {
338 std::vector<ArrayRef<uint8_t>> Ret;
339 while (Arr.size() > ChunkSize) {
340 Ret.push_back(Arr.take_front(ChunkSize));
341 Arr = Arr.drop_front(ChunkSize);
342 }
343 if (!Arr.empty())
344 Ret.push_back(Arr);
345 return Ret;
346}
347
Rui Ueyama35e00752016-11-10 00:12:28 +0000348// Computes a hash value of Data using a given hash function.
349// In order to utilize multiple cores, we first split data into 1MB
350// chunks, compute a hash for each chunk, and then compute a hash value
351// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000352void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000353 llvm::ArrayRef<uint8_t> Data,
354 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000355 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000356 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000357
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000358 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000359 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000360 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
361 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000362
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000363 // Write to the final output buffer.
364 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000365}
366
George Rimar1ab9cf42017-03-17 10:14:53 +0000367BssSection::BssSection(StringRef Name)
368 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, 0, Name) {}
369
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000370size_t BssSection::reserveSpace(uint64_t Size, uint32_t Alignment) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000371 if (OutputSection *Sec = getParent())
372 Sec->updateAlignment(Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000373 this->Size = alignTo(this->Size, Alignment) + Size;
Rui Ueyama6022b2b2017-03-29 00:49:50 +0000374 this->Alignment = std::max(this->Alignment, Alignment);
George Rimar1ab9cf42017-03-17 10:14:53 +0000375 return this->Size - Size;
376}
Peter Smithebfe9942017-02-09 10:27:57 +0000377
George Rimar6c2949d2017-03-20 16:40:21 +0000378void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000379 switch (Config->BuildId) {
380 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000381 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000382 write64le(Dest, xxHash64(toStringRef(Arr)));
383 });
384 break;
385 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000386 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000387 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000388 });
389 break;
390 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000391 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000392 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000393 });
394 break;
395 case BuildIdKind::Uuid:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000396 if (getRandomBytes(HashBuf, HashSize))
Rui Ueyamac4030a12016-11-22 00:54:15 +0000397 error("entropy source failure");
398 break;
399 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000400 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000401 break;
402 default:
403 llvm_unreachable("unknown BuildIdKind");
404 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000405}
406
Eugene Leviant41ca3272016-11-10 09:48:29 +0000407template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000408EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000409 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000410
411// Search for an existing CIE record or create a new one.
412// CIE records from input object files are uniquified by their contents
413// and where their relocations point to.
414template <class ELFT>
415template <class RelTy>
416CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Piece,
417 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000418 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000419 const endianness E = ELFT::TargetEndianness;
420 if (read32<E>(Piece.data().data() + 4) != 0)
421 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
422
423 SymbolBody *Personality = nullptr;
424 unsigned FirstRelI = Piece.FirstRelocation;
425 if (FirstRelI != (unsigned)-1)
426 Personality =
427 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
428
429 // Search for an existing CIE by CIE contents/relocation target pair.
430 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
431
432 // If not found, create a new one.
433 if (Cie->Piece == nullptr) {
434 Cie->Piece = &Piece;
435 Cies.push_back(Cie);
436 }
437 return Cie;
438}
439
440// There is one FDE per function. Returns true if a given FDE
441// points to a live function.
442template <class ELFT>
443template <class RelTy>
444bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
445 ArrayRef<RelTy> Rels) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000446 auto *Sec = cast<EhInputSection>(Piece.ID);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000447 unsigned FirstRelI = Piece.FirstRelocation;
448 if (FirstRelI == (unsigned)-1)
449 return false;
450 const RelTy &Rel = Rels[FirstRelI];
451 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
Rui Ueyama80474a22017-02-28 19:29:55 +0000452 auto *D = dyn_cast<DefinedRegular>(&B);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000453 if (!D || !D->Section)
454 return false;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000455 auto *Target =
456 cast<InputSectionBase>(cast<InputSectionBase>(D->Section)->Repl);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000457 return Target && Target->Live;
458}
459
460// .eh_frame is a sequence of CIE or FDE records. In general, there
461// is one CIE record per input object file which is followed by
462// a list of FDEs. This function searches an existing CIE or create a new
463// one and associates FDEs to the CIE.
464template <class ELFT>
465template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000466void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000467 ArrayRef<RelTy> Rels) {
468 const endianness E = ELFT::TargetEndianness;
469
470 DenseMap<size_t, CieRecord *> OffsetToCie;
471 for (EhSectionPiece &Piece : Sec->Pieces) {
472 // The empty record is the end marker.
473 if (Piece.size() == 4)
474 return;
475
476 size_t Offset = Piece.InputOff;
477 uint32_t ID = read32<E>(Piece.data().data() + 4);
478 if (ID == 0) {
479 OffsetToCie[Offset] = addCie(Piece, Rels);
480 continue;
481 }
482
483 uint32_t CieOffset = Offset + 4 - ID;
484 CieRecord *Cie = OffsetToCie[CieOffset];
485 if (!Cie)
486 fatal(toString(Sec) + ": invalid CIE reference");
487
488 if (!isFdeLive(Piece, Rels))
489 continue;
490 Cie->FdePieces.push_back(&Piece);
491 NumFdes++;
492 }
493}
494
495template <class ELFT>
496void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000497 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000498 Sec->Parent = this;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000499 updateAlignment(Sec->Alignment);
500 Sections.push_back(Sec);
Petr Hosek7b793212017-03-10 20:00:42 +0000501 for (auto *DS : Sec->DependentSections)
502 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000503
504 // .eh_frame is a sequence of CIE or FDE records. This function
505 // splits it into pieces so that we can call
506 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000507 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000508 if (Sec->Pieces.empty())
509 return;
510
511 if (Sec->NumRelocations) {
512 if (Sec->AreRelocsRela)
513 addSectionAux(Sec, Sec->template relas<ELFT>());
514 else
515 addSectionAux(Sec, Sec->template rels<ELFT>());
516 return;
517 }
518 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
519}
520
521template <class ELFT>
522static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
523 memcpy(Buf, D.data(), D.size());
524
525 // Fix the size field. -4 since size does not include the size field itself.
526 const endianness E = ELFT::TargetEndianness;
527 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
528}
529
Rui Ueyama945055a2017-02-27 03:07:41 +0000530template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000531 if (this->Size)
532 return; // Already finalized.
533
534 size_t Off = 0;
535 for (CieRecord *Cie : Cies) {
536 Cie->Piece->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000537 Off += alignTo(Cie->Piece->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000538
539 for (EhSectionPiece *Fde : Cie->FdePieces) {
540 Fde->OutputOff = Off;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000541 Off += alignTo(Fde->size(), Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000542 }
543 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000544
545 // The LSB standard does not allow a .eh_frame section with zero
546 // Call Frame Information records. Therefore add a CIE record length
547 // 0 as a terminator if this .eh_frame section is empty.
548 if (Off == 0)
549 Off = 4;
550
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000551 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000552}
553
554template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
555 const endianness E = ELFT::TargetEndianness;
556 switch (Size) {
557 case DW_EH_PE_udata2:
558 return read16<E>(Buf);
559 case DW_EH_PE_udata4:
560 return read32<E>(Buf);
561 case DW_EH_PE_udata8:
562 return read64<E>(Buf);
563 case DW_EH_PE_absptr:
564 if (ELFT::Is64Bits)
565 return read64<E>(Buf);
566 return read32<E>(Buf);
567 }
568 fatal("unknown FDE size encoding");
569}
570
571// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
572// We need it to create .eh_frame_hdr section.
573template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000574uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
575 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000576 // The starting address to which this FDE applies is
577 // stored at FDE + 8 byte.
578 size_t Off = FdeOff + 8;
579 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
580 if ((Enc & 0x70) == DW_EH_PE_absptr)
581 return Addr;
582 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000583 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000584 fatal("unknown FDE size relative encoding");
585}
586
587template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
588 const endianness E = ELFT::TargetEndianness;
589 for (CieRecord *Cie : Cies) {
590 size_t CieOffset = Cie->Piece->OutputOff;
591 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
592
593 for (EhSectionPiece *Fde : Cie->FdePieces) {
594 size_t Off = Fde->OutputOff;
595 writeCieFde<ELFT>(Buf + Off, Fde->data());
596
597 // FDE's second word should have the offset to an associated CIE.
598 // Write it.
599 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
600 }
601 }
602
Rafael Espindola5c02b742017-03-06 21:17:18 +0000603 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000604 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000605
606 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
607 // to get a FDE from an address to which FDE is applied. So here
608 // we obtain two addresses and pass them to EhFrameHdr object.
609 if (In<ELFT>::EhFrameHdr) {
610 for (CieRecord *Cie : Cies) {
611 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
612 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000613 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000614 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000615 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
616 }
617 }
618 }
619}
620
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000621GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000622 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
623 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000624
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000625void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000626 Sym.GotIndex = NumEntries;
627 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000628}
629
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000630bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000631 if (Sym.GlobalDynIndex != -1U)
632 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000633 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000634 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000635 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000636 return true;
637}
638
639// Reserves TLS entries for a TLS module ID and a TLS block offset.
640// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000641bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000642 if (TlsIndexOff != uint32_t(-1))
643 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000644 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000645 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000646 return true;
647}
648
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000649uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000650 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000651}
652
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000653uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000654 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000655}
656
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000657void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000658
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000659bool GotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000660 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
661 // we need to emit a GOT even if it's empty.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000662 return NumEntries == 0 && !HasGotOffRel;
George Rimar11992c862016-11-25 08:05:41 +0000663}
664
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000665void GotSection::writeTo(uint8_t *Buf) { relocateAlloc(Buf, Buf + Size); }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000666
George Rimar14534eb2017-03-20 16:44:28 +0000667MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000668 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
669 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000670
George Rimar14534eb2017-03-20 16:44:28 +0000671void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000672 // For "true" local symbols which can be referenced from the same module
673 // only compiler creates two instructions for address loading:
674 //
675 // lw $8, 0($gp) # R_MIPS_GOT16
676 // addi $8, $8, 0 # R_MIPS_LO16
677 //
678 // The first instruction loads high 16 bits of the symbol address while
679 // the second adds an offset. That allows to reduce number of required
680 // GOT entries because only one global offset table entry is necessary
681 // for every 64 KBytes of local data. So for local symbols we need to
682 // allocate number of GOT entries to hold all required "page" addresses.
683 //
684 // All global symbols (hidden and regular) considered by compiler uniformly.
685 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
686 // to load address of the symbol. So for each such symbol we need to
687 // allocate dedicated GOT entry to store its address.
688 //
689 // If a symbol is preemptible we need help of dynamic linker to get its
690 // final address. The corresponding GOT entries are allocated in the
691 // "global" part of GOT. Entries for non preemptible global symbol allocated
692 // in the "local" part of GOT.
693 //
694 // See "Global Offset Table" in Chapter 5:
695 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
696 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
697 // At this point we do not know final symbol value so to reduce number
698 // of allocated GOT entries do the following trick. Save all output
699 // sections referenced by GOT relocations. Then later in the `finalize`
700 // method calculate number of "pages" required to cover all saved output
701 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000702 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000703 return;
704 }
705 if (Sym.isTls()) {
706 // GOT entries created for MIPS TLS relocations behave like
707 // almost GOT entries from other ABIs. They go to the end
708 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000709 Sym.GotIndex = TlsEntries.size();
710 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000711 return;
712 }
George Rimar14534eb2017-03-20 16:44:28 +0000713 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000714 if (S.isInGot() && !A)
715 return;
716 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000717 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 return;
719 Items.emplace_back(&S, A);
720 if (!A)
721 S.GotIndex = NewIndex;
722 };
723 if (Sym.isPreemptible()) {
724 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000725 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 Sym.IsInGlobalMipsGot = true;
727 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000728 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 Sym.Is32BitMipsGot = true;
730 } else {
731 // Hold local GOT entries accessed via a 16-bit index separately.
732 // That allows to write them in the beginning of the GOT and keep
733 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000734 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000735 }
736}
737
George Rimar14534eb2017-03-20 16:44:28 +0000738bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000739 if (Sym.GlobalDynIndex != -1U)
740 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000741 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000742 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000743 TlsEntries.push_back(nullptr);
744 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000745 return true;
746}
747
748// Reserves TLS entries for a TLS module ID and a TLS block offset.
749// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000750bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000751 if (TlsIndexOff != uint32_t(-1))
752 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000753 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000754 TlsEntries.push_back(nullptr);
755 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000756 return true;
757}
758
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000759static uint64_t getMipsPageAddr(uint64_t Addr) {
760 return (Addr + 0x8000) & ~0xffff;
761}
762
763static uint64_t getMipsPageCount(uint64_t Size) {
764 return (Size + 0xfffe) / 0xffff + 1;
765}
766
George Rimar14534eb2017-03-20 16:44:28 +0000767uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
768 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000769 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000770 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
771 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
772 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000773 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000774 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000775}
776
George Rimar14534eb2017-03-20 16:44:28 +0000777uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
778 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000779 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000780 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000781 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000782 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000783 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000784 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000785 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000786 Index += LocalEntries.size();
787 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000788 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000789 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000791 auto It = EntryIndexMap.find({&B, Addend});
792 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000793 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794 }
George Rimar14534eb2017-03-20 16:44:28 +0000795 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000796}
797
George Rimar14534eb2017-03-20 16:44:28 +0000798uint64_t MipsGotSection::getTlsOffset() const {
799 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000800}
801
George Rimar14534eb2017-03-20 16:44:28 +0000802uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
803 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000804}
805
George Rimar14534eb2017-03-20 16:44:28 +0000806const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000807 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000808}
809
George Rimar14534eb2017-03-20 16:44:28 +0000810unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000811 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
812 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000813}
814
George Rimar14534eb2017-03-20 16:44:28 +0000815void MipsGotSection::finalizeContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +0000816 updateAllocSize();
817}
818
George Rimar14534eb2017-03-20 16:44:28 +0000819void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000820 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000821 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000822 // For each output section referenced by GOT page relocations calculate
823 // and save into PageIndexMap an upper bound of MIPS GOT entries required
824 // to store page addresses of local symbols. We assume the worst case -
825 // each 64kb page of the output section has at least one GOT relocation
826 // against it. And take in account the case when the section intersects
827 // page boundaries.
828 P.second = PageEntriesNum;
829 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000830 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000831 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000832 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000833}
834
George Rimar14534eb2017-03-20 16:44:28 +0000835bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000836 // We add the .got section to the result for dynamic MIPS target because
837 // its address and properties are mentioned in the .dynamic section.
838 return Config->Relocatable;
839}
840
George Rimar14534eb2017-03-20 16:44:28 +0000841uint64_t MipsGotSection::getGp() const {
George Rimarf64618a2017-03-17 11:56:54 +0000842 return ElfSym::MipsGp->getVA(0);
Simon Atanasyan8469b882016-11-23 22:22:16 +0000843}
844
George Rimar5f73bc92017-03-29 15:23:28 +0000845static uint64_t readUint(uint8_t *Buf) {
846 if (Config->Is64)
847 return read64(Buf, Config->Endianness);
848 return read32(Buf, Config->Endianness);
849}
850
George Rimar14534eb2017-03-20 16:44:28 +0000851static void writeUint(uint8_t *Buf, uint64_t Val) {
Rui Ueyama7ab38c32017-03-22 00:01:11 +0000852 if (Config->Is64)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000853 write64(Buf, Val, Config->Endianness);
George Rimar14534eb2017-03-20 16:44:28 +0000854 else
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000855 write32(Buf, Val, Config->Endianness);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000856}
857
George Rimar14534eb2017-03-20 16:44:28 +0000858void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000859 // Set the MSB of the second GOT slot. This is not required by any
860 // MIPS ABI documentation, though.
861 //
862 // There is a comment in glibc saying that "The MSB of got[1] of a
863 // gnu object is set to identify gnu objects," and in GNU gold it
864 // says "the second entry will be used by some runtime loaders".
865 // But how this field is being used is unclear.
866 //
867 // We are not really willing to mimic other linkers behaviors
868 // without understanding why they do that, but because all files
869 // generated by GNU tools have this special GOT value, and because
870 // we've been doing this for years, it is probably a safe bet to
871 // keep doing this for now. We really need to revisit this to see
872 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000873 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
874 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000875 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000876 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000877 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000878 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000879 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000880 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
881 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000882 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000883 }
George Rimar14534eb2017-03-20 16:44:28 +0000884 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000885 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000886 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000887 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000888 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000889 uint64_t VA = Body->getVA(SA.second);
890 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000891 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000892 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
893 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
894 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000895 // Initialize TLS-related GOT entries. If the entry has a corresponding
896 // dynamic relocations, leave it initialized by zero. Write down adjusted
897 // TLS symbol's values otherwise. To calculate the adjustments use offsets
898 // for thread-local storage.
899 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000900 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000901 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000902 for (const SymbolBody *B : TlsEntries) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000903 if (!B || B->isPreemptible())
904 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000905 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000906 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000907 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
908 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000909 }
910 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000911 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
912 writeUint(Entry, 1);
913 Entry += Config->Wordsize;
914 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000915 }
916 }
917}
918
George Rimar10f74fc2017-03-15 09:12:56 +0000919GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000920 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
921 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000922
George Rimar10f74fc2017-03-15 09:12:56 +0000923void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000924 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
925 Entries.push_back(&Sym);
926}
927
George Rimar10f74fc2017-03-15 09:12:56 +0000928size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000929 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
930 Target->GotPltEntrySize;
931}
932
George Rimar10f74fc2017-03-15 09:12:56 +0000933void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000934 Target->writeGotPltHeader(Buf);
935 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
936 for (const SymbolBody *B : Entries) {
937 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000938 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000939 }
940}
941
Peter Smithbaffdb82016-12-08 12:58:55 +0000942// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
943// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000944IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000945 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
946 Target->GotPltEntrySize,
947 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000948
George Rimar10f74fc2017-03-15 09:12:56 +0000949void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000950 Sym.IsInIgot = true;
951 Sym.GotPltIndex = Entries.size();
952 Entries.push_back(&Sym);
953}
954
George Rimar10f74fc2017-03-15 09:12:56 +0000955size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000956 return Entries.size() * Target->GotPltEntrySize;
957}
958
George Rimar10f74fc2017-03-15 09:12:56 +0000959void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000960 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000961 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000962 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000963 }
964}
965
George Rimar49648002017-03-15 09:32:36 +0000966StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
967 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000968 Dynamic(Dynamic) {
969 // ELF string tables start with a NUL byte.
970 addString("");
971}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000972
973// Adds a string to the string table. If HashIt is true we hash and check for
974// duplicates. It is optional because the name of global symbols are already
975// uniqued and hashing them again has a big cost for a small value: uniquing
976// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000977unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000978 if (HashIt) {
979 auto R = StringMap.insert(std::make_pair(S, this->Size));
980 if (!R.second)
981 return R.first->second;
982 }
983 unsigned Ret = this->Size;
984 this->Size = this->Size + S.size() + 1;
985 Strings.push_back(S);
986 return Ret;
987}
988
George Rimar49648002017-03-15 09:32:36 +0000989void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000990 for (StringRef S : Strings) {
991 memcpy(Buf, S.data(), S.size());
992 Buf += S.size() + 1;
993 }
994}
995
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000996// Returns the number of version definition entries. Because the first entry
997// is for the version definition itself, it is the number of versioned symbols
998// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000999static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1000
1001template <class ELFT>
1002DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001003 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001004 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001005 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001006
Petr Hosekffa786f2017-05-26 19:12:38 +00001007 // .dynamic section is not writable on MIPS and on Fuchsia OS
1008 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001009 // See "Special Section" in Chapter 4 in the following document:
1010 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001011 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001012 this->Flags = SHF_ALLOC;
1013
1014 addEntries();
1015}
1016
1017// There are some dynamic entries that don't depend on other sections.
1018// Such entries can be set early.
1019template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1020 // Add strings to .dynstr early so that .dynstr's size will be
1021 // fixed early.
1022 for (StringRef S : Config->AuxiliaryList)
Rafael Espindola895aea62017-05-11 22:02:41 +00001023 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001024 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001025 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001026 InX::DynStrTab->addString(Config->Rpath)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001027 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
1028 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001029 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001030 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001031 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001032
1033 // Set DT_FLAGS and DT_FLAGS_1.
1034 uint32_t DtFlags = 0;
1035 uint32_t DtFlags1 = 0;
1036 if (Config->Bsymbolic)
1037 DtFlags |= DF_SYMBOLIC;
1038 if (Config->ZNodelete)
1039 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001040 if (Config->ZNodlopen)
1041 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001042 if (Config->ZNow) {
1043 DtFlags |= DF_BIND_NOW;
1044 DtFlags1 |= DF_1_NOW;
1045 }
1046 if (Config->ZOrigin) {
1047 DtFlags |= DF_ORIGIN;
1048 DtFlags1 |= DF_1_ORIGIN;
1049 }
1050
1051 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001052 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001053 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001054 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001055
Petr Hosekffa786f2017-05-26 19:12:38 +00001056 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1057 // need it for each process, so we don't write it for DSOs. The loader writes
1058 // the pointer into this entry.
1059 //
1060 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1061 // systems (currently only Fuchsia OS) provide other means to give the
1062 // debugger this information. Such systems may choose make .dynamic read-only.
1063 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1064 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001065 add({DT_DEBUG, (uint64_t)0});
1066}
1067
1068// Add remaining entries to complete .dynamic contents.
1069template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1070 if (this->Size)
1071 return; // Already finalized.
1072
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001073 this->Link = InX::DynStrTab->getParent()->SectionIndex;
1074 if (In<ELFT>::RelaDyn->getParent()->Size > 0) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001075 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001076 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001077 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent()->Size});
Rui Ueyama729ac792016-11-17 04:10:09 +00001078 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001079 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001080
1081 // MIPS dynamic loader does not support RELCOUNT tag.
1082 // The problem is in the tight relation between dynamic
1083 // relocations and GOT. So do not emit this tag on MIPS.
1084 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001085 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001086 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001087 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001088 }
1089 }
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001090 if (In<ELFT>::RelaPlt->getParent()->Size > 0) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001091 add({DT_JMPREL, In<ELFT>::RelaPlt});
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001092 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent()->Size});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001093 switch (Config->EMachine) {
1094 case EM_MIPS:
1095 add({DT_MIPS_PLTGOT, In<ELFT>::GotPlt});
1096 break;
1097 case EM_SPARCV9:
1098 add({DT_PLTGOT, In<ELFT>::Plt});
1099 break;
1100 default:
1101 add({DT_PLTGOT, In<ELFT>::GotPlt});
1102 break;
1103 }
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001104 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001105 }
1106
George Rimar69b17c32017-05-16 10:04:42 +00001107 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001108 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001109 add({DT_STRTAB, InX::DynStrTab});
1110 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001111 if (!Config->ZText)
1112 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001113 if (InX::GnuHashTab)
1114 add({DT_GNU_HASH, InX::GnuHashTab});
Eugene Leviantb96e8092016-11-18 09:06:47 +00001115 if (In<ELFT>::HashTab)
1116 add({DT_HASH, In<ELFT>::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001117
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001118 if (Out::PreinitArray) {
1119 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1120 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001121 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001122 if (Out::InitArray) {
1123 add({DT_INIT_ARRAY, Out::InitArray});
1124 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001125 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001126 if (Out::FiniArray) {
1127 add({DT_FINI_ARRAY, Out::FiniArray});
1128 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001129 }
1130
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001131 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Init))
Rui Ueyama729ac792016-11-17 04:10:09 +00001132 add({DT_INIT, B});
Rafael Espindola1d6d1b42017-01-17 16:08:06 +00001133 if (SymbolBody *B = Symtab<ELFT>::X->findInCurrentDSO(Config->Fini))
Rui Ueyama729ac792016-11-17 04:10:09 +00001134 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001135
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001136 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1137 if (HasVerNeed || In<ELFT>::VerDef)
1138 add({DT_VERSYM, In<ELFT>::VerSym});
1139 if (In<ELFT>::VerDef) {
1140 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001141 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001142 }
1143 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001144 add({DT_VERNEED, In<ELFT>::VerNeed});
1145 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001146 }
1147
1148 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001149 add({DT_MIPS_RLD_VERSION, 1});
1150 add({DT_MIPS_FLAGS, RHF_NOTPOT});
1151 add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
George Rimar69b17c32017-05-16 10:04:42 +00001152 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001153 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1154 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001155 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001156 else
George Rimar69b17c32017-05-16 10:04:42 +00001157 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001158 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001159 if (InX::MipsRldMap)
1160 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001161 }
1162
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001163 getParent()->Link = this->Link;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001164
1165 // +1 for DT_NULL
1166 this->Size = (Entries.size() + 1) * this->Entsize;
1167}
1168
1169template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1170 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1171
1172 for (const Entry &E : Entries) {
1173 P->d_tag = E.Tag;
1174 switch (E.Kind) {
1175 case Entry::SecAddr:
1176 P->d_un.d_ptr = E.OutSec->Addr;
1177 break;
1178 case Entry::InSecAddr:
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001179 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001180 break;
1181 case Entry::SecSize:
1182 P->d_un.d_val = E.OutSec->Size;
1183 break;
1184 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001185 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001186 break;
1187 case Entry::PlainInt:
1188 P->d_un.d_val = E.Val;
1189 break;
1190 }
1191 ++P;
1192 }
1193}
1194
George Rimar97def8c2017-03-17 12:07:44 +00001195uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001196 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001197}
1198
George Rimar97def8c2017-03-17 12:07:44 +00001199int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001200 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001201 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001202 return Addend;
1203}
1204
George Rimar97def8c2017-03-17 12:07:44 +00001205uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001206 if (Sym && !UseSymVA)
1207 return Sym->DynsymIndex;
1208 return 0;
1209}
1210
1211template <class ELFT>
1212RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001213 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001214 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001215 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001216 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001217}
1218
1219template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001220void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001221 if (Reloc.Type == Target->RelativeRel)
1222 ++NumRelativeRelocs;
1223 Relocs.push_back(Reloc);
1224}
1225
1226template <class ELFT, class RelTy>
1227static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001228 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1229 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001230 if (AIsRel != BIsRel)
1231 return AIsRel;
1232
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001233 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001234}
1235
1236template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1237 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001238 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001239 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001240 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001241
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001242 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001243 P->r_addend = Rel.getAddend();
1244 P->r_offset = Rel.getOffset();
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001245 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001246 // Dynamic relocation against MIPS GOT section make deal TLS entries
1247 // allocated in the end of the GOT. We need to adjust the offset to take
1248 // in account 'local' and 'global' GOT entries.
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001249 P->r_offset += InX::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001250 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001251 }
1252
1253 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001254 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001255 std::stable_sort((Elf_Rela *)BufBegin,
1256 (Elf_Rela *)BufBegin + Relocs.size(),
1257 compRelocations<ELFT, Elf_Rela>);
1258 else
1259 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1260 compRelocations<ELFT, Elf_Rel>);
1261 }
1262}
1263
1264template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1265 return this->Entsize * Relocs.size();
1266}
1267
Rui Ueyama945055a2017-02-27 03:07:41 +00001268template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001269 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex
1270 : InX::SymTab->getParent()->SectionIndex;
Eugene Levianta96d9022016-11-16 10:02:27 +00001271
1272 // Set required output section properties.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001273 getParent()->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001274}
1275
George Rimarf45f6812017-05-16 08:53:30 +00001276SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001277 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001278 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001279 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001280 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001281 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001282
1283// Orders symbols according to their positions in the GOT,
1284// in compliance with MIPS ABI rules.
1285// See "Global Offset Table" in Chapter 5 in the following document
1286// for detailed description:
1287// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001288static bool sortMipsSymbols(const SymbolTableEntry &L,
1289 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001290 // Sort entries related to non-local preemptible symbols by GOT indexes.
1291 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001292 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1293 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001294 if (LIsInLocalGot || RIsInLocalGot)
1295 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001296 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001297}
1298
Rui Ueyamabb07d102017-02-27 03:31:19 +00001299// Finalize a symbol table. The ELF spec requires that all local
1300// symbols precede global symbols, so we sort symbol entries in this
1301// function. (For .dynsym, we don't do that because symbols for
1302// dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001303void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001304 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001305
Rui Ueyama6e967342017-02-28 03:29:12 +00001306 // If it is a .dynsym, there should be no local symbols, but we need
1307 // to do a few things for the dynamic linker.
1308 if (this->Type == SHT_DYNSYM) {
1309 // Section's Info field has the index of the first non-local symbol.
1310 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001311 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001312
George Rimarf45f6812017-05-16 08:53:30 +00001313 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001314 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001315 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001316 } else if (Config->EMachine == EM_MIPS) {
1317 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1318 }
1319
1320 size_t I = 0;
1321 for (const SymbolTableEntry &S : Symbols)
1322 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001323 return;
Peter Smith55865432017-02-20 11:12:33 +00001324 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001325}
Peter Smith55865432017-02-20 11:12:33 +00001326
George Rimarf45f6812017-05-16 08:53:30 +00001327void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001328 if (this->Type == SHT_DYNSYM)
1329 return;
1330 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001331 auto It = std::stable_partition(
1332 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1333 return S.Symbol->isLocal() ||
1334 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1335 });
1336 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001337 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001338}
1339
George Rimarf45f6812017-05-16 08:53:30 +00001340void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001341 // Adding a local symbol to a .dynsym is a bug.
1342 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001343
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001344 bool HashIt = B->isLocal();
1345 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001346}
1347
George Rimarf45f6812017-05-16 08:53:30 +00001348size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001349 auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) {
1350 if (E.Symbol == Body)
1351 return true;
1352 // This is used for -r, so we have to handle multiple section
1353 // symbols being combined.
1354 if (Body->Type == STT_SECTION && E.Symbol->Type == STT_SECTION)
Rafael Espindola0dc25102017-05-31 19:26:37 +00001355 return Body->getOutputSection() == E.Symbol->getOutputSection();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001356 return false;
1357 });
Rafael Espindola0b034d62017-01-26 14:09:18 +00001358 if (I == Symbols.end())
1359 return 0;
George Rimar190bac52017-01-23 14:07:23 +00001360 return I - Symbols.begin() + 1;
1361}
1362
George Rimarf45f6812017-05-16 08:53:30 +00001363template <class ELFT>
1364SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1365 : SymbolTableBaseSection(StrTabSec) {
1366 this->Entsize = sizeof(Elf_Sym);
1367}
1368
Rui Ueyama1f032532017-02-28 01:56:36 +00001369// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001370template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001371 // The first entry is a null entry as per the ELF spec.
Eugene Leviant9230db92016-11-17 09:16:34 +00001372 Buf += sizeof(Elf_Sym);
1373
Eugene Leviant9230db92016-11-17 09:16:34 +00001374 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001375
Rui Ueyama1f032532017-02-28 01:56:36 +00001376 for (SymbolTableEntry &Ent : Symbols) {
1377 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001378
Rui Ueyama1b003182017-02-28 19:22:09 +00001379 // Set st_info and st_other.
Rui Ueyama1f032532017-02-28 01:56:36 +00001380 if (Body->isLocal()) {
1381 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1382 } else {
1383 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1384 ESym->setVisibility(Body->symbol()->Visibility);
1385 }
1386
1387 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001388
Rui Ueyama1b003182017-02-28 19:22:09 +00001389 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001390 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001391 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001392 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001393 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001394 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001395 ESym->st_shndx = SHN_COMMON;
Rui Ueyama1b003182017-02-28 19:22:09 +00001396
George Rimardbe843d2017-06-28 09:51:33 +00001397 // Copy symbol size if it is a defined symbol. st_size is not significant
1398 // for undefined symbols, so whether copying it or not is up to us if that's
1399 // the case. We'll leave it as zero because by not setting a value, we can
1400 // get the exact same outputs for two sets of input files that differ only
1401 // in undefined symbol size in DSOs.
1402 if (ESym->st_shndx != SHN_UNDEF)
1403 ESym->st_size = Body->getSize<ELFT>();
1404
Rui Ueyama1b003182017-02-28 19:22:09 +00001405 // st_value is usually an address of a symbol, but that has a
1406 // special meaining for uninstantiated common symbols (this can
1407 // occur if -r is given).
1408 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001409 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001410 else
George Rimarf64618a2017-03-17 11:56:54 +00001411 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001412
Rui Ueyama1f032532017-02-28 01:56:36 +00001413 ++ESym;
1414 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001415
Rui Ueyama1f032532017-02-28 01:56:36 +00001416 // On MIPS we need to mark symbol which has a PLT entry and requires
1417 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1418 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1419 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1420 if (Config->EMachine == EM_MIPS) {
1421 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1422
1423 for (SymbolTableEntry &Ent : Symbols) {
1424 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001425 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001426 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001427
1428 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001429 if (auto *D = dyn_cast<DefinedRegular>(Body))
1430 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001431 ESym->st_other |= STO_MIPS_PIC;
1432 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001433 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001434 }
1435}
1436
Rui Ueyamae4120632017-02-28 22:05:13 +00001437// .hash and .gnu.hash sections contain on-disk hash tables that map
1438// symbol names to their dynamic symbol table indices. Their purpose
1439// is to help the dynamic linker resolve symbols quickly. If ELF files
1440// don't have them, the dynamic linker has to do linear search on all
1441// dynamic symbols, which makes programs slower. Therefore, a .hash
1442// section is added to a DSO by default. A .gnu.hash is added if you
1443// give the -hash-style=gnu or -hash-style=both option.
1444//
1445// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1446// Each ELF file has a list of DSOs that the ELF file depends on and a
1447// list of dynamic symbols that need to be resolved from any of the
1448// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1449// where m is the number of DSOs and n is the number of dynamic
1450// symbols. For modern large programs, both m and n are large. So
1451// making each step faster by using hash tables substiantially
1452// improves time to load programs.
1453//
1454// (Note that this is not the only way to design the shared library.
1455// For instance, the Windows DLL takes a different approach. On
1456// Windows, each dynamic symbol has a name of DLL from which the symbol
1457// has to be resolved. That makes the cost of symbol resolution O(n).
1458// This disables some hacky techniques you can use on Unix such as
1459// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1460//
1461// Due to historical reasons, we have two different hash tables, .hash
1462// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1463// and better version of .hash. .hash is just an on-disk hash table, but
1464// .gnu.hash has a bloom filter in addition to a hash table to skip
1465// DSOs very quickly. If you are sure that your dynamic linker knows
1466// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1467// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001468GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001469 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1470}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001471
George Rimarf45f6812017-05-16 08:53:30 +00001472void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001473 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001474
1475 // Computes bloom filter size in word size. We want to allocate 8
1476 // bits for each symbol. It must be a power of two.
1477 if (Symbols.empty())
1478 MaskWords = 1;
1479 else
George Rimar5f73bc92017-03-29 15:23:28 +00001480 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001481
George Rimar5f73bc92017-03-29 15:23:28 +00001482 Size = 16; // Header
1483 Size += Config->Wordsize * MaskWords; // Bloom filter
1484 Size += NBuckets * 4; // Hash buckets
1485 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001486}
1487
George Rimarf45f6812017-05-16 08:53:30 +00001488void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001489 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001490 write32(Buf, NBuckets, Config->Endianness);
George Rimarf45f6812017-05-16 08:53:30 +00001491 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
George Rimar5f73bc92017-03-29 15:23:28 +00001492 Config->Endianness);
1493 write32(Buf + 8, MaskWords, Config->Endianness);
1494 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001495 Buf += 16;
1496
Rui Ueyama7986b452017-03-01 18:09:09 +00001497 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001498 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001499 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001500 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001501}
1502
Rui Ueyama7986b452017-03-01 18:09:09 +00001503// This function writes a 2-bit bloom filter. This bloom filter alone
1504// usually filters out 80% or more of all symbol lookups [1].
1505// The dynamic linker uses the hash table only when a symbol is not
1506// filtered out by a bloom filter.
1507//
1508// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1509// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001510void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001511 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001512 for (const Entry &Sym : Symbols) {
1513 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001514 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1515 Val |= uint64_t(1) << (Sym.Hash % C);
1516 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1517 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001518 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001519}
1520
George Rimarf45f6812017-05-16 08:53:30 +00001521void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001522 // Group symbols by hash value.
1523 std::vector<std::vector<Entry>> Syms(NBuckets);
1524 for (const Entry &Ent : Symbols)
1525 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001526
Rui Ueyamae13373b2017-03-01 02:51:42 +00001527 // Write hash buckets. Hash buckets contain indices in the following
1528 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001529 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001530 for (size_t I = 0; I < NBuckets; ++I)
1531 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001532 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001533
1534 // Write a hash value table. It represents a sequence of chains that
1535 // share the same hash modulo value. The last element of each chain
1536 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001537 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001538 size_t I = 0;
1539 for (std::vector<Entry> &Vec : Syms) {
1540 if (Vec.empty())
1541 continue;
1542 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001543 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1544 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001545 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001546}
1547
1548static uint32_t hashGnu(StringRef Name) {
1549 uint32_t H = 5381;
1550 for (uint8_t C : Name)
1551 H = (H << 5) + H + C;
1552 return H;
1553}
1554
Rui Ueyamae13373b2017-03-01 02:51:42 +00001555// Returns a number of hash buckets to accomodate given number of elements.
1556// We want to choose a moderate number that is not too small (which
1557// causes too many hash collisions) and not too large (which wastes
1558// disk space.)
1559//
1560// We return a prime number because it (is believed to) achieve good
1561// hash distribution.
1562static size_t getBucketSize(size_t NumSymbols) {
1563 // List of largest prime numbers that are not greater than 2^n + 1.
1564 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1565 251, 127, 61, 31, 13, 7, 3, 1})
1566 if (N <= NumSymbols)
1567 return N;
1568 return 0;
1569}
1570
Eugene Leviantbe809a72016-11-18 06:44:18 +00001571// Add symbols to this symbol hash table. Note that this function
1572// destructively sort a given vector -- which is needed because
1573// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001574void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001575 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1576 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001577 std::vector<SymbolTableEntry>::iterator Mid =
1578 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1579 return S.Symbol->isUndefined();
1580 });
1581 if (Mid == V.end())
1582 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001583
1584 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1585 SymbolBody *B = Ent.Symbol;
1586 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001587 }
1588
Rui Ueyamae13373b2017-03-01 02:51:42 +00001589 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001590 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001591 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001592 return L.Hash % NBuckets < R.Hash % NBuckets;
1593 });
1594
1595 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001596 for (const Entry &Ent : Symbols)
1597 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001598}
1599
Eugene Leviantb96e8092016-11-18 09:06:47 +00001600template <class ELFT>
1601HashTableSection<ELFT>::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001602 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1603 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001604}
1605
Rui Ueyama945055a2017-02-27 03:07:41 +00001606template <class ELFT> void HashTableSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001607 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001608
1609 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001610 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001611
1612 // Create as many buckets as there are symbols.
1613 // FIXME: This is simplistic. We can try to optimize it, but implementing
1614 // support for SHT_GNU_HASH is probably even more profitable.
George Rimar69b17c32017-05-16 10:04:42 +00001615 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001616 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001617}
1618
1619template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001620 // A 32-bit integer type in the target endianness.
1621 typedef typename ELFT::Word Elf_Word;
1622
George Rimar69b17c32017-05-16 10:04:42 +00001623 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001624
Eugene Leviantb96e8092016-11-18 09:06:47 +00001625 auto *P = reinterpret_cast<Elf_Word *>(Buf);
1626 *P++ = NumSymbols; // nbucket
1627 *P++ = NumSymbols; // nchain
1628
1629 Elf_Word *Buckets = P;
1630 Elf_Word *Chains = P + NumSymbols;
1631
George Rimar69b17c32017-05-16 10:04:42 +00001632 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001633 SymbolBody *Body = S.Symbol;
1634 StringRef Name = Body->getName();
1635 unsigned I = Body->DynsymIndex;
1636 uint32_t Hash = hashSysV(Name) % NumSymbols;
1637 Chains[I] = Buckets[Hash];
1638 Buckets[Hash] = I;
1639 }
1640}
1641
George Rimardfc020e2017-03-17 11:01:57 +00001642PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001643 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001644 HeaderSize(S) {
1645 // The PLT needs to be writable on SPARC as the dynamic linker will
1646 // modify the instructions in the PLT entries.
1647 if (Config->EMachine == EM_SPARCV9)
1648 this->Flags |= SHF_WRITE;
1649}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001650
George Rimardfc020e2017-03-17 11:01:57 +00001651void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001652 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1653 // linker to resolve dynsyms at runtime. Write such code.
1654 if (HeaderSize != 0)
1655 Target->writePltHeader(Buf);
1656 size_t Off = HeaderSize;
1657 // The IPlt is immediately after the Plt, account for this in RelOff
1658 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001659
1660 for (auto &I : Entries) {
1661 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001662 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001663 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001664 uint64_t Plt = this->getVA() + Off;
1665 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1666 Off += Target->PltEntrySize;
1667 }
1668}
1669
George Rimardfc020e2017-03-17 11:01:57 +00001670template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001671 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001672 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1673 if (HeaderSize == 0) {
1674 PltRelocSection = In<ELFT>::RelaIplt;
1675 Sym.IsInIplt = true;
1676 }
1677 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001678 Entries.push_back(std::make_pair(&Sym, RelOff));
1679}
1680
George Rimardfc020e2017-03-17 11:01:57 +00001681size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001682 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001683}
1684
Peter Smith96943762017-01-25 10:31:16 +00001685// Some architectures such as additional symbols in the PLT section. For
1686// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001687void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001688 // The PLT may have symbols defined for the Header, the IPLT has no header
1689 if (HeaderSize != 0)
1690 Target->addPltHeaderSymbols(this);
1691 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001692 for (size_t I = 0; I < Entries.size(); ++I) {
1693 Target->addPltSymbols(this, Off);
1694 Off += Target->PltEntrySize;
1695 }
1696}
1697
George Rimardfc020e2017-03-17 11:01:57 +00001698unsigned PltSection::getPltRelocOff() const {
1699 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001700}
1701
George Rimar35e846e2017-03-21 08:19:34 +00001702GdbIndexSection::GdbIndexSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001703 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"),
George Rimarec02b8d2016-12-15 12:07:53 +00001704 StringPool(llvm::StringTableBuilder::ELF) {}
Eugene Levianta113a412016-11-21 09:24:43 +00001705
George Rimarec02b8d2016-12-15 12:07:53 +00001706// Iterative hash function for symbol's name is described in .gdb_index format
1707// specification. Note that we use one for version 5 to 7 here, it is different
1708// for version 4.
1709static uint32_t hash(StringRef Str) {
1710 uint32_t R = 0;
1711 for (uint8_t C : Str)
1712 R = R * 67 + tolower(C) - 113;
1713 return R;
1714}
1715
George Rimar86665622017-06-07 16:59:11 +00001716static std::vector<CompilationUnitEntry> readCuList(DWARFContext &Dwarf,
1717 InputSection *Sec) {
1718 std::vector<CompilationUnitEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001719 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units())
1720 Ret.push_back({Sec->OutSecOff + CU->getOffset(), CU->getLength() + 4});
1721 return Ret;
1722}
1723
George Rimar86665622017-06-07 16:59:11 +00001724static std::vector<AddressEntry> readAddressArea(DWARFContext &Dwarf,
1725 InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001726 std::vector<AddressEntry> Ret;
1727
George Rimar86665622017-06-07 16:59:11 +00001728 uint32_t CurrentCu = 0;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001729 for (std::unique_ptr<DWARFCompileUnit> &CU : Dwarf.compile_units()) {
1730 DWARFAddressRangesVector Ranges;
1731 CU->collectAddressRanges(Ranges);
1732
George Rimar35e846e2017-03-21 08:19:34 +00001733 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001734 for (DWARFAddressRange &R : Ranges) {
1735 InputSectionBase *S = Sections[R.SectionIndex];
1736 if (!S || S == &InputSection::Discarded || !S->Live)
1737 continue;
1738 // Range list with zero size has no effect.
1739 if (R.LowPC == R.HighPC)
1740 continue;
George Rimar86665622017-06-07 16:59:11 +00001741 Ret.push_back({cast<InputSection>(S), R.LowPC, R.HighPC, CurrentCu});
George Rimar0641b8b2017-06-07 10:52:02 +00001742 }
George Rimar86665622017-06-07 16:59:11 +00001743 ++CurrentCu;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001744 }
1745 return Ret;
1746}
1747
George Rimar86665622017-06-07 16:59:11 +00001748static std::vector<NameTypeEntry> readPubNamesAndTypes(DWARFContext &Dwarf,
1749 bool IsLE) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001750 StringRef Data[] = {Dwarf.getGnuPubNamesSection(),
1751 Dwarf.getGnuPubTypesSection()};
1752
George Rimar86665622017-06-07 16:59:11 +00001753 std::vector<NameTypeEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001754 for (StringRef D : Data) {
1755 DWARFDebugPubTable PubTable(D, IsLE, true);
1756 for (const DWARFDebugPubTable::Set &Set : PubTable.getData())
1757 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries)
1758 Ret.push_back({Ent.Name, Ent.Descriptor.toBits()});
1759 }
1760 return Ret;
1761}
1762
George Rimar86665622017-06-07 16:59:11 +00001763static std::vector<InputSection *> getDebugInfoSections() {
1764 std::vector<InputSection *> Ret;
1765 for (InputSectionBase *S : InputSections)
1766 if (InputSection *IS = dyn_cast<InputSection>(S))
1767 if (IS->getParent() && IS->Name == ".debug_info")
1768 Ret.push_back(IS);
1769 return Ret;
1770}
1771
1772void GdbIndexSection::buildIndex() {
1773 std::vector<InputSection *> V = getDebugInfoSections();
1774 if (V.empty())
1775 return;
1776
1777 for (InputSection *Sec : V)
1778 Chunks.push_back(readDwarf(Sec));
1779
1780 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) {
1787 uint32_t Hash = hash(NameType.Name);
1788 size_t Offset = StringPool.add(NameType.Name);
1789
1790 bool IsNew;
1791 GdbSymbol *Sym;
1792 std::tie(IsNew, Sym) = SymbolTable.add(Hash, Offset);
1793 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
1805GdbIndexChunk GdbIndexSection::readDwarf(InputSection *Sec) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001806 Expected<std::unique_ptr<object::ObjectFile>> Obj =
George Rimar05423482017-03-20 10:47:00 +00001807 object::ObjectFile::createObjectFile(Sec->File->MB);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001808 if (!Obj) {
George Rimar05423482017-03-20 10:47:00 +00001809 error(toString(Sec->File) + ": error creating DWARF context");
George Rimar86665622017-06-07 16:59:11 +00001810 return {};
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001811 }
1812
George Rimar0641b8b2017-06-07 10:52:02 +00001813 DWARFContextInMemory Dwarf(*Obj.get());
George Rimar8b547392016-12-15 09:08:13 +00001814
George Rimar86665622017-06-07 16:59:11 +00001815 GdbIndexChunk Ret;
1816 Ret.CompilationUnits = readCuList(Dwarf, Sec);
1817 Ret.AddressArea = readAddressArea(Dwarf, Sec);
1818 Ret.NamesAndTypes = readPubNamesAndTypes(Dwarf, Config->IsLE);
1819 return Ret;
1820}
George Rimar8b547392016-12-15 09:08:13 +00001821
George Rimar86665622017-06-07 16:59:11 +00001822static size_t getCuSize(std::vector<GdbIndexChunk> &C) {
1823 size_t Ret = 0;
1824 for (GdbIndexChunk &D : C)
1825 Ret += D.CompilationUnits.size();
1826 return Ret;
1827}
George Rimarec02b8d2016-12-15 12:07:53 +00001828
George Rimar86665622017-06-07 16:59:11 +00001829static size_t getAddressAreaSize(std::vector<GdbIndexChunk> &C) {
1830 size_t Ret = 0;
1831 for (GdbIndexChunk &D : C)
1832 Ret += D.AddressArea.size();
1833 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00001834}
1835
George Rimar35e846e2017-03-21 08:19:34 +00001836void GdbIndexSection::finalizeContents() {
George Rimar8b547392016-12-15 09:08:13 +00001837 if (Finalized)
1838 return;
1839 Finalized = true;
1840
George Rimar86665622017-06-07 16:59:11 +00001841 buildIndex();
Rui Ueyama475b1dd2017-03-01 22:02:17 +00001842
Rui Ueyamad0e07b92017-03-01 21:08:21 +00001843 SymbolTable.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;
George Rimarec02b8d2016-12-15 12:07:53 +00001849
1850 ConstantPoolOffset =
1851 SymTabOffset + SymbolTable.getCapacity() * SymTabEntrySize;
1852
George Rimarc1a03642017-05-26 12:09:26 +00001853 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001854 CuVectorsOffset.push_back(CuVectorsSize);
1855 CuVectorsSize += OffsetTypeSize * (CuVec.size() + 1);
1856 }
1857 StringPoolOffset = ConstantPoolOffset + CuVectorsSize;
1858
1859 StringPool.finalizeInOrder();
George Rimar8b547392016-12-15 09:08:13 +00001860}
1861
George Rimar35e846e2017-03-21 08:19:34 +00001862size_t GdbIndexSection::getSize() const {
1863 const_cast<GdbIndexSection *>(this)->finalizeContents();
George Rimarec02b8d2016-12-15 12:07:53 +00001864 return StringPoolOffset + StringPool.getSize();
Eugene Levianta113a412016-11-21 09:24:43 +00001865}
1866
George Rimar35e846e2017-03-21 08:19:34 +00001867void GdbIndexSection::writeTo(uint8_t *Buf) {
George Rimarec02b8d2016-12-15 12:07:53 +00001868 write32le(Buf, 7); // Write version.
1869 write32le(Buf + 4, CuListOffset); // CU list offset.
1870 write32le(Buf + 8, CuTypesOffset); // Types CU list offset.
1871 write32le(Buf + 12, CuTypesOffset); // Address area offset.
1872 write32le(Buf + 16, SymTabOffset); // Symbol table offset.
1873 write32le(Buf + 20, ConstantPoolOffset); // Constant pool offset.
Eugene Levianta113a412016-11-21 09:24:43 +00001874 Buf += 24;
1875
1876 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00001877 for (GdbIndexChunk &D : Chunks) {
1878 for (CompilationUnitEntry &Cu : D.CompilationUnits) {
1879 write64le(Buf, Cu.CuOffset);
1880 write64le(Buf + 8, Cu.CuLength);
1881 Buf += 16;
1882 }
Eugene Levianta113a412016-11-21 09:24:43 +00001883 }
George Rimar8b547392016-12-15 09:08:13 +00001884
1885 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00001886 for (GdbIndexChunk &D : Chunks) {
1887 for (AddressEntry &E : D.AddressArea) {
1888 uint64_t BaseAddr =
1889 E.Section->getParent()->Addr + E.Section->getOffset(0);
1890 write64le(Buf, BaseAddr + E.LowAddress);
1891 write64le(Buf + 8, BaseAddr + E.HighAddress);
1892 write32le(Buf + 16, E.CuIndex);
1893 Buf += 20;
1894 }
George Rimar8b547392016-12-15 09:08:13 +00001895 }
George Rimarec02b8d2016-12-15 12:07:53 +00001896
1897 // Write the symbol table.
1898 for (size_t I = 0; I < SymbolTable.getCapacity(); ++I) {
1899 GdbSymbol *Sym = SymbolTable.getSymbol(I);
1900 if (Sym) {
1901 size_t NameOffset =
1902 Sym->NameOffset + StringPoolOffset - ConstantPoolOffset;
1903 size_t CuVectorOffset = CuVectorsOffset[Sym->CuVectorIndex];
1904 write32le(Buf, NameOffset);
1905 write32le(Buf + 4, CuVectorOffset);
1906 }
1907 Buf += 8;
1908 }
1909
1910 // Write the CU vectors into the constant pool.
George Rimarc1a03642017-05-26 12:09:26 +00001911 for (std::set<uint32_t> &CuVec : CuVectors) {
George Rimarec02b8d2016-12-15 12:07:53 +00001912 write32le(Buf, CuVec.size());
1913 Buf += 4;
George Rimar5f5905e2017-05-26 12:01:40 +00001914 for (uint32_t Val : CuVec) {
1915 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00001916 Buf += 4;
1917 }
1918 }
1919
1920 StringPool.write(Buf);
Eugene Levianta113a412016-11-21 09:24:43 +00001921}
1922
George Rimar35e846e2017-03-21 08:19:34 +00001923bool GdbIndexSection::empty() const {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001924 return !Out::DebugInfo;
George Rimar3fb5a6d2016-11-29 16:05:27 +00001925}
1926
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001927template <class ELFT>
1928EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001929 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001930
1931// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1932// Each entry of the search table consists of two values,
1933// the starting PC from where FDEs covers, and the FDE's address.
1934// It is sorted by PC.
1935template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1936 const endianness E = ELFT::TargetEndianness;
1937
1938 // Sort the FDE list by their PC and uniqueify. Usually there is only
1939 // one FDE for a PC (i.e. function), but if ICF merges two functions
1940 // into one, there can be more than one FDEs pointing to the address.
1941 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1942 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1943 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1944 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1945
1946 Buf[0] = 1;
1947 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1948 Buf[2] = DW_EH_PE_udata4;
1949 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001950 write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001951 write32<E>(Buf + 8, Fdes.size());
1952 Buf += 12;
1953
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001954 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001955 for (FdeData &Fde : Fdes) {
1956 write32<E>(Buf, Fde.Pc - VA);
1957 write32<E>(Buf + 4, Fde.FdeVA - VA);
1958 Buf += 8;
1959 }
1960}
1961
1962template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
1963 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001964 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001965}
1966
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001967template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001968void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
1969 Fdes.push_back({Pc, FdeVA});
1970}
1971
George Rimar11992c862016-11-25 08:05:41 +00001972template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00001973 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00001974}
1975
Rui Ueyamab38ddb12016-11-21 19:46:04 +00001976template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001977VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001978 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
1979 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001980
1981static StringRef getFileDefName() {
1982 if (!Config->SoName.empty())
1983 return Config->SoName;
1984 return Config->OutputFile;
1985}
1986
Rui Ueyama945055a2017-02-27 03:07:41 +00001987template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00001988 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001989 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00001990 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001991
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001992 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001993
1994 // sh_info should be set to the number of definitions. This fact is missed in
1995 // documentation, but confirmed by binutils community:
1996 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001997 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001998}
1999
2000template <class ELFT>
2001void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2002 StringRef Name, size_t NameOff) {
2003 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2004 Verdef->vd_version = 1;
2005 Verdef->vd_cnt = 1;
2006 Verdef->vd_aux = sizeof(Elf_Verdef);
2007 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2008 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2009 Verdef->vd_ndx = Index;
2010 Verdef->vd_hash = hashSysV(Name);
2011
2012 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2013 Verdaux->vda_name = NameOff;
2014 Verdaux->vda_next = 0;
2015}
2016
2017template <class ELFT>
2018void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2019 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2020
2021 for (VersionDefinition &V : Config->VersionDefinitions) {
2022 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2023 writeOne(Buf, V.Id, V.Name, V.NameOff);
2024 }
2025
2026 // Need to terminate the last version definition.
2027 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2028 Verdef->vd_next = 0;
2029}
2030
2031template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2032 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2033}
2034
2035template <class ELFT>
2036VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002037 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002038 ".gnu.version") {
2039 this->Entsize = sizeof(Elf_Versym);
2040}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002041
Rui Ueyama945055a2017-02-27 03:07:41 +00002042template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002043 // At the moment of june 2016 GNU docs does not mention that sh_link field
2044 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002045 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002046}
2047
2048template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002049 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002050}
2051
2052template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2053 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002054 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002055 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2056 ++OutVersym;
2057 }
2058}
2059
George Rimar11992c862016-11-25 08:05:41 +00002060template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2061 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2062}
2063
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002064template <class ELFT>
2065VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002066 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2067 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002068 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2069 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2070 // First identifiers are reserved by verdef section if it exist.
2071 NextIndex = getVerDefNum() + 1;
2072}
2073
2074template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002075void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2076 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2077 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002078 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2079 return;
2080 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002081
2082 auto *File = cast<SharedFile<ELFT>>(SS->File);
2083
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002084 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2085 // to create one by adding it to our needed list and creating a dynstr entry
2086 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002087 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002088 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002089 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002090 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2091 // prepare to create one by allocating a version identifier and creating a
2092 // dynstr entry for the version name.
2093 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002094 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2095 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002096 NV.Index = NextIndex++;
2097 }
2098 SS->symbol()->VersionId = NV.Index;
2099}
2100
2101template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2102 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2103 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2104 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2105
2106 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2107 // Create an Elf_Verneed for this DSO.
2108 Verneed->vn_version = 1;
2109 Verneed->vn_cnt = P.first->VerdefMap.size();
2110 Verneed->vn_file = P.second;
2111 Verneed->vn_aux =
2112 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2113 Verneed->vn_next = sizeof(Elf_Verneed);
2114 ++Verneed;
2115
2116 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2117 // VerdefMap, which will only contain references to needed version
2118 // definitions. Each Elf_Vernaux is based on the information contained in
2119 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2120 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2121 // data structures within a single input file.
2122 for (auto &NV : P.first->VerdefMap) {
2123 Vernaux->vna_hash = NV.first->vd_hash;
2124 Vernaux->vna_flags = 0;
2125 Vernaux->vna_other = NV.second.Index;
2126 Vernaux->vna_name = NV.second.StrTab;
2127 Vernaux->vna_next = sizeof(Elf_Vernaux);
2128 ++Vernaux;
2129 }
2130
2131 Vernaux[-1].vna_next = 0;
2132 }
2133 Verneed[-1].vn_next = 0;
2134}
2135
Rui Ueyama945055a2017-02-27 03:07:41 +00002136template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002137 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2138 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002139}
2140
2141template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2142 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2143 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2144 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2145 return Size;
2146}
2147
George Rimar11992c862016-11-25 08:05:41 +00002148template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2149 return getNeedNum() == 0;
2150}
2151
Rafael Espindola6119b862017-03-06 20:23:56 +00002152MergeSyntheticSection::MergeSyntheticSection(StringRef Name, uint32_t Type,
Rafael Espindolafcd208f2017-03-08 19:35:29 +00002153 uint64_t Flags, uint32_t Alignment)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002154 : SyntheticSection(Flags, Type, Alignment, Name),
Rafael Espindola25324312017-02-03 21:29:51 +00002155 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002156
Rafael Espindola6119b862017-03-06 20:23:56 +00002157void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002158 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002159 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002160}
2161
Rafael Espindola6119b862017-03-06 20:23:56 +00002162void MergeSyntheticSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002163
Rafael Espindola6119b862017-03-06 20:23:56 +00002164bool MergeSyntheticSection::shouldTailMerge() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002165 return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
2166}
2167
Rafael Espindola6119b862017-03-06 20:23:56 +00002168void MergeSyntheticSection::finalizeTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002169 // Add all string pieces to the string table builder to create section
2170 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002171 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002172 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2173 if (Sec->Pieces[I].Live)
2174 Builder.add(Sec->getData(I));
2175
2176 // Fix the string table content. After this, the contents will never change.
2177 Builder.finalize();
2178
2179 // finalize() fixed tail-optimized strings, so we can now get
2180 // offsets of strings. Get an offset for each string and save it
2181 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002182 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002183 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2184 if (Sec->Pieces[I].Live)
2185 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2186}
2187
Rafael Espindola6119b862017-03-06 20:23:56 +00002188void MergeSyntheticSection::finalizeNoTailMerge() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002189 // Add all string pieces to the string table builder to create section
2190 // contents. Because we are not tail-optimizing, offsets of strings are
2191 // fixed when they are added to the builder (string table builder contains
2192 // a hash table from strings to offsets).
Rafael Espindola6119b862017-03-06 20:23:56 +00002193 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002194 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2195 if (Sec->Pieces[I].Live)
2196 Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
2197
2198 Builder.finalizeInOrder();
2199}
2200
Rafael Espindola6119b862017-03-06 20:23:56 +00002201void MergeSyntheticSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002202 if (shouldTailMerge())
2203 finalizeTailMerge();
2204 else
2205 finalizeNoTailMerge();
2206}
2207
Rafael Espindola6119b862017-03-06 20:23:56 +00002208size_t MergeSyntheticSection::getSize() const {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002209 return Builder.getSize();
2210}
2211
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002212// This function decompresses compressed sections and scans over the input
2213// sections to create mergeable synthetic sections. It removes
2214// MergeInputSections from the input section array and adds new synthetic
2215// sections at the location of the first input section that it replaces. It then
2216// finalizes each synthetic section in order to compute an output offset for
2217// each piece of each input section.
2218void elf::decompressAndMergeSections() {
2219 // splitIntoPieces needs to be called on each MergeInputSection before calling
2220 // finalizeContents(). Do that first.
2221 parallelForEach(InputSections.begin(), InputSections.end(),
2222 [](InputSectionBase *S) {
2223 if (!S->Live)
2224 return;
2225 if (Decompressor::isCompressedELFSection(S->Flags, S->Name))
2226 S->uncompress();
2227 if (auto *MS = dyn_cast<MergeInputSection>(S))
2228 MS->splitIntoPieces();
2229 });
2230
2231 std::vector<MergeSyntheticSection *> MergeSections;
2232 for (InputSectionBase *&S : InputSections) {
2233 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2234 if (!MS)
2235 continue;
2236
2237 // We do not want to handle sections that are not alive, so just remove
2238 // them instead of trying to merge.
2239 if (!MS->Live)
2240 continue;
2241
2242 StringRef OutsecName = getOutputSectionName(MS->Name);
2243 uint64_t Flags = MS->Flags & ~(uint64_t)SHF_GROUP;
2244 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2245
2246 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
2247 return Sec->Name == OutsecName && Sec->Flags == Flags &&
2248 Sec->Alignment == Alignment;
2249 });
2250 if (I == MergeSections.end()) {
2251 MergeSyntheticSection *Syn =
2252 make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
2253 MergeSections.push_back(Syn);
2254 I = std::prev(MergeSections.end());
2255 S = Syn;
2256 } else {
2257 S = nullptr;
2258 }
2259 (*I)->addSection(MS);
2260 }
2261 for (auto *MS : MergeSections)
2262 MS->finalizeContents();
2263
2264 std::vector<InputSectionBase *> &V = InputSections;
2265 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2266}
2267
George Rimar42886c42017-03-15 12:02:31 +00002268MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002269 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2270 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002271
George Rimar90a528b2017-03-21 09:01:39 +00002272ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002273 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002274 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002275
2276// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2277// This section will have been sorted last in the .ARM.exidx table.
2278// This table entry will have the form:
2279// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002280// The sentinel must have the PREL31 value of an address higher than any
2281// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002282void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002283 // The Sections are sorted in order of ascending PREL31 address with the
2284 // sentinel last. We need to find the InputSection that precedes the
2285 // sentinel. By construction the Sentinel is in the last
2286 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002287 OutputSectionCommand *C = Script->getCmd(getParent());
Peter Smithea79b212017-05-31 09:02:21 +00002288 auto ISD = std::find_if(C->Commands.rbegin(), C->Commands.rend(),
2289 [](const BaseCommand *Base) {
2290 return isa<InputSectionDescription>(Base);
2291 });
2292 auto L = cast<InputSectionDescription>(*ISD);
2293 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002294 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002295 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002296 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002297 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2298 write32le(Buf + 4, 0x1);
2299}
2300
George Rimar7b827042017-03-16 10:40:50 +00002301ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002302 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002303 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002304 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002305 this->OutSecOff = Off;
2306}
2307
George Rimar7b827042017-03-16 10:40:50 +00002308void ThunkSection::addThunk(Thunk *T) {
Peter Smith3a52eb02017-02-01 10:26:03 +00002309 uint64_t Off = alignTo(Size, T->alignment);
2310 T->Offset = Off;
2311 Thunks.push_back(T);
2312 T->addSymbols(*this);
2313 Size = Off + T->size();
2314}
2315
George Rimar7b827042017-03-16 10:40:50 +00002316void ThunkSection::writeTo(uint8_t *Buf) {
2317 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002318 T->writeTo(Buf + T->Offset, *this);
2319}
2320
George Rimar7b827042017-03-16 10:40:50 +00002321InputSection *ThunkSection::getTargetInputSection() const {
2322 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002323 return T->getTargetInputSection();
2324}
2325
George Rimar9782ca52017-03-15 15:29:29 +00002326InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002327BssSection *InX::Bss;
2328BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002329BuildIdSection *InX::BuildId;
George Rimar9782ca52017-03-15 15:29:29 +00002330InputSection *InX::Common;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002331SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002332StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002333SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002334InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002335GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002336GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002337GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002338GnuHashTableSection *InX::GnuHashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002339IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002340MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002341MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002342PltSection *InX::Plt;
2343PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002344StringTableSection *InX::ShStrTab;
2345StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002346SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002347
George Rimara9189572017-03-17 16:50:07 +00002348template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2349template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2350template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2351template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2352
Rafael Espindola774ea7d2017-02-23 16:49:07 +00002353template InputSection *elf::createCommonSection<ELF32LE>();
2354template InputSection *elf::createCommonSection<ELF32BE>();
2355template InputSection *elf::createCommonSection<ELF64LE>();
2356template InputSection *elf::createCommonSection<ELF64BE>();
Rui Ueyamae8a61022016-11-05 23:05:47 +00002357
Rafael Espindola6119b862017-03-06 20:23:56 +00002358template MergeInputSection *elf::createCommentSection<ELF32LE>();
2359template MergeInputSection *elf::createCommentSection<ELF32BE>();
2360template MergeInputSection *elf::createCommentSection<ELF64LE>();
2361template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002362
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002363template class elf::MipsAbiFlagsSection<ELF32LE>;
2364template class elf::MipsAbiFlagsSection<ELF32BE>;
2365template class elf::MipsAbiFlagsSection<ELF64LE>;
2366template class elf::MipsAbiFlagsSection<ELF64BE>;
2367
Simon Atanasyance02cf02016-11-09 21:36:56 +00002368template class elf::MipsOptionsSection<ELF32LE>;
2369template class elf::MipsOptionsSection<ELF32BE>;
2370template class elf::MipsOptionsSection<ELF64LE>;
2371template class elf::MipsOptionsSection<ELF64BE>;
2372
2373template class elf::MipsReginfoSection<ELF32LE>;
2374template class elf::MipsReginfoSection<ELF32BE>;
2375template class elf::MipsReginfoSection<ELF64LE>;
2376template class elf::MipsReginfoSection<ELF64BE>;
2377
Eugene Leviant6380ce22016-11-15 12:26:55 +00002378template class elf::DynamicSection<ELF32LE>;
2379template class elf::DynamicSection<ELF32BE>;
2380template class elf::DynamicSection<ELF64LE>;
2381template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002382
2383template class elf::RelocationSection<ELF32LE>;
2384template class elf::RelocationSection<ELF32BE>;
2385template class elf::RelocationSection<ELF64LE>;
2386template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002387
2388template class elf::SymbolTableSection<ELF32LE>;
2389template class elf::SymbolTableSection<ELF32BE>;
2390template class elf::SymbolTableSection<ELF64LE>;
2391template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002392
Eugene Leviantb96e8092016-11-18 09:06:47 +00002393template class elf::HashTableSection<ELF32LE>;
2394template class elf::HashTableSection<ELF32BE>;
2395template class elf::HashTableSection<ELF64LE>;
2396template class elf::HashTableSection<ELF64BE>;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00002397
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002398template class elf::EhFrameHeader<ELF32LE>;
2399template class elf::EhFrameHeader<ELF32BE>;
2400template class elf::EhFrameHeader<ELF64LE>;
2401template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002402
2403template class elf::VersionTableSection<ELF32LE>;
2404template class elf::VersionTableSection<ELF32BE>;
2405template class elf::VersionTableSection<ELF64LE>;
2406template class elf::VersionTableSection<ELF64BE>;
2407
2408template class elf::VersionNeedSection<ELF32LE>;
2409template class elf::VersionNeedSection<ELF32BE>;
2410template class elf::VersionNeedSection<ELF64LE>;
2411template class elf::VersionNeedSection<ELF64BE>;
2412
2413template class elf::VersionDefinitionSection<ELF32LE>;
2414template class elf::VersionDefinitionSection<ELF32BE>;
2415template class elf::VersionDefinitionSection<ELF64LE>;
2416template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002417
Rafael Espindola66b4e212017-02-23 22:06:28 +00002418template class elf::EhFrameSection<ELF32LE>;
2419template class elf::EhFrameSection<ELF32BE>;
2420template class elf::EhFrameSection<ELF64LE>;
2421template class elf::EhFrameSection<ELF64BE>;