blob: bd9adab8d5cc724f3062d34d64f2e763d603b8d2 [file] [log] [blame]
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +00001//===- SyntheticSections.cpp ----------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains linker-synthesized sections. Currently,
11// synthetic sections are created either output sections or input sections,
12// but we are rewriting code so that all synthetic sections are created as
13// input sections.
14//
15//===----------------------------------------------------------------------===//
16
17#include "SyntheticSections.h"
Rui Ueyama6e5fda92017-10-26 21:37:17 +000018#include "Bits.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000019#include "Config.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000020#include "InputFiles.h"
Eugene Leviant17b7a572016-11-22 17:49:14 +000021#include "LinkerScript.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000022#include "Memory.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000023#include "OutputSections.h"
24#include "Strings.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000025#include "SymbolTable.h"
Simon Atanasyance02cf02016-11-09 21:36:56 +000026#include "Target.h"
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +000027#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000028#include "lld/Common/ErrorHandler.h"
Bob Haarman4f5c8c22017-10-13 18:22:55 +000029#include "lld/Common/Threads.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000030#include "lld/Common/Version.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000031#include "llvm/BinaryFormat/Dwarf.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000032#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Peter Collingbournedc7936e2017-06-12 00:00:51 +000033#include "llvm/Object/Decompressor.h"
Rui Ueyamaac2d8152017-03-01 22:54:50 +000034#include "llvm/Object/ELFObjectFile.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000035#include "llvm/Support/Endian.h"
36#include "llvm/Support/MD5.h"
37#include "llvm/Support/RandomNumberGenerator.h"
38#include "llvm/Support/SHA1.h"
39#include "llvm/Support/xxhash.h"
Rui Ueyama3da3f062016-11-10 20:20:37 +000040#include <cstdlib>
Rui Ueyamac97a70c2017-09-30 11:46:26 +000041#include <thread>
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000042
43using namespace llvm;
Eugene Leviant952eb4d2016-11-21 15:52:10 +000044using namespace llvm::dwarf;
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000045using namespace llvm::ELF;
46using namespace llvm::object;
47using namespace llvm::support;
48using namespace llvm::support::endian;
49
50using namespace lld;
51using namespace lld::elf;
52
NAKAMURA Takumi70947e22017-09-30 13:40:22 +000053constexpr size_t MergeNoTailSection::NumShards;
Rui Ueyamac97a70c2017-09-30 11:46:26 +000054
Rui Ueyama9320cb02017-02-27 02:56:02 +000055uint64_t SyntheticSection::getVA() const {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +000056 if (OutputSection *Sec = getParent())
57 return Sec->Addr + OutSecOff;
Rui Ueyama9320cb02017-02-27 02:56:02 +000058 return 0;
59}
60
Rui Ueyama0fda1d72017-10-06 04:32:08 +000061// Create a .bss section for each common symbol and replace the common symbol
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000062// with a DefinedRegular symbol.
63template <class ELFT> void elf::createCommonSections() {
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000064 for (Symbol *S : Symtab->getSymbols()) {
65 auto *Sym = dyn_cast<DefinedCommon>(S->body());
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000066
67 if (!Sym)
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000068 continue;
George Rimar176d6062017-03-17 13:31:07 +000069
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000070 // Create a synthetic section for the common data.
Rui Ueyama732f4e22017-10-04 00:21:17 +000071 auto *Section = make<BssSection>("COMMON", Sym->Size, Sym->Alignment);
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000072 Section->File = Sym->getFile();
73 Section->Live = !Config->GcSections;
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000074 InputSections.push_back(Section);
75
76 // Replace all DefinedCommon symbols with DefinedRegular symbols so that we
77 // don't have to care about DefinedCommon symbols beyond this point.
78 replaceBody<DefinedRegular>(S, Sym->getFile(), Sym->getName(),
Rui Ueyama662bb002017-10-13 03:37:26 +000079 static_cast<bool>(Sym->isLocal()), Sym->StOther,
Ben Dunbobbin73eabf22017-09-29 09:08:26 +000080 Sym->Type, 0, Sym->getSize<ELFT>(), Section);
Dmitry Mikulin1e30f072017-09-08 16:22:43 +000081 }
Rui Ueyamae8a61022016-11-05 23:05:47 +000082}
83
Rui Ueyama3da3f062016-11-10 20:20:37 +000084// Returns an LLD version string.
85static ArrayRef<uint8_t> getVersion() {
86 // Check LLD_VERSION first for ease of testing.
87 // You can get consitent output by using the environment variable.
88 // This is only for testing.
89 StringRef S = getenv("LLD_VERSION");
90 if (S.empty())
91 S = Saver.save(Twine("Linker: ") + getLLDVersion());
92
93 // +1 to include the terminating '\0'.
94 return {(const uint8_t *)S.data(), S.size() + 1};
Davide Italianob69f38f2016-11-11 00:05:41 +000095}
Rui Ueyama3da3f062016-11-10 20:20:37 +000096
97// Creates a .comment section containing LLD version info.
98// With this feature, you can identify LLD-generated binaries easily
Rui Ueyama42fca6e2017-04-27 04:50:08 +000099// by "readelf --string-dump .comment <file>".
Rui Ueyama3da3f062016-11-10 20:20:37 +0000100// The returned object is a mergeable string section.
Rafael Espindola6119b862017-03-06 20:23:56 +0000101template <class ELFT> MergeInputSection *elf::createCommentSection() {
Rui Ueyama3da3f062016-11-10 20:20:37 +0000102 typename ELFT::Shdr Hdr = {};
103 Hdr.sh_flags = SHF_MERGE | SHF_STRINGS;
104 Hdr.sh_type = SHT_PROGBITS;
105 Hdr.sh_entsize = 1;
106 Hdr.sh_addralign = 1;
107
Rafael Espindola6119b862017-03-06 20:23:56 +0000108 auto *Ret =
Rui Ueyama709fb2bb12017-07-26 22:13:32 +0000109 make<MergeInputSection>((ObjFile<ELFT> *)nullptr, &Hdr, ".comment");
Rui Ueyama3da3f062016-11-10 20:20:37 +0000110 Ret->Data = getVersion();
Rui Ueyama3da3f062016-11-10 20:20:37 +0000111 return Ret;
112}
113
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000114// .MIPS.abiflags section.
115template <class ELFT>
Rui Ueyama12f2da82016-11-22 03:57:06 +0000116MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000117 : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
Rui Ueyama27876642017-03-01 04:04:23 +0000118 Flags(Flags) {
119 this->Entsize = sizeof(Elf_Mips_ABIFlags);
120}
Rui Ueyama12f2da82016-11-22 03:57:06 +0000121
122template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
123 memcpy(Buf, &Flags, sizeof(Flags));
124}
125
126template <class ELFT>
127MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
128 Elf_Mips_ABIFlags Flags = {};
129 bool Create = false;
130
Rui Ueyama536a2672017-02-27 02:32:08 +0000131 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000132 if (Sec->Type != SHT_MIPS_ABIFLAGS)
Rui Ueyama12f2da82016-11-22 03:57:06 +0000133 continue;
134 Sec->Live = false;
135 Create = true;
136
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000137 std::string Filename = toString(Sec->getFile<ELFT>());
Simon Atanasyan86dc60d2016-12-21 05:31:57 +0000138 const size_t Size = Sec->Data.size();
139 // Older version of BFD (such as the default FreeBSD linker) concatenate
140 // .MIPS.abiflags instead of merging. To allow for this case (or potential
141 // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
142 if (Size < sizeof(Elf_Mips_ABIFlags)) {
143 error(Filename + ": invalid size of .MIPS.abiflags section: got " +
144 Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000145 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000146 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000147 auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000148 if (S->version != 0) {
Rui Ueyama12f2da82016-11-22 03:57:06 +0000149 error(Filename + ": unexpected .MIPS.abiflags version " +
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000150 Twine(S->version));
Rui Ueyama12f2da82016-11-22 03:57:06 +0000151 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000152 }
Rui Ueyama12f2da82016-11-22 03:57:06 +0000153
Simon Atanasyan649e4d32017-10-02 14:56:41 +0000154 // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000155 // select the highest number of ISA/Rev/Ext.
156 Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
157 Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
158 Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
159 Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
160 Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
161 Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
162 Flags.ases |= S->ases;
163 Flags.flags1 |= S->flags1;
164 Flags.flags2 |= S->flags2;
Rui Ueyama12f2da82016-11-22 03:57:06 +0000165 Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000166 };
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000167
Rui Ueyama12f2da82016-11-22 03:57:06 +0000168 if (Create)
169 return make<MipsAbiFlagsSection<ELFT>>(Flags);
170 return nullptr;
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +0000171}
172
Simon Atanasyance02cf02016-11-09 21:36:56 +0000173// .MIPS.options section.
174template <class ELFT>
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000175MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000176 : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
Rui Ueyama27876642017-03-01 04:04:23 +0000177 Reginfo(Reginfo) {
178 this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
179}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000180
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000181template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
182 auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
183 Options->kind = ODK_REGINFO;
184 Options->size = getSize();
185
186 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000187 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rafael Espindola4862ae82016-11-24 16:38:35 +0000188 memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
Simon Atanasyance02cf02016-11-09 21:36:56 +0000189}
190
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000191template <class ELFT>
192MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
193 // N64 ABI only.
194 if (!ELFT::Is64Bits)
195 return nullptr;
196
197 Elf_Mips_RegInfo Reginfo = {};
198 bool Create = false;
199
Rui Ueyama536a2672017-02-27 02:32:08 +0000200 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000201 if (Sec->Type != SHT_MIPS_OPTIONS)
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000202 continue;
203 Sec->Live = false;
204 Create = true;
205
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000206 std::string Filename = toString(Sec->getFile<ELFT>());
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000207 ArrayRef<uint8_t> D = Sec->Data;
208
209 while (!D.empty()) {
210 if (D.size() < sizeof(Elf_Mips_Options)) {
211 error(Filename + ": invalid size of .MIPS.options section");
212 break;
213 }
214
215 auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
216 if (Opt->kind == ODK_REGINFO) {
217 if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
218 error(Filename + ": unsupported non-zero ri_gp_value");
219 Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000220 Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000221 break;
222 }
223
224 if (!Opt->size)
225 fatal(Filename + ": zero option descriptor size");
226 D = D.slice(Opt->size);
227 }
228 };
229
230 if (Create)
Rui Ueyama3cc93d72016-11-22 23:13:08 +0000231 return make<MipsOptionsSection<ELFT>>(Reginfo);
Rui Ueyama9cfac8a2016-11-22 04:13:09 +0000232 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000233}
234
235// MIPS .reginfo section.
236template <class ELFT>
Rui Ueyamab71cae92016-11-22 03:57:08 +0000237MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
Rui Ueyama9320cb02017-02-27 02:56:02 +0000238 : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
Rui Ueyama27876642017-03-01 04:04:23 +0000239 Reginfo(Reginfo) {
240 this->Entsize = sizeof(Elf_Mips_RegInfo);
241}
Simon Atanasyance02cf02016-11-09 21:36:56 +0000242
Rui Ueyamab71cae92016-11-22 03:57:08 +0000243template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyance02cf02016-11-09 21:36:56 +0000244 if (!Config->Relocatable)
Rafael Espindolab3aa2c92017-05-11 21:33:30 +0000245 Reginfo.ri_gp_value = InX::MipsGot->getGp();
Rui Ueyamab71cae92016-11-22 03:57:08 +0000246 memcpy(Buf, &Reginfo, sizeof(Reginfo));
247}
248
249template <class ELFT>
250MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
251 // Section should be alive for O32 and N32 ABIs only.
252 if (ELFT::Is64Bits)
253 return nullptr;
254
255 Elf_Mips_RegInfo Reginfo = {};
256 bool Create = false;
257
Rui Ueyama536a2672017-02-27 02:32:08 +0000258 for (InputSectionBase *Sec : InputSections) {
Simon Atanasyan462f84a2017-03-17 14:27:55 +0000259 if (Sec->Type != SHT_MIPS_REGINFO)
Rui Ueyamab71cae92016-11-22 03:57:08 +0000260 continue;
261 Sec->Live = false;
262 Create = true;
263
264 if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000265 error(toString(Sec->getFile<ELFT>()) +
266 ": invalid size of .reginfo section");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000267 return nullptr;
268 }
269 auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
270 if (Config->Relocatable && R->ri_gp_value)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000271 error(toString(Sec->getFile<ELFT>()) +
272 ": unsupported non-zero ri_gp_value");
Rui Ueyamab71cae92016-11-22 03:57:08 +0000273
274 Reginfo.ri_gprmask |= R->ri_gprmask;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000275 Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
Rui Ueyamab71cae92016-11-22 03:57:08 +0000276 };
277
278 if (Create)
279 return make<MipsReginfoSection<ELFT>>(Reginfo);
280 return nullptr;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000281}
282
Rui Ueyama3255a522017-02-27 02:32:49 +0000283InputSection *elf::createInterpSection() {
Rui Ueyama81a4b262016-11-22 04:33:01 +0000284 // StringSaver guarantees that the returned string ends with '\0'.
285 StringRef S = Saver.save(Config->DynamicLinker);
Rui Ueyama6e50fd52017-03-01 07:39:06 +0000286 ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
287
288 auto *Sec =
289 make<InputSection>(SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp");
290 Sec->Live = true;
291 return Sec;
Rui Ueyamaa9ee8d62016-11-04 22:25:39 +0000292}
Rui Ueyamae288eef2016-11-02 18:58:44 +0000293
Rui Ueyama65316d72017-02-23 03:15:57 +0000294SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
295 uint64_t Size, InputSectionBase *Section) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000296 auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type,
Rafael Espindola6e93d052017-08-04 22:31:42 +0000297 Value, Size, Section);
George Rimar69b17c32017-05-16 10:04:42 +0000298 if (InX::SymTab)
299 InX::SymTab->addSymbol(S);
Peter Smith96943762017-01-25 10:31:16 +0000300 return S;
301}
302
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000303static size_t getHashSize() {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000304 switch (Config->BuildId) {
305 case BuildIdKind::Fast:
306 return 8;
307 case BuildIdKind::Md5:
308 case BuildIdKind::Uuid:
309 return 16;
310 case BuildIdKind::Sha1:
311 return 20;
312 case BuildIdKind::Hexstring:
313 return Config->BuildIdVector.size();
314 default:
315 llvm_unreachable("unknown BuildIdKind");
316 }
317}
318
George Rimar6c2949d2017-03-20 16:40:21 +0000319BuildIdSection::BuildIdSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000320 : SyntheticSection(SHF_ALLOC, SHT_NOTE, 1, ".note.gnu.build-id"),
Rui Ueyamabb536fe2016-11-22 01:36:19 +0000321 HashSize(getHashSize()) {}
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000322
George Rimar6c2949d2017-03-20 16:40:21 +0000323void BuildIdSection::writeTo(uint8_t *Buf) {
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000324 endianness E = Config->Endianness;
George Rimar6c2949d2017-03-20 16:40:21 +0000325 write32(Buf, 4, E); // Name size
326 write32(Buf + 4, HashSize, E); // Content size
327 write32(Buf + 8, NT_GNU_BUILD_ID, E); // Type
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000328 memcpy(Buf + 12, "GNU", 4); // Name string
329 HashBuf = Buf + 16;
330}
331
Rui Ueyama35e00752016-11-10 00:12:28 +0000332// Split one uint8 array into small pieces of uint8 arrays.
George Rimar364b59e22016-11-06 07:42:55 +0000333static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
334 size_t ChunkSize) {
335 std::vector<ArrayRef<uint8_t>> Ret;
336 while (Arr.size() > ChunkSize) {
337 Ret.push_back(Arr.take_front(ChunkSize));
338 Arr = Arr.drop_front(ChunkSize);
339 }
340 if (!Arr.empty())
341 Ret.push_back(Arr);
342 return Ret;
343}
344
Rui Ueyama35e00752016-11-10 00:12:28 +0000345// Computes a hash value of Data using a given hash function.
346// In order to utilize multiple cores, we first split data into 1MB
347// chunks, compute a hash for each chunk, and then compute a hash value
348// of the hash values.
George Rimar6c2949d2017-03-20 16:40:21 +0000349void BuildIdSection::computeHash(
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000350 llvm::ArrayRef<uint8_t> Data,
351 std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
George Rimar364b59e22016-11-06 07:42:55 +0000352 std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000353 std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
George Rimar364b59e22016-11-06 07:42:55 +0000354
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000355 // Compute hash values.
Rui Ueyama33d903d2017-05-10 20:02:19 +0000356 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama4995afd2017-03-22 23:03:35 +0000357 HashFn(Hashes.data() + I * HashSize, Chunks[I]);
358 });
Rui Ueyama35e00752016-11-10 00:12:28 +0000359
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000360 // Write to the final output buffer.
361 HashFn(HashBuf, Hashes);
George Rimar364b59e22016-11-06 07:42:55 +0000362}
363
Rui Ueyama732f4e22017-10-04 00:21:17 +0000364BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
365 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000366 if (OutputSection *Sec = getParent())
Rui Ueyama8befefb2017-10-07 00:58:34 +0000367 Sec->Alignment = std::max(Sec->Alignment, Alignment);
Rui Ueyama732f4e22017-10-04 00:21:17 +0000368 this->Size = Size;
George Rimar1ab9cf42017-03-17 10:14:53 +0000369}
Peter Smithebfe9942017-02-09 10:27:57 +0000370
George Rimar6c2949d2017-03-20 16:40:21 +0000371void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000372 switch (Config->BuildId) {
373 case BuildIdKind::Fast:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000374 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyamac4030a12016-11-22 00:54:15 +0000375 write64le(Dest, xxHash64(toStringRef(Arr)));
376 });
377 break;
378 case BuildIdKind::Md5:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000379 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000380 memcpy(Dest, MD5::hash(Arr).data(), 16);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000381 });
382 break;
383 case BuildIdKind::Sha1:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000384 computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
Rui Ueyama28590b62016-11-23 18:11:38 +0000385 memcpy(Dest, SHA1::hash(Arr).data(), 20);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000386 });
387 break;
388 case BuildIdKind::Uuid:
Rui Ueyama88f05682017-10-27 01:25:29 +0000389 if (auto EC = getRandomBytes(HashBuf, HashSize))
390 error("entropy source failure: " + EC.message());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000391 break;
392 case BuildIdKind::Hexstring:
Rui Ueyama2d98fea2016-11-22 01:31:32 +0000393 memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
Rui Ueyamac4030a12016-11-22 00:54:15 +0000394 break;
395 default:
396 llvm_unreachable("unknown BuildIdKind");
397 }
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +0000398}
399
Eugene Leviant41ca3272016-11-10 09:48:29 +0000400template <class ELFT>
Rafael Espindola66b4e212017-02-23 22:06:28 +0000401EhFrameSection<ELFT>::EhFrameSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000402 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
Rafael Espindola66b4e212017-02-23 22:06:28 +0000403
404// Search for an existing CIE record or create a new one.
405// CIE records from input object files are uniquified by their contents
406// and where their relocations point to.
407template <class ELFT>
408template <class RelTy>
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000409CieRecord *EhFrameSection<ELFT>::addCie(EhSectionPiece &Cie,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000410 ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000411 auto *Sec = cast<EhInputSection>(Cie.Sec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000412 const endianness E = ELFT::TargetEndianness;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000413 if (read32<E>(Cie.data().data() + 4) != 0)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000414 fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
415
416 SymbolBody *Personality = nullptr;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000417 unsigned FirstRelI = Cie.FirstRelocation;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000418 if (FirstRelI != (unsigned)-1)
419 Personality =
420 &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
421
422 // Search for an existing CIE by CIE contents/relocation target pair.
George Rimar94444b92017-09-20 09:27:41 +0000423 CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
Rafael Espindola66b4e212017-02-23 22:06:28 +0000424
425 // If not found, create a new one.
George Rimar94444b92017-09-20 09:27:41 +0000426 if (!Rec) {
427 Rec = make<CieRecord>();
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000428 Rec->Cie = &Cie;
429 CieRecords.push_back(Rec);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000430 }
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000431 return Rec;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000432}
433
434// There is one FDE per function. Returns true if a given FDE
435// points to a live function.
436template <class ELFT>
437template <class RelTy>
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000438bool EhFrameSection<ELFT>::isFdeLive(EhSectionPiece &Fde,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000439 ArrayRef<RelTy> Rels) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000440 auto *Sec = cast<EhInputSection>(Fde.Sec);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000441 unsigned FirstRelI = Fde.FirstRelocation;
Rui Ueyama56614e42017-09-12 23:43:45 +0000442
443 // An FDE should point to some function because FDEs are to describe
444 // functions. That's however not always the case due to an issue of
445 // ld.gold with -r. ld.gold may discard only functions and leave their
446 // corresponding FDEs, which results in creating bad .eh_frame sections.
447 // To deal with that, we ignore such FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +0000448 if (FirstRelI == (unsigned)-1)
449 return false;
Rui Ueyama56614e42017-09-12 23:43:45 +0000450
Rafael Espindola66b4e212017-02-23 22:06:28 +0000451 const RelTy &Rel = Rels[FirstRelI];
452 SymbolBody &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
George Rimard605f412017-10-26 09:13:19 +0000453
454 // FDEs for garbage-collected or merged-by-ICF sections are dead.
Rui Ueyama27a357c2017-09-18 19:15:54 +0000455 if (auto *D = dyn_cast<DefinedRegular>(&B))
George Rimard605f412017-10-26 09:13:19 +0000456 if (auto *Sec = cast_or_null<InputSectionBase>(D->Section))
457 return Sec->Live && (Sec == Sec->Repl);
Rui Ueyama27a357c2017-09-18 19:15:54 +0000458 return false;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000459}
460
461// .eh_frame is a sequence of CIE or FDE records. In general, there
462// is one CIE record per input object file which is followed by
463// a list of FDEs. This function searches an existing CIE or create a new
464// one and associates FDEs to the CIE.
465template <class ELFT>
466template <class RelTy>
Rafael Espindola5c02b742017-03-06 21:17:18 +0000467void EhFrameSection<ELFT>::addSectionAux(EhInputSection *Sec,
Rafael Espindola66b4e212017-02-23 22:06:28 +0000468 ArrayRef<RelTy> Rels) {
469 const endianness E = ELFT::TargetEndianness;
470
471 DenseMap<size_t, CieRecord *> OffsetToCie;
472 for (EhSectionPiece &Piece : Sec->Pieces) {
473 // The empty record is the end marker.
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000474 if (Piece.Size == 4)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000475 return;
476
477 size_t Offset = Piece.InputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000478 uint32_t ID = read32<E>(Piece.data().data() + 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000479 if (ID == 0) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000480 OffsetToCie[Offset] = addCie(Piece, Rels);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000481 continue;
482 }
483
484 uint32_t CieOffset = Offset + 4 - ID;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000485 CieRecord *Rec = OffsetToCie[CieOffset];
486 if (!Rec)
Rafael Espindola66b4e212017-02-23 22:06:28 +0000487 fatal(toString(Sec) + ": invalid CIE reference");
488
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000489 if (!isFdeLive(Piece, Rels))
Rafael Espindola66b4e212017-02-23 22:06:28 +0000490 continue;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000491 Rec->Fdes.push_back(&Piece);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000492 NumFdes++;
493 }
494}
495
496template <class ELFT>
497void EhFrameSection<ELFT>::addSection(InputSectionBase *C) {
Rafael Espindola5c02b742017-03-06 21:17:18 +0000498 auto *Sec = cast<EhInputSection>(C);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000499 Sec->Parent = this;
Rui Ueyama8befefb2017-10-07 00:58:34 +0000500
501 Alignment = std::max(Alignment, Sec->Alignment);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000502 Sections.push_back(Sec);
Rui Ueyama8befefb2017-10-07 00:58:34 +0000503
Petr Hosek7b793212017-03-10 20:00:42 +0000504 for (auto *DS : Sec->DependentSections)
505 DependentSections.push_back(DS);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000506
507 // .eh_frame is a sequence of CIE or FDE records. This function
508 // splits it into pieces so that we can call
509 // SplitInputSection::getSectionPiece on the section.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000510 Sec->split<ELFT>();
Rafael Espindola66b4e212017-02-23 22:06:28 +0000511 if (Sec->Pieces.empty())
512 return;
513
Rui Ueyamabfa84322017-10-26 22:30:25 +0000514 if (Sec->AreRelocsRela)
Rui Ueyamafaa38022017-09-19 20:28:03 +0000515 addSectionAux(Sec, Sec->template relas<ELFT>());
516 else
517 addSectionAux(Sec, Sec->template rels<ELFT>());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000518}
519
520template <class ELFT>
521static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
522 memcpy(Buf, D.data(), D.size());
523
Andrew Ng6dee7362017-09-07 08:43:56 +0000524 size_t Aligned = alignTo(D.size(), sizeof(typename ELFT::uint));
525
526 // Zero-clear trailing padding if it exists.
527 memset(Buf + D.size(), 0, Aligned - D.size());
528
Rafael Espindola66b4e212017-02-23 22:06:28 +0000529 // Fix the size field. -4 since size does not include the size field itself.
530 const endianness E = ELFT::TargetEndianness;
Andrew Ng6dee7362017-09-07 08:43:56 +0000531 write32<E>(Buf, Aligned - 4);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000532}
533
Rui Ueyama945055a2017-02-27 03:07:41 +0000534template <class ELFT> void EhFrameSection<ELFT>::finalizeContents() {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000535 if (this->Size)
536 return; // Already finalized.
537
538 size_t Off = 0;
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000539 for (CieRecord *Rec : CieRecords) {
540 Rec->Cie->OutputOff = Off;
541 Off += alignTo(Rec->Cie->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000542
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000543 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000544 Fde->OutputOff = Off;
Rui Ueyamaa6ff6172017-09-18 23:07:09 +0000545 Off += alignTo(Fde->Size, Config->Wordsize);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000546 }
547 }
Rafael Espindolaa8a1a4f2017-05-02 15:45:31 +0000548
549 // The LSB standard does not allow a .eh_frame section with zero
550 // Call Frame Information records. Therefore add a CIE record length
551 // 0 as a terminator if this .eh_frame section is empty.
552 if (Off == 0)
553 Off = 4;
554
Rafael Espindolab691ccf2017-02-28 18:55:08 +0000555 this->Size = Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000556}
557
558template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
559 const endianness E = ELFT::TargetEndianness;
560 switch (Size) {
561 case DW_EH_PE_udata2:
562 return read16<E>(Buf);
563 case DW_EH_PE_udata4:
564 return read32<E>(Buf);
565 case DW_EH_PE_udata8:
566 return read64<E>(Buf);
567 case DW_EH_PE_absptr:
568 if (ELFT::Is64Bits)
569 return read64<E>(Buf);
570 return read32<E>(Buf);
571 }
572 fatal("unknown FDE size encoding");
573}
574
575// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
576// We need it to create .eh_frame_hdr section.
577template <class ELFT>
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000578uint64_t EhFrameSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
579 uint8_t Enc) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000580 // The starting address to which this FDE applies is
581 // stored at FDE + 8 byte.
582 size_t Off = FdeOff + 8;
583 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
584 if ((Enc & 0x70) == DW_EH_PE_absptr)
585 return Addr;
586 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000587 return Addr + getParent()->Addr + Off;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000588 fatal("unknown FDE size relative encoding");
589}
590
591template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) {
592 const endianness E = ELFT::TargetEndianness;
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000593
594 // Write CIE and FDE records.
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000595 for (CieRecord *Rec : CieRecords) {
596 size_t CieOffset = Rec->Cie->OutputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000597 writeCieFde<ELFT>(Buf + CieOffset, Rec->Cie->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000598
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000599 for (EhSectionPiece *Fde : Rec->Fdes) {
Rafael Espindola66b4e212017-02-23 22:06:28 +0000600 size_t Off = Fde->OutputOff;
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000601 writeCieFde<ELFT>(Buf + Off, Fde->data());
Rafael Espindola66b4e212017-02-23 22:06:28 +0000602
603 // FDE's second word should have the offset to an associated CIE.
604 // Write it.
605 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
606 }
607 }
608
Rui Ueyamac9a4d1c2017-10-10 03:58:18 +0000609 // Apply relocations. .eh_frame section contents are not contiguous
610 // in the output buffer, but relocateAlloc() still works because
611 // getOffset() takes care of discontiguous section pieces.
Rafael Espindola5c02b742017-03-06 21:17:18 +0000612 for (EhInputSection *S : Sections)
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000613 S->relocateAlloc(Buf, nullptr);
Rafael Espindola66b4e212017-02-23 22:06:28 +0000614
615 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
616 // to get a FDE from an address to which FDE is applied. So here
617 // we obtain two addresses and pass them to EhFrameHdr object.
618 if (In<ELFT>::EhFrameHdr) {
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000619 for (CieRecord *Rec : CieRecords) {
NAKAMURA Takumi169dbde2017-09-20 08:03:18 +0000620 uint8_t Enc = getFdeEncoding<ELFT>(Rec->Cie);
Rui Ueyama74ea1f02017-09-19 21:31:57 +0000621 for (EhSectionPiece *Fde : Rec->Fdes) {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000622 uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000623 uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
Rafael Espindola66b4e212017-02-23 22:06:28 +0000624 In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
625 }
626 }
627 }
628}
629
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000630GotSection::GotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000631 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
632 Target->GotEntrySize, ".got") {}
Eugene Leviantad4439e2016-11-11 11:33:32 +0000633
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000634void GotSection::addEntry(SymbolBody &Sym) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000635 Sym.GotIndex = NumEntries;
636 ++NumEntries;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000637}
638
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000639bool GotSection::addDynTlsEntry(SymbolBody &Sym) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000640 if (Sym.GlobalDynIndex != -1U)
641 return false;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000642 Sym.GlobalDynIndex = NumEntries;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000643 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000644 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000645 return true;
646}
647
648// Reserves TLS entries for a TLS module ID and a TLS block offset.
649// In total it takes two GOT slots.
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000650bool GotSection::addTlsIndex() {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000651 if (TlsIndexOff != uint32_t(-1))
652 return false;
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000653 TlsIndexOff = NumEntries * Config->Wordsize;
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000654 NumEntries += 2;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000655 return true;
656}
657
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000658uint64_t GotSection::getGlobalDynAddr(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000659 return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000660}
661
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000662uint64_t GotSection::getGlobalDynOffset(const SymbolBody &B) const {
Rui Ueyamac49bdd62017-04-14 01:34:45 +0000663 return B.GlobalDynIndex * Config->Wordsize;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000664}
665
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000666void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000667
Rafael Espindolaa6465bb2017-05-18 16:45:36 +0000668bool GotSection::empty() const {
George Rimar19d6ce92017-09-25 09:46:33 +0000669 // We need to emit a GOT even if it's empty if there's a relocation that is
670 // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
671 // (i.e. _GLOBAL_OFFSET_TABLE_).
672 return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable;
George Rimar11992c862016-11-25 08:05:41 +0000673}
674
Igor Kudrin202a9f62017-07-14 08:10:45 +0000675void GotSection::writeTo(uint8_t *Buf) {
676 // Buf points to the start of this section's buffer,
677 // whereas InputSectionBase::relocateAlloc() expects its argument
678 // to point to the start of the output section.
679 relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
680}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000681
George Rimar14534eb2017-03-20 16:44:28 +0000682MipsGotSection::MipsGotSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000683 : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
684 ".got") {}
Simon Atanasyan725dc142016-11-16 21:01:02 +0000685
George Rimar14534eb2017-03-20 16:44:28 +0000686void MipsGotSection::addEntry(SymbolBody &Sym, int64_t Addend, RelExpr Expr) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000687 // For "true" local symbols which can be referenced from the same module
688 // only compiler creates two instructions for address loading:
689 //
690 // lw $8, 0($gp) # R_MIPS_GOT16
691 // addi $8, $8, 0 # R_MIPS_LO16
692 //
693 // The first instruction loads high 16 bits of the symbol address while
694 // the second adds an offset. That allows to reduce number of required
695 // GOT entries because only one global offset table entry is necessary
696 // for every 64 KBytes of local data. So for local symbols we need to
697 // allocate number of GOT entries to hold all required "page" addresses.
698 //
699 // All global symbols (hidden and regular) considered by compiler uniformly.
700 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
701 // to load address of the symbol. So for each such symbol we need to
702 // allocate dedicated GOT entry to store its address.
703 //
704 // If a symbol is preemptible we need help of dynamic linker to get its
705 // final address. The corresponding GOT entries are allocated in the
706 // "global" part of GOT. Entries for non preemptible global symbol allocated
707 // in the "local" part of GOT.
708 //
709 // See "Global Offset Table" in Chapter 5:
710 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
711 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
712 // At this point we do not know final symbol value so to reduce number
713 // of allocated GOT entries do the following trick. Save all output
714 // sections referenced by GOT relocations. Then later in the `finalize`
715 // method calculate number of "pages" required to cover all saved output
716 // section and allocate appropriate number of GOT entries.
Rafael Espindola23db6362017-05-31 19:22:01 +0000717 PageIndexMap.insert({Sym.getOutputSection(), 0});
Eugene Leviantad4439e2016-11-11 11:33:32 +0000718 return;
719 }
720 if (Sym.isTls()) {
721 // GOT entries created for MIPS TLS relocations behave like
722 // almost GOT entries from other ABIs. They go to the end
723 // of the global offset table.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000724 Sym.GotIndex = TlsEntries.size();
725 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000726 return;
727 }
George Rimar14534eb2017-03-20 16:44:28 +0000728 auto AddEntry = [&](SymbolBody &S, uint64_t A, GotEntries &Items) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000729 if (S.isInGot() && !A)
730 return;
731 size_t NewIndex = Items.size();
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000732 if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000733 return;
734 Items.emplace_back(&S, A);
735 if (!A)
736 S.GotIndex = NewIndex;
737 };
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000738 if (Sym.IsPreemptible) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000739 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000740 AddEntry(Sym, 0, GlobalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000741 Sym.IsInGlobalMipsGot = true;
742 } else if (Expr == R_MIPS_GOT_OFF32) {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000743 AddEntry(Sym, Addend, LocalEntries32);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000744 Sym.Is32BitMipsGot = true;
745 } else {
746 // Hold local GOT entries accessed via a 16-bit index separately.
747 // That allows to write them in the beginning of the GOT and keep
748 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000749 AddEntry(Sym, Addend, LocalEntries);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000750 }
751}
752
George Rimar14534eb2017-03-20 16:44:28 +0000753bool MipsGotSection::addDynTlsEntry(SymbolBody &Sym) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000754 if (Sym.GlobalDynIndex != -1U)
755 return false;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000756 Sym.GlobalDynIndex = TlsEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000757 // Global Dynamic TLS entries take two GOT slots.
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000758 TlsEntries.push_back(nullptr);
759 TlsEntries.push_back(&Sym);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000760 return true;
761}
762
763// Reserves TLS entries for a TLS module ID and a TLS block offset.
764// In total it takes two GOT slots.
George Rimar14534eb2017-03-20 16:44:28 +0000765bool MipsGotSection::addTlsIndex() {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000766 if (TlsIndexOff != uint32_t(-1))
767 return false;
George Rimar14534eb2017-03-20 16:44:28 +0000768 TlsIndexOff = TlsEntries.size() * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000769 TlsEntries.push_back(nullptr);
770 TlsEntries.push_back(nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000771 return true;
772}
773
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000774static uint64_t getMipsPageAddr(uint64_t Addr) {
775 return (Addr + 0x8000) & ~0xffff;
776}
777
778static uint64_t getMipsPageCount(uint64_t Size) {
779 return (Size + 0xfffe) / 0xffff + 1;
780}
781
George Rimar14534eb2017-03-20 16:44:28 +0000782uint64_t MipsGotSection::getPageEntryOffset(const SymbolBody &B,
783 int64_t Addend) const {
Rafael Espindola0dc25102017-05-31 19:26:37 +0000784 const OutputSection *OutSec = B.getOutputSection();
George Rimar14534eb2017-03-20 16:44:28 +0000785 uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
786 uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
787 uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000788 assert(Index < PageEntriesNum);
George Rimar14534eb2017-03-20 16:44:28 +0000789 return (HeaderEntriesNum + Index) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000790}
791
George Rimar14534eb2017-03-20 16:44:28 +0000792uint64_t MipsGotSection::getBodyEntryOffset(const SymbolBody &B,
793 int64_t Addend) const {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000794 // Calculate offset of the GOT entries block: TLS, global, local.
George Rimar14534eb2017-03-20 16:44:28 +0000795 uint64_t Index = HeaderEntriesNum + PageEntriesNum;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000796 if (B.isTls())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000797 Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000798 else if (B.IsInGlobalMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000799 Index += LocalEntries.size() + LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000800 else if (B.Is32BitMipsGot)
Simon Atanasyana0efc422016-11-29 10:23:50 +0000801 Index += LocalEntries.size();
802 // Calculate offset of the GOT entry in the block.
Eugene Leviantad4439e2016-11-11 11:33:32 +0000803 if (B.isInGot())
Simon Atanasyana0efc422016-11-29 10:23:50 +0000804 Index += B.GotIndex;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000805 else {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000806 auto It = EntryIndexMap.find({&B, Addend});
807 assert(It != EntryIndexMap.end());
Simon Atanasyana0efc422016-11-29 10:23:50 +0000808 Index += It->second;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000809 }
George Rimar14534eb2017-03-20 16:44:28 +0000810 return Index * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000811}
812
George Rimar14534eb2017-03-20 16:44:28 +0000813uint64_t MipsGotSection::getTlsOffset() const {
814 return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000815}
816
George Rimar14534eb2017-03-20 16:44:28 +0000817uint64_t MipsGotSection::getGlobalDynOffset(const SymbolBody &B) const {
818 return B.GlobalDynIndex * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000819}
820
George Rimar14534eb2017-03-20 16:44:28 +0000821const SymbolBody *MipsGotSection::getFirstGlobalEntry() const {
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000822 return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000823}
824
George Rimar14534eb2017-03-20 16:44:28 +0000825unsigned MipsGotSection::getLocalEntriesNum() const {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000826 return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
827 LocalEntries32.size();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000828}
829
George Rimar67c60722017-07-18 11:55:35 +0000830void MipsGotSection::finalizeContents() { updateAllocSize(); }
Peter Smith1ec42d92017-03-08 14:06:24 +0000831
George Rimar14534eb2017-03-20 16:44:28 +0000832void MipsGotSection::updateAllocSize() {
Simon Atanasyana0efc422016-11-29 10:23:50 +0000833 PageEntriesNum = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000834 for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000835 // For each output section referenced by GOT page relocations calculate
836 // and save into PageIndexMap an upper bound of MIPS GOT entries required
837 // to store page addresses of local symbols. We assume the worst case -
838 // each 64kb page of the output section has at least one GOT relocation
839 // against it. And take in account the case when the section intersects
840 // page boundaries.
841 P.second = PageEntriesNum;
842 PageEntriesNum += getMipsPageCount(P.first->Size);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000843 }
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000844 Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
George Rimar14534eb2017-03-20 16:44:28 +0000845 Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000846}
847
George Rimar14534eb2017-03-20 16:44:28 +0000848bool MipsGotSection::empty() const {
George Rimar11992c862016-11-25 08:05:41 +0000849 // We add the .got section to the result for dynamic MIPS target because
850 // its address and properties are mentioned in the .dynamic section.
851 return Config->Relocatable;
852}
853
George Rimar67c60722017-07-18 11:55:35 +0000854uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
Simon Atanasyan8469b882016-11-23 22:22:16 +0000855
George Rimar14534eb2017-03-20 16:44:28 +0000856void MipsGotSection::writeTo(uint8_t *Buf) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000857 // Set the MSB of the second GOT slot. This is not required by any
858 // MIPS ABI documentation, though.
859 //
860 // There is a comment in glibc saying that "The MSB of got[1] of a
861 // gnu object is set to identify gnu objects," and in GNU gold it
862 // says "the second entry will be used by some runtime loaders".
863 // But how this field is being used is unclear.
864 //
865 // We are not really willing to mimic other linkers behaviors
866 // without understanding why they do that, but because all files
867 // generated by GNU tools have this special GOT value, and because
868 // we've been doing this for years, it is probably a safe bet to
869 // keep doing this for now. We really need to revisit this to see
870 // if we had to do this.
George Rimar14534eb2017-03-20 16:44:28 +0000871 writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
872 Buf += HeaderEntriesNum * Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000873 // Write 'page address' entries to the local part of the GOT.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000874 for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000875 size_t PageCount = getMipsPageCount(L.first->Size);
George Rimar14534eb2017-03-20 16:44:28 +0000876 uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000877 for (size_t PI = 0; PI < PageCount; ++PI) {
George Rimar14534eb2017-03-20 16:44:28 +0000878 uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
879 writeUint(Entry, FirstPageAddr + PI * 0x10000);
Simon Atanasyan9fae3b82016-11-29 10:23:56 +0000880 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000881 }
George Rimar14534eb2017-03-20 16:44:28 +0000882 Buf += PageEntriesNum * Config->Wordsize;
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000883 auto AddEntry = [&](const GotEntry &SA) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000884 uint8_t *Entry = Buf;
George Rimar14534eb2017-03-20 16:44:28 +0000885 Buf += Config->Wordsize;
Eugene Leviantad4439e2016-11-11 11:33:32 +0000886 const SymbolBody *Body = SA.first;
George Rimar14534eb2017-03-20 16:44:28 +0000887 uint64_t VA = Body->getVA(SA.second);
888 writeUint(Entry, VA);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000889 };
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000890 std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
891 std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
892 std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000893 // Initialize TLS-related GOT entries. If the entry has a corresponding
894 // dynamic relocations, leave it initialized by zero. Write down adjusted
895 // TLS symbol's values otherwise. To calculate the adjustments use offsets
896 // for thread-local storage.
897 // https://www.linux-mips.org/wiki/NPTL
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000898 if (TlsIndexOff != -1U && !Config->Pic)
George Rimar14534eb2017-03-20 16:44:28 +0000899 writeUint(Buf + TlsIndexOff, 1);
Simon Atanasyanb8bfec62016-11-17 21:49:14 +0000900 for (const SymbolBody *B : TlsEntries) {
Rui Ueyamaca05b6f2017-10-12 19:10:41 +0000901 if (!B || B->IsPreemptible)
Eugene Leviantad4439e2016-11-11 11:33:32 +0000902 continue;
George Rimar14534eb2017-03-20 16:44:28 +0000903 uint64_t VA = B->getVA();
Eugene Leviantad4439e2016-11-11 11:33:32 +0000904 if (B->GotIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000905 uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
906 writeUint(Entry, VA - 0x7000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000907 }
908 if (B->GlobalDynIndex != -1U) {
George Rimar14534eb2017-03-20 16:44:28 +0000909 uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
910 writeUint(Entry, 1);
911 Entry += Config->Wordsize;
912 writeUint(Entry, VA - 0x8000);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000913 }
914 }
915}
916
George Rimar10f74fc2017-03-15 09:12:56 +0000917GotPltSection::GotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000918 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
919 Target->GotPltEntrySize, ".got.plt") {}
Eugene Leviant41ca3272016-11-10 09:48:29 +0000920
George Rimar10f74fc2017-03-15 09:12:56 +0000921void GotPltSection::addEntry(SymbolBody &Sym) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000922 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
923 Entries.push_back(&Sym);
924}
925
George Rimar10f74fc2017-03-15 09:12:56 +0000926size_t GotPltSection::getSize() const {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000927 return (Target->GotPltHeaderEntriesNum + Entries.size()) *
928 Target->GotPltEntrySize;
929}
930
George Rimar10f74fc2017-03-15 09:12:56 +0000931void GotPltSection::writeTo(uint8_t *Buf) {
Eugene Leviant41ca3272016-11-10 09:48:29 +0000932 Target->writeGotPltHeader(Buf);
933 Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
934 for (const SymbolBody *B : Entries) {
935 Target->writeGotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000936 Buf += Config->Wordsize;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000937 }
938}
939
Peter Smithbaffdb82016-12-08 12:58:55 +0000940// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
941// part of the .got.plt
George Rimar10f74fc2017-03-15 09:12:56 +0000942IgotPltSection::IgotPltSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +0000943 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
944 Target->GotPltEntrySize,
945 Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
Peter Smithbaffdb82016-12-08 12:58:55 +0000946
George Rimar10f74fc2017-03-15 09:12:56 +0000947void IgotPltSection::addEntry(SymbolBody &Sym) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000948 Sym.IsInIgot = true;
949 Sym.GotPltIndex = Entries.size();
950 Entries.push_back(&Sym);
951}
952
George Rimar10f74fc2017-03-15 09:12:56 +0000953size_t IgotPltSection::getSize() const {
Peter Smithbaffdb82016-12-08 12:58:55 +0000954 return Entries.size() * Target->GotPltEntrySize;
955}
956
George Rimar10f74fc2017-03-15 09:12:56 +0000957void IgotPltSection::writeTo(uint8_t *Buf) {
Peter Smithbaffdb82016-12-08 12:58:55 +0000958 for (const SymbolBody *B : Entries) {
Peter Smith4b360292016-12-09 09:59:54 +0000959 Target->writeIgotPlt(Buf, *B);
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000960 Buf += Config->Wordsize;
Peter Smithbaffdb82016-12-08 12:58:55 +0000961 }
962}
963
George Rimar49648002017-03-15 09:32:36 +0000964StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
965 : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
Rafael Espindola1b36eea2017-02-15 00:23:09 +0000966 Dynamic(Dynamic) {
967 // ELF string tables start with a NUL byte.
968 addString("");
969}
Eugene Leviant22eb0262016-11-14 09:16:00 +0000970
971// Adds a string to the string table. If HashIt is true we hash and check for
972// duplicates. It is optional because the name of global symbols are already
973// uniqued and hashing them again has a big cost for a small value: uniquing
974// them with some other string that happens to be the same.
George Rimar49648002017-03-15 09:32:36 +0000975unsigned StringTableSection::addString(StringRef S, bool HashIt) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000976 if (HashIt) {
977 auto R = StringMap.insert(std::make_pair(S, this->Size));
978 if (!R.second)
979 return R.first->second;
980 }
981 unsigned Ret = this->Size;
982 this->Size = this->Size + S.size() + 1;
983 Strings.push_back(S);
984 return Ret;
985}
986
George Rimar49648002017-03-15 09:32:36 +0000987void StringTableSection::writeTo(uint8_t *Buf) {
Eugene Leviant22eb0262016-11-14 09:16:00 +0000988 for (StringRef S : Strings) {
989 memcpy(Buf, S.data(), S.size());
James Hendersona5bc09a2017-08-04 09:07:55 +0000990 Buf[S.size()] = '\0';
Eugene Leviant22eb0262016-11-14 09:16:00 +0000991 Buf += S.size() + 1;
992 }
993}
994
Eugene Leviante9bab5d2016-11-21 16:59:33 +0000995// Returns the number of version definition entries. Because the first entry
996// is for the version definition itself, it is the number of versioned symbols
997// plus one. Note that we don't support multiple versions yet.
Eugene Leviant6380ce22016-11-15 12:26:55 +0000998static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
999
1000template <class ELFT>
1001DynamicSection<ELFT>::DynamicSection()
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001002 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001003 ".dynamic") {
Eugene Leviant6380ce22016-11-15 12:26:55 +00001004 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Rui Ueyama27876642017-03-01 04:04:23 +00001005
Petr Hosekffa786f2017-05-26 19:12:38 +00001006 // .dynamic section is not writable on MIPS and on Fuchsia OS
1007 // which passes -z rodynamic.
Eugene Leviant6380ce22016-11-15 12:26:55 +00001008 // See "Special Section" in Chapter 4 in the following document:
1009 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Petr Hosekffa786f2017-05-26 19:12:38 +00001010 if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
Eugene Leviant6380ce22016-11-15 12:26:55 +00001011 this->Flags = SHF_ALLOC;
1012
1013 addEntries();
1014}
1015
1016// There are some dynamic entries that don't depend on other sections.
1017// Such entries can be set early.
1018template <class ELFT> void DynamicSection<ELFT>::addEntries() {
1019 // Add strings to .dynstr early so that .dynstr's size will be
1020 // fixed early.
George Rimarf525c922017-07-17 09:43:18 +00001021 for (StringRef S : Config->FilterList)
1022 add({DT_FILTER, InX::DynStrTab->addString(S)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001023 for (StringRef S : Config->AuxiliaryList)
Rafael Espindola895aea62017-05-11 22:02:41 +00001024 add({DT_AUXILIARY, InX::DynStrTab->addString(S)});
Rui Ueyamabd278492017-04-29 23:06:43 +00001025 if (!Config->Rpath.empty())
Rui Ueyama729ac792016-11-17 04:10:09 +00001026 add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
Rafael Espindola895aea62017-05-11 22:02:41 +00001027 InX::DynStrTab->addString(Config->Rpath)});
George Rimar696a7f92017-09-19 09:20:54 +00001028 for (InputFile *File : SharedFiles) {
1029 SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
Eugene Leviant6380ce22016-11-15 12:26:55 +00001030 if (F->isNeeded())
Rafael Espindola895aea62017-05-11 22:02:41 +00001031 add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)});
George Rimar696a7f92017-09-19 09:20:54 +00001032 }
Eugene Leviant6380ce22016-11-15 12:26:55 +00001033 if (!Config->SoName.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00001034 add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001035
1036 // Set DT_FLAGS and DT_FLAGS_1.
1037 uint32_t DtFlags = 0;
1038 uint32_t DtFlags1 = 0;
1039 if (Config->Bsymbolic)
1040 DtFlags |= DF_SYMBOLIC;
1041 if (Config->ZNodelete)
1042 DtFlags1 |= DF_1_NODELETE;
Davide Italiano76907212017-03-23 00:54:16 +00001043 if (Config->ZNodlopen)
1044 DtFlags1 |= DF_1_NOOPEN;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001045 if (Config->ZNow) {
1046 DtFlags |= DF_BIND_NOW;
1047 DtFlags1 |= DF_1_NOW;
1048 }
1049 if (Config->ZOrigin) {
1050 DtFlags |= DF_ORIGIN;
1051 DtFlags1 |= DF_1_ORIGIN;
1052 }
1053
1054 if (DtFlags)
Rui Ueyama729ac792016-11-17 04:10:09 +00001055 add({DT_FLAGS, DtFlags});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001056 if (DtFlags1)
Rui Ueyama729ac792016-11-17 04:10:09 +00001057 add({DT_FLAGS_1, DtFlags1});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001058
Petr Hosekffa786f2017-05-26 19:12:38 +00001059 // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1060 // need it for each process, so we don't write it for DSOs. The loader writes
1061 // the pointer into this entry.
1062 //
1063 // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1064 // systems (currently only Fuchsia OS) provide other means to give the
1065 // debugger this information. Such systems may choose make .dynamic read-only.
1066 // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1067 if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic)
George Rimarb4081bb2017-05-12 08:04:58 +00001068 add({DT_DEBUG, (uint64_t)0});
1069}
1070
1071// Add remaining entries to complete .dynamic contents.
1072template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1073 if (this->Size)
1074 return; // Already finalized.
1075
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001076 this->Link = InX::DynStrTab->getParent()->SectionIndex;
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001077 if (In<ELFT>::RelaDyn->getParent() && !In<ELFT>::RelaDyn->empty()) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001078 bool IsRela = Config->IsRela;
Rui Ueyama729ac792016-11-17 04:10:09 +00001079 add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001080 add({IsRela ? DT_RELASZ : DT_RELSZ, In<ELFT>::RelaDyn->getParent(),
1081 Entry::SecSize});
Rui Ueyama729ac792016-11-17 04:10:09 +00001082 add({IsRela ? DT_RELAENT : DT_RELENT,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001083 uint64_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001084
1085 // MIPS dynamic loader does not support RELCOUNT tag.
1086 // The problem is in the tight relation between dynamic
1087 // relocations and GOT. So do not emit this tag on MIPS.
1088 if (Config->EMachine != EM_MIPS) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001089 size_t NumRelativeRels = In<ELFT>::RelaDyn->getRelativeRelocCount();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001090 if (Config->ZCombreloc && NumRelativeRels)
Rui Ueyama729ac792016-11-17 04:10:09 +00001091 add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001092 }
1093 }
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001094 if (In<ELFT>::RelaPlt->getParent() && !In<ELFT>::RelaPlt->empty()) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001095 add({DT_JMPREL, In<ELFT>::RelaPlt});
Rafael Espindola4cc0cd62017-07-05 23:06:59 +00001096 add({DT_PLTRELSZ, In<ELFT>::RelaPlt->getParent(), Entry::SecSize});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001097 switch (Config->EMachine) {
1098 case EM_MIPS:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001099 add({DT_MIPS_PLTGOT, InX::GotPlt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001100 break;
1101 case EM_SPARCV9:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001102 add({DT_PLTGOT, InX::Plt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001103 break;
1104 default:
Rui Ueyamaed55e6c2017-10-26 23:54:00 +00001105 add({DT_PLTGOT, InX::GotPlt});
Rui Ueyama0cc14832017-06-28 17:05:39 +00001106 break;
1107 }
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001108 add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001109 }
1110
George Rimar69b17c32017-05-16 10:04:42 +00001111 add({DT_SYMTAB, InX::DynSymTab});
Rui Ueyama729ac792016-11-17 04:10:09 +00001112 add({DT_SYMENT, sizeof(Elf_Sym)});
Rafael Espindola895aea62017-05-11 22:02:41 +00001113 add({DT_STRTAB, InX::DynStrTab});
1114 add({DT_STRSZ, InX::DynStrTab->getSize()});
George Rimar0a7412f2017-03-09 08:48:34 +00001115 if (!Config->ZText)
1116 add({DT_TEXTREL, (uint64_t)0});
George Rimar69b17c32017-05-16 10:04:42 +00001117 if (InX::GnuHashTab)
1118 add({DT_GNU_HASH, InX::GnuHashTab});
George Rimaraaf54712017-09-27 09:14:59 +00001119 if (InX::HashTab)
1120 add({DT_HASH, InX::HashTab});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001121
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001122 if (Out::PreinitArray) {
1123 add({DT_PREINIT_ARRAY, Out::PreinitArray});
1124 add({DT_PREINIT_ARRAYSZ, Out::PreinitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001125 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001126 if (Out::InitArray) {
1127 add({DT_INIT_ARRAY, Out::InitArray});
1128 add({DT_INIT_ARRAYSZ, Out::InitArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001129 }
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001130 if (Out::FiniArray) {
1131 add({DT_FINI_ARRAY, Out::FiniArray});
1132 add({DT_FINI_ARRAYSZ, Out::FiniArray, Entry::SecSize});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001133 }
1134
Rui Ueyama43099e42017-08-15 16:03:11 +00001135 if (SymbolBody *B = Symtab->find(Config->Init))
1136 if (B->isInCurrentDSO())
1137 add({DT_INIT, B});
1138 if (SymbolBody *B = Symtab->find(Config->Fini))
1139 if (B->isInCurrentDSO())
1140 add({DT_FINI, B});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001141
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001142 bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1143 if (HasVerNeed || In<ELFT>::VerDef)
1144 add({DT_VERSYM, In<ELFT>::VerSym});
1145 if (In<ELFT>::VerDef) {
1146 add({DT_VERDEF, In<ELFT>::VerDef});
Rui Ueyama729ac792016-11-17 04:10:09 +00001147 add({DT_VERDEFNUM, getVerDefNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001148 }
1149 if (HasVerNeed) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001150 add({DT_VERNEED, In<ELFT>::VerNeed});
1151 add({DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum()});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001152 }
1153
1154 if (Config->EMachine == EM_MIPS) {
Rui Ueyama729ac792016-11-17 04:10:09 +00001155 add({DT_MIPS_RLD_VERSION, 1});
1156 add({DT_MIPS_FLAGS, RHF_NOTPOT});
James Hendersonb5ca92e2017-10-10 10:09:35 +00001157 add({DT_MIPS_BASE_ADDRESS, Target->getImageBase()});
George Rimar69b17c32017-05-16 10:04:42 +00001158 add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001159 add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()});
1160 if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry())
Rui Ueyama729ac792016-11-17 04:10:09 +00001161 add({DT_MIPS_GOTSYM, B->DynsymIndex});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001162 else
George Rimar69b17c32017-05-16 10:04:42 +00001163 add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()});
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001164 add({DT_PLTGOT, InX::MipsGot});
Rafael Espindola895aea62017-05-11 22:02:41 +00001165 if (InX::MipsRldMap)
1166 add({DT_MIPS_RLD_MAP, InX::MipsRldMap});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001167 }
1168
George Rimar8f3a6c82017-10-06 10:06:13 +00001169 add({DT_NULL, (uint64_t)0});
Eugene Leviant6380ce22016-11-15 12:26:55 +00001170
George Rimar8f3a6c82017-10-06 10:06:13 +00001171 getParent()->Link = this->Link;
1172 this->Size = Entries.size() * this->Entsize;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001173}
1174
1175template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1176 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1177
1178 for (const Entry &E : Entries) {
1179 P->d_tag = E.Tag;
1180 switch (E.Kind) {
1181 case Entry::SecAddr:
1182 P->d_un.d_ptr = E.OutSec->Addr;
1183 break;
1184 case Entry::InSecAddr:
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001185 P->d_un.d_ptr = E.InSec->getParent()->Addr + E.InSec->OutSecOff;
Eugene Leviant6380ce22016-11-15 12:26:55 +00001186 break;
1187 case Entry::SecSize:
1188 P->d_un.d_val = E.OutSec->Size;
1189 break;
1190 case Entry::SymAddr:
George Rimarf64618a2017-03-17 11:56:54 +00001191 P->d_un.d_ptr = E.Sym->getVA();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001192 break;
1193 case Entry::PlainInt:
1194 P->d_un.d_val = E.Val;
1195 break;
1196 }
1197 ++P;
1198 }
1199}
1200
George Rimar97def8c2017-03-17 12:07:44 +00001201uint64_t DynamicReloc::getOffset() const {
Rafael Espindola180de972017-05-31 00:23:23 +00001202 return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
Eugene Levianta96d9022016-11-16 10:02:27 +00001203}
1204
George Rimar97def8c2017-03-17 12:07:44 +00001205int64_t DynamicReloc::getAddend() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001206 if (UseSymVA)
George Rimarf64618a2017-03-17 11:56:54 +00001207 return Sym->getVA(Addend);
Eugene Levianta96d9022016-11-16 10:02:27 +00001208 return Addend;
1209}
1210
George Rimar97def8c2017-03-17 12:07:44 +00001211uint32_t DynamicReloc::getSymIndex() const {
Eugene Levianta96d9022016-11-16 10:02:27 +00001212 if (Sym && !UseSymVA)
1213 return Sym->DynsymIndex;
1214 return 0;
1215}
1216
1217template <class ELFT>
1218RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001219 : SyntheticSection(SHF_ALLOC, Config->IsRela ? SHT_RELA : SHT_REL,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001220 Config->Wordsize, Name),
Eugene Levianta96d9022016-11-16 10:02:27 +00001221 Sort(Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001222 this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001223}
1224
1225template <class ELFT>
George Rimar97def8c2017-03-17 12:07:44 +00001226void RelocationSection<ELFT>::addReloc(const DynamicReloc &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001227 if (Reloc.Type == Target->RelativeRel)
1228 ++NumRelativeRelocs;
1229 Relocs.push_back(Reloc);
1230}
1231
1232template <class ELFT, class RelTy>
1233static bool compRelocations(const RelTy &A, const RelTy &B) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001234 bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1235 bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
Eugene Levianta96d9022016-11-16 10:02:27 +00001236 if (AIsRel != BIsRel)
1237 return AIsRel;
1238
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001239 return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001240}
1241
1242template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1243 uint8_t *BufBegin = Buf;
George Rimar97def8c2017-03-17 12:07:44 +00001244 for (const DynamicReloc &Rel : Relocs) {
Eugene Levianta96d9022016-11-16 10:02:27 +00001245 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001246 Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Eugene Levianta96d9022016-11-16 10:02:27 +00001247
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001248 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001249 P->r_addend = Rel.getAddend();
1250 P->r_offset = Rel.getOffset();
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001251 if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
Eugene Levianta96d9022016-11-16 10:02:27 +00001252 // Dynamic relocation against MIPS GOT section make deal TLS entries
1253 // allocated in the end of the GOT. We need to adjust the offset to take
1254 // in account 'local' and 'global' GOT entries.
Rafael Espindolab3aa2c92017-05-11 21:33:30 +00001255 P->r_offset += InX::MipsGot->getTlsOffset();
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001256 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
Eugene Levianta96d9022016-11-16 10:02:27 +00001257 }
1258
1259 if (Sort) {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001260 if (Config->IsRela)
Eugene Levianta96d9022016-11-16 10:02:27 +00001261 std::stable_sort((Elf_Rela *)BufBegin,
1262 (Elf_Rela *)BufBegin + Relocs.size(),
1263 compRelocations<ELFT, Elf_Rela>);
1264 else
1265 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1266 compRelocations<ELFT, Elf_Rel>);
1267 }
1268}
1269
1270template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1271 return this->Entsize * Relocs.size();
1272}
1273
Rui Ueyama945055a2017-02-27 03:07:41 +00001274template <class ELFT> void RelocationSection<ELFT>::finalizeContents() {
Rafael Espindola49419bb2017-10-12 15:05:04 +00001275 // If all relocations are *RELATIVE they don't refer to any
1276 // dynamic symbol and we don't need a dynamic symbol table. If that
1277 // is the case, just use 0 as the link.
1278 this->Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0;
Eugene Levianta96d9022016-11-16 10:02:27 +00001279
1280 // Set required output section properties.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001281 getParent()->Link = this->Link;
Eugene Levianta96d9022016-11-16 10:02:27 +00001282}
1283
George Rimarf45f6812017-05-16 08:53:30 +00001284SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001285 : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001286 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001287 Config->Wordsize,
Rui Ueyama9320cb02017-02-27 02:56:02 +00001288 StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
George Rimarf45f6812017-05-16 08:53:30 +00001289 StrTabSec(StrTabSec) {}
Eugene Leviant9230db92016-11-17 09:16:34 +00001290
1291// Orders symbols according to their positions in the GOT,
1292// in compliance with MIPS ABI rules.
1293// See "Global Offset Table" in Chapter 5 in the following document
1294// for detailed description:
1295// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan8c753112017-03-19 19:32:51 +00001296static bool sortMipsSymbols(const SymbolTableEntry &L,
1297 const SymbolTableEntry &R) {
Eugene Leviant9230db92016-11-17 09:16:34 +00001298 // Sort entries related to non-local preemptible symbols by GOT indexes.
1299 // All other entries go to the first part of GOT in arbitrary order.
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001300 bool LIsInLocalGot = !L.Symbol->IsInGlobalMipsGot;
1301 bool RIsInLocalGot = !R.Symbol->IsInGlobalMipsGot;
Eugene Leviant9230db92016-11-17 09:16:34 +00001302 if (LIsInLocalGot || RIsInLocalGot)
1303 return !RIsInLocalGot;
Rui Ueyamaaa5c5272017-02-27 03:31:38 +00001304 return L.Symbol->GotIndex < R.Symbol->GotIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001305}
1306
George Rimarf45f6812017-05-16 08:53:30 +00001307void SymbolTableBaseSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001308 getParent()->Link = StrTabSec.getParent()->SectionIndex;
Eugene Leviant9230db92016-11-17 09:16:34 +00001309
Rui Ueyama6e967342017-02-28 03:29:12 +00001310 // If it is a .dynsym, there should be no local symbols, but we need
1311 // to do a few things for the dynamic linker.
1312 if (this->Type == SHT_DYNSYM) {
1313 // Section's Info field has the index of the first non-local symbol.
1314 // Because the first symbol entry is a null entry, 1 is the first.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001315 getParent()->Info = 1;
Rui Ueyama6e967342017-02-28 03:29:12 +00001316
George Rimarf45f6812017-05-16 08:53:30 +00001317 if (InX::GnuHashTab) {
Rui Ueyama6e967342017-02-28 03:29:12 +00001318 // NB: It also sorts Symbols to meet the GNU hash table requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001319 InX::GnuHashTab->addSymbols(Symbols);
Rui Ueyama6e967342017-02-28 03:29:12 +00001320 } else if (Config->EMachine == EM_MIPS) {
1321 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1322 }
1323
1324 size_t I = 0;
1325 for (const SymbolTableEntry &S : Symbols)
1326 S.Symbol->DynsymIndex = ++I;
Rui Ueyama406331e2017-02-28 04:11:01 +00001327 return;
Peter Smith55865432017-02-20 11:12:33 +00001328 }
Peter Smith1ec42d92017-03-08 14:06:24 +00001329}
Peter Smith55865432017-02-20 11:12:33 +00001330
George Rimar0d6f30e2017-10-18 13:06:18 +00001331// The ELF spec requires that all local symbols precede global symbols, so we
1332// sort symbol entries in this function. (For .dynsym, we don't do that because
1333// symbols for dynamic linking are inherently all globals.)
George Rimarf45f6812017-05-16 08:53:30 +00001334void SymbolTableBaseSection::postThunkContents() {
Peter Smith1ec42d92017-03-08 14:06:24 +00001335 if (this->Type == SHT_DYNSYM)
1336 return;
1337 // move all local symbols before global symbols.
Rui Ueyama6e967342017-02-28 03:29:12 +00001338 auto It = std::stable_partition(
1339 Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1340 return S.Symbol->isLocal() ||
1341 S.Symbol->symbol()->computeBinding() == STB_LOCAL;
1342 });
1343 size_t NumLocals = It - Symbols.begin();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001344 getParent()->Info = NumLocals + 1;
Eugene Leviant9230db92016-11-17 09:16:34 +00001345}
1346
George Rimarf45f6812017-05-16 08:53:30 +00001347void SymbolTableBaseSection::addSymbol(SymbolBody *B) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001348 // Adding a local symbol to a .dynsym is a bug.
1349 assert(this->Type != SHT_DYNSYM || !B->isLocal());
Eugene Leviant9230db92016-11-17 09:16:34 +00001350
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001351 bool HashIt = B->isLocal();
1352 Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
George Rimar190bac52017-01-23 14:07:23 +00001353}
1354
George Rimarf45f6812017-05-16 08:53:30 +00001355size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) {
George Rimar5d6efd12017-09-27 09:08:53 +00001356 // Initializes symbol lookup tables lazily. This is used only
1357 // for -r or -emit-relocs.
1358 llvm::call_once(OnceFlag, [&] {
1359 SymbolIndexMap.reserve(Symbols.size());
1360 size_t I = 0;
1361 for (const SymbolTableEntry &E : Symbols) {
1362 if (E.Symbol->Type == STT_SECTION)
1363 SectionIndexMap[E.Symbol->getOutputSection()] = ++I;
1364 else
1365 SymbolIndexMap[E.Symbol] = ++I;
1366 }
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001367 });
George Rimar5d6efd12017-09-27 09:08:53 +00001368
1369 // Section symbols are mapped based on their output sections
1370 // to maintain their semantics.
1371 if (Body->Type == STT_SECTION)
1372 return SectionIndexMap.lookup(Body->getOutputSection());
1373 return SymbolIndexMap.lookup(Body);
George Rimar190bac52017-01-23 14:07:23 +00001374}
1375
George Rimarf45f6812017-05-16 08:53:30 +00001376template <class ELFT>
1377SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1378 : SymbolTableBaseSection(StrTabSec) {
1379 this->Entsize = sizeof(Elf_Sym);
1380}
1381
Rui Ueyama1f032532017-02-28 01:56:36 +00001382// Write the internal symbol table contents to the output symbol table.
Eugene Leviant9230db92016-11-17 09:16:34 +00001383template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1f032532017-02-28 01:56:36 +00001384 // The first entry is a null entry as per the ELF spec.
George Rimar2727ce22017-10-06 09:56:24 +00001385 memset(Buf, 0, sizeof(Elf_Sym));
Eugene Leviant9230db92016-11-17 09:16:34 +00001386 Buf += sizeof(Elf_Sym);
1387
Eugene Leviant9230db92016-11-17 09:16:34 +00001388 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
George Rimar190bac52017-01-23 14:07:23 +00001389
Rui Ueyama1f032532017-02-28 01:56:36 +00001390 for (SymbolTableEntry &Ent : Symbols) {
1391 SymbolBody *Body = Ent.Symbol;
Eugene Leviant9230db92016-11-17 09:16:34 +00001392
Rui Ueyama1b003182017-02-28 19:22:09 +00001393 // Set st_info and st_other.
George Rimar2727ce22017-10-06 09:56:24 +00001394 ESym->st_other = 0;
Rui Ueyama1f032532017-02-28 01:56:36 +00001395 if (Body->isLocal()) {
1396 ESym->setBindingAndType(STB_LOCAL, Body->Type);
1397 } else {
1398 ESym->setBindingAndType(Body->symbol()->computeBinding(), Body->Type);
1399 ESym->setVisibility(Body->symbol()->Visibility);
1400 }
1401
1402 ESym->st_name = Ent.StrTabOffset;
Eugene Leviant9230db92016-11-17 09:16:34 +00001403
Rui Ueyama1b003182017-02-28 19:22:09 +00001404 // Set a section index.
George Rimar69268a82017-03-16 11:06:13 +00001405 if (const OutputSection *OutSec = Body->getOutputSection())
Eugene Leviant9230db92016-11-17 09:16:34 +00001406 ESym->st_shndx = OutSec->SectionIndex;
Rui Ueyama80474a22017-02-28 19:29:55 +00001407 else if (isa<DefinedRegular>(Body))
Eugene Leviant9230db92016-11-17 09:16:34 +00001408 ESym->st_shndx = SHN_ABS;
Rui Ueyama1b003182017-02-28 19:22:09 +00001409 else if (isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001410 ESym->st_shndx = SHN_COMMON;
George Rimar2727ce22017-10-06 09:56:24 +00001411 else
1412 ESym->st_shndx = SHN_UNDEF;
Rui Ueyama1b003182017-02-28 19:22:09 +00001413
George Rimardbe843d2017-06-28 09:51:33 +00001414 // Copy symbol size if it is a defined symbol. st_size is not significant
1415 // for undefined symbols, so whether copying it or not is up to us if that's
1416 // the case. We'll leave it as zero because by not setting a value, we can
1417 // get the exact same outputs for two sets of input files that differ only
1418 // in undefined symbol size in DSOs.
George Rimar2727ce22017-10-06 09:56:24 +00001419 if (ESym->st_shndx == SHN_UNDEF)
1420 ESym->st_size = 0;
1421 else
George Rimardbe843d2017-06-28 09:51:33 +00001422 ESym->st_size = Body->getSize<ELFT>();
1423
Rui Ueyama1b003182017-02-28 19:22:09 +00001424 // st_value is usually an address of a symbol, but that has a
1425 // special meaining for uninstantiated common symbols (this can
1426 // occur if -r is given).
1427 if (!Config->DefineCommon && isa<DefinedCommon>(Body))
Rui Ueyamab2a23cf2017-01-24 03:41:20 +00001428 ESym->st_value = cast<DefinedCommon>(Body)->Alignment;
Rui Ueyama1b003182017-02-28 19:22:09 +00001429 else
George Rimarf64618a2017-03-17 11:56:54 +00001430 ESym->st_value = Body->getVA();
Rui Ueyama1b003182017-02-28 19:22:09 +00001431
Rui Ueyama1f032532017-02-28 01:56:36 +00001432 ++ESym;
1433 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001434
Rui Ueyama1f032532017-02-28 01:56:36 +00001435 // On MIPS we need to mark symbol which has a PLT entry and requires
1436 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1437 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1438 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1439 if (Config->EMachine == EM_MIPS) {
1440 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1441
1442 for (SymbolTableEntry &Ent : Symbols) {
1443 SymbolBody *Body = Ent.Symbol;
Rui Ueyama924b3612017-02-16 06:12:22 +00001444 if (Body->isInPlt() && Body->NeedsPltAddr)
Eugene Leviant9230db92016-11-17 09:16:34 +00001445 ESym->st_other |= STO_MIPS_PLT;
Rui Ueyama1f032532017-02-28 01:56:36 +00001446
1447 if (Config->Relocatable)
Rui Ueyama80474a22017-02-28 19:29:55 +00001448 if (auto *D = dyn_cast<DefinedRegular>(Body))
1449 if (D->isMipsPIC<ELFT>())
Rui Ueyama1f032532017-02-28 01:56:36 +00001450 ESym->st_other |= STO_MIPS_PIC;
1451 ++ESym;
Eugene Leviant9230db92016-11-17 09:16:34 +00001452 }
Eugene Leviant9230db92016-11-17 09:16:34 +00001453 }
1454}
1455
Rui Ueyamae4120632017-02-28 22:05:13 +00001456// .hash and .gnu.hash sections contain on-disk hash tables that map
1457// symbol names to their dynamic symbol table indices. Their purpose
1458// is to help the dynamic linker resolve symbols quickly. If ELF files
1459// don't have them, the dynamic linker has to do linear search on all
1460// dynamic symbols, which makes programs slower. Therefore, a .hash
1461// section is added to a DSO by default. A .gnu.hash is added if you
1462// give the -hash-style=gnu or -hash-style=both option.
1463//
1464// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1465// Each ELF file has a list of DSOs that the ELF file depends on and a
1466// list of dynamic symbols that need to be resolved from any of the
1467// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1468// where m is the number of DSOs and n is the number of dynamic
1469// symbols. For modern large programs, both m and n are large. So
1470// making each step faster by using hash tables substiantially
1471// improves time to load programs.
1472//
1473// (Note that this is not the only way to design the shared library.
1474// For instance, the Windows DLL takes a different approach. On
1475// Windows, each dynamic symbol has a name of DLL from which the symbol
1476// has to be resolved. That makes the cost of symbol resolution O(n).
1477// This disables some hacky techniques you can use on Unix such as
1478// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1479//
1480// Due to historical reasons, we have two different hash tables, .hash
1481// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1482// and better version of .hash. .hash is just an on-disk hash table, but
1483// .gnu.hash has a bloom filter in addition to a hash table to skip
1484// DSOs very quickly. If you are sure that your dynamic linker knows
1485// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1486// safe bet is to specify -hash-style=both for backward compatibilty.
George Rimarf45f6812017-05-16 08:53:30 +00001487GnuHashTableSection::GnuHashTableSection()
George Rimar5f73bc92017-03-29 15:23:28 +00001488 : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1489}
Eugene Leviantbe809a72016-11-18 06:44:18 +00001490
George Rimarf45f6812017-05-16 08:53:30 +00001491void GnuHashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001492 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001493
1494 // Computes bloom filter size in word size. We want to allocate 8
1495 // bits for each symbol. It must be a power of two.
1496 if (Symbols.empty())
1497 MaskWords = 1;
1498 else
George Rimar5f73bc92017-03-29 15:23:28 +00001499 MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001500
George Rimar5f73bc92017-03-29 15:23:28 +00001501 Size = 16; // Header
1502 Size += Config->Wordsize * MaskWords; // Bloom filter
1503 Size += NBuckets * 4; // Hash buckets
1504 Size += Symbols.size() * 4; // Hash values
Eugene Leviantbe809a72016-11-18 06:44:18 +00001505}
1506
George Rimarf45f6812017-05-16 08:53:30 +00001507void GnuHashTableSection::writeTo(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001508 // Write a header.
George Rimar5f73bc92017-03-29 15:23:28 +00001509 write32(Buf, NBuckets, Config->Endianness);
George Rimarf45f6812017-05-16 08:53:30 +00001510 write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(),
George Rimar5f73bc92017-03-29 15:23:28 +00001511 Config->Endianness);
1512 write32(Buf + 8, MaskWords, Config->Endianness);
1513 write32(Buf + 12, getShift2(), Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001514 Buf += 16;
1515
Rui Ueyama7986b452017-03-01 18:09:09 +00001516 // Write a bloom filter and a hash table.
Rui Ueyamae13373b2017-03-01 02:51:42 +00001517 writeBloomFilter(Buf);
George Rimar5f73bc92017-03-29 15:23:28 +00001518 Buf += Config->Wordsize * MaskWords;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001519 writeHashTable(Buf);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001520}
1521
Rui Ueyama7986b452017-03-01 18:09:09 +00001522// This function writes a 2-bit bloom filter. This bloom filter alone
1523// usually filters out 80% or more of all symbol lookups [1].
1524// The dynamic linker uses the hash table only when a symbol is not
1525// filtered out by a bloom filter.
1526//
1527// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1528// p.9, https://www.akkadia.org/drepper/dsohowto.pdf
George Rimarf45f6812017-05-16 08:53:30 +00001529void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
George Rimar5f73bc92017-03-29 15:23:28 +00001530 const unsigned C = Config->Wordsize * 8;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001531 for (const Entry &Sym : Symbols) {
1532 size_t I = (Sym.Hash / C) & (MaskWords - 1);
George Rimar5f73bc92017-03-29 15:23:28 +00001533 uint64_t Val = readUint(Buf + I * Config->Wordsize);
1534 Val |= uint64_t(1) << (Sym.Hash % C);
1535 Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1536 writeUint(Buf + I * Config->Wordsize, Val);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001537 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001538}
1539
George Rimarf45f6812017-05-16 08:53:30 +00001540void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001541 // Group symbols by hash value.
1542 std::vector<std::vector<Entry>> Syms(NBuckets);
1543 for (const Entry &Ent : Symbols)
1544 Syms[Ent.Hash % NBuckets].push_back(Ent);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001545
Rui Ueyamae13373b2017-03-01 02:51:42 +00001546 // Write hash buckets. Hash buckets contain indices in the following
1547 // hash value table.
George Rimar5f73bc92017-03-29 15:23:28 +00001548 uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001549 for (size_t I = 0; I < NBuckets; ++I)
1550 if (!Syms[I].empty())
George Rimar5f73bc92017-03-29 15:23:28 +00001551 write32(Buckets + I, Syms[I][0].Body->DynsymIndex, Config->Endianness);
Rui Ueyamae13373b2017-03-01 02:51:42 +00001552
1553 // Write a hash value table. It represents a sequence of chains that
1554 // share the same hash modulo value. The last element of each chain
1555 // is terminated by LSB 1.
George Rimar5f73bc92017-03-29 15:23:28 +00001556 uint32_t *Values = Buckets + NBuckets;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001557 size_t I = 0;
1558 for (std::vector<Entry> &Vec : Syms) {
1559 if (Vec.empty())
1560 continue;
1561 for (const Entry &Ent : makeArrayRef(Vec).drop_back())
George Rimar5f73bc92017-03-29 15:23:28 +00001562 write32(Values + I++, Ent.Hash & ~1, Config->Endianness);
1563 write32(Values + I++, Vec.back().Hash | 1, Config->Endianness);
Eugene Leviantbe809a72016-11-18 06:44:18 +00001564 }
Eugene Leviantbe809a72016-11-18 06:44:18 +00001565}
1566
1567static uint32_t hashGnu(StringRef Name) {
1568 uint32_t H = 5381;
1569 for (uint8_t C : Name)
1570 H = (H << 5) + H + C;
1571 return H;
1572}
1573
Rui Ueyamae13373b2017-03-01 02:51:42 +00001574// Returns a number of hash buckets to accomodate given number of elements.
1575// We want to choose a moderate number that is not too small (which
1576// causes too many hash collisions) and not too large (which wastes
1577// disk space.)
1578//
1579// We return a prime number because it (is believed to) achieve good
1580// hash distribution.
1581static size_t getBucketSize(size_t NumSymbols) {
1582 // List of largest prime numbers that are not greater than 2^n + 1.
1583 for (size_t N : {131071, 65521, 32749, 16381, 8191, 4093, 2039, 1021, 509,
1584 251, 127, 61, 31, 13, 7, 3, 1})
1585 if (N <= NumSymbols)
1586 return N;
1587 return 0;
1588}
1589
Eugene Leviantbe809a72016-11-18 06:44:18 +00001590// Add symbols to this symbol hash table. Note that this function
1591// destructively sort a given vector -- which is needed because
1592// GNU-style hash table places some sorting requirements.
George Rimarf45f6812017-05-16 08:53:30 +00001593void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
Rui Ueyamae13373b2017-03-01 02:51:42 +00001594 // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1595 // its type correctly.
Eugene Leviantbe809a72016-11-18 06:44:18 +00001596 std::vector<SymbolTableEntry>::iterator Mid =
1597 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
Rafael Espindola06ea0ce2017-10-18 06:49:59 +00001598 // Shared symbols that this executable preempts are special. The dynamic
1599 // linker has to look them up, so they have to be in the hash table.
1600 if (auto *SS = dyn_cast<SharedSymbol>(S.Symbol))
1601 return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr;
1602 return !S.Symbol->isInCurrentDSO();
Eugene Leviantbe809a72016-11-18 06:44:18 +00001603 });
1604 if (Mid == V.end())
1605 return;
Rui Ueyamae13373b2017-03-01 02:51:42 +00001606
1607 for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1608 SymbolBody *B = Ent.Symbol;
1609 Symbols.push_back({B, Ent.StrTabOffset, hashGnu(B->getName())});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001610 }
1611
Rui Ueyamae13373b2017-03-01 02:51:42 +00001612 NBuckets = getBucketSize(Symbols.size());
Eugene Leviantbe809a72016-11-18 06:44:18 +00001613 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyamae13373b2017-03-01 02:51:42 +00001614 [&](const Entry &L, const Entry &R) {
Eugene Leviantbe809a72016-11-18 06:44:18 +00001615 return L.Hash % NBuckets < R.Hash % NBuckets;
1616 });
1617
1618 V.erase(Mid, V.end());
Rui Ueyamae13373b2017-03-01 02:51:42 +00001619 for (const Entry &Ent : Symbols)
1620 V.push_back({Ent.Body, Ent.StrTabOffset});
Eugene Leviantbe809a72016-11-18 06:44:18 +00001621}
1622
George Rimaraaf54712017-09-27 09:14:59 +00001623HashTableSection::HashTableSection()
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001624 : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1625 this->Entsize = 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001626}
1627
George Rimaraaf54712017-09-27 09:14:59 +00001628void HashTableSection::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001629 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001630
George Rimar67c60722017-07-18 11:55:35 +00001631 unsigned NumEntries = 2; // nbucket and nchain.
George Rimar69b17c32017-05-16 10:04:42 +00001632 NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
Eugene Leviantb96e8092016-11-18 09:06:47 +00001633
1634 // Create as many buckets as there are symbols.
George Rimar69b17c32017-05-16 10:04:42 +00001635 NumEntries += InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001636 this->Size = NumEntries * 4;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001637}
1638
George Rimaraaf54712017-09-27 09:14:59 +00001639void HashTableSection::writeTo(uint8_t *Buf) {
George Rimar69b17c32017-05-16 10:04:42 +00001640 unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
Rui Ueyama6b776ad2017-02-28 05:53:47 +00001641
George Rimaraaf54712017-09-27 09:14:59 +00001642 uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
1643 write32(P++, NumSymbols, Config->Endianness); // nbucket
1644 write32(P++, NumSymbols, Config->Endianness); // nchain
Eugene Leviantb96e8092016-11-18 09:06:47 +00001645
George Rimaraaf54712017-09-27 09:14:59 +00001646 uint32_t *Buckets = P;
1647 uint32_t *Chains = P + NumSymbols;
Eugene Leviantb96e8092016-11-18 09:06:47 +00001648
George Rimar69b17c32017-05-16 10:04:42 +00001649 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviantb96e8092016-11-18 09:06:47 +00001650 SymbolBody *Body = S.Symbol;
1651 StringRef Name = Body->getName();
1652 unsigned I = Body->DynsymIndex;
1653 uint32_t Hash = hashSysV(Name) % NumSymbols;
1654 Chains[I] = Buckets[Hash];
George Rimaraaf54712017-09-27 09:14:59 +00001655 write32(Buckets + Hash, I, Config->Endianness);
Eugene Leviantb96e8092016-11-18 09:06:47 +00001656 }
1657}
1658
George Rimardfc020e2017-03-17 11:01:57 +00001659PltSection::PltSection(size_t S)
Rui Ueyama9320cb02017-02-27 02:56:02 +00001660 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
Rui Ueyama0cc14832017-06-28 17:05:39 +00001661 HeaderSize(S) {
1662 // The PLT needs to be writable on SPARC as the dynamic linker will
1663 // modify the instructions in the PLT entries.
1664 if (Config->EMachine == EM_SPARCV9)
1665 this->Flags |= SHF_WRITE;
1666}
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001667
George Rimardfc020e2017-03-17 11:01:57 +00001668void PltSection::writeTo(uint8_t *Buf) {
Peter Smithf09245a2017-02-09 10:56:15 +00001669 // At beginning of PLT but not the IPLT, we have code to call the dynamic
1670 // linker to resolve dynsyms at runtime. Write such code.
1671 if (HeaderSize != 0)
1672 Target->writePltHeader(Buf);
1673 size_t Off = HeaderSize;
1674 // The IPlt is immediately after the Plt, account for this in RelOff
1675 unsigned PltOff = getPltRelocOff();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001676
1677 for (auto &I : Entries) {
1678 const SymbolBody *B = I.first;
Peter Smithf09245a2017-02-09 10:56:15 +00001679 unsigned RelOff = I.second + PltOff;
George Rimar4670bb02017-03-16 12:58:11 +00001680 uint64_t Got = B->getGotPltVA();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001681 uint64_t Plt = this->getVA() + Off;
1682 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1683 Off += Target->PltEntrySize;
1684 }
1685}
1686
George Rimardfc020e2017-03-17 11:01:57 +00001687template <class ELFT> void PltSection::addEntry(SymbolBody &Sym) {
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001688 Sym.PltIndex = Entries.size();
Peter Smithf09245a2017-02-09 10:56:15 +00001689 RelocationSection<ELFT> *PltRelocSection = In<ELFT>::RelaPlt;
1690 if (HeaderSize == 0) {
1691 PltRelocSection = In<ELFT>::RelaIplt;
1692 Sym.IsInIplt = true;
1693 }
1694 unsigned RelOff = PltRelocSection->getRelocOffset();
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001695 Entries.push_back(std::make_pair(&Sym, RelOff));
1696}
1697
George Rimardfc020e2017-03-17 11:01:57 +00001698size_t PltSection::getSize() const {
Peter Smithf09245a2017-02-09 10:56:15 +00001699 return HeaderSize + Entries.size() * Target->PltEntrySize;
Eugene Leviantff23d3e2016-11-18 14:35:03 +00001700}
1701
Peter Smith96943762017-01-25 10:31:16 +00001702// Some architectures such as additional symbols in the PLT section. For
1703// example ARM uses mapping symbols to aid disassembly
George Rimardfc020e2017-03-17 11:01:57 +00001704void PltSection::addSymbols() {
Peter Smithf09245a2017-02-09 10:56:15 +00001705 // The PLT may have symbols defined for the Header, the IPLT has no header
1706 if (HeaderSize != 0)
1707 Target->addPltHeaderSymbols(this);
1708 size_t Off = HeaderSize;
Peter Smith96943762017-01-25 10:31:16 +00001709 for (size_t I = 0; I < Entries.size(); ++I) {
1710 Target->addPltSymbols(this, Off);
1711 Off += Target->PltEntrySize;
1712 }
1713}
1714
George Rimardfc020e2017-03-17 11:01:57 +00001715unsigned PltSection::getPltRelocOff() const {
1716 return (HeaderSize == 0) ? InX::Plt->getSize() : 0;
Peter Smith96943762017-01-25 10:31:16 +00001717}
1718
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001719// The string hash function for .gdb_index.
1720static uint32_t computeGdbHash(StringRef S) {
1721 uint32_t H = 0;
1722 for (uint8_t C : S)
1723 H = H * 67 + tolower(C) - 113;
1724 return H;
George Rimarec02b8d2016-12-15 12:07:53 +00001725}
1726
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001727static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1728 std::vector<GdbIndexChunk::CuEntry> Ret;
1729 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1730 Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001731 return Ret;
1732}
1733
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001734static std::vector<GdbIndexChunk::AddressEntry>
1735readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1736 std::vector<GdbIndexChunk::AddressEntry> Ret;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001737
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001738 uint32_t CuIdx = 0;
1739 for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001740 DWARFAddressRangesVector Ranges;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001741 Cu->collectAddressRanges(Ranges);
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001742
George Rimar35e846e2017-03-21 08:19:34 +00001743 ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
George Rimar0641b8b2017-06-07 10:52:02 +00001744 for (DWARFAddressRange &R : Ranges) {
1745 InputSectionBase *S = Sections[R.SectionIndex];
1746 if (!S || S == &InputSection::Discarded || !S->Live)
1747 continue;
1748 // Range list with zero size has no effect.
1749 if (R.LowPC == R.HighPC)
1750 continue;
Rafael Espindola8b1afd52017-07-19 22:27:35 +00001751 auto *IS = cast<InputSection>(S);
1752 uint64_t Offset = IS->getOffsetInFile();
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001753 Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
George Rimar0641b8b2017-06-07 10:52:02 +00001754 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001755 ++CuIdx;
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001756 }
1757 return Ret;
1758}
1759
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001760static std::vector<GdbIndexChunk::NameTypeEntry>
1761readPubNamesAndTypes(DWARFContext &Dwarf) {
1762 StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1763 StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001764
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001765 std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1766 for (StringRef Sec : {Sec1, Sec2}) {
1767 DWARFDebugPubTable Table(Sec, Config->IsLE, true);
Rui Ueyama22125d82017-09-25 01:42:57 +00001768 for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1769 for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1770 CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1771 Ret.push_back({S, Ent.Descriptor.toBits()});
1772 }
1773 }
Rui Ueyamaac2d8152017-03-01 22:54:50 +00001774 }
1775 return Ret;
1776}
1777
George Rimar86665622017-06-07 16:59:11 +00001778static std::vector<InputSection *> getDebugInfoSections() {
1779 std::vector<InputSection *> Ret;
1780 for (InputSectionBase *S : InputSections)
1781 if (InputSection *IS = dyn_cast<InputSection>(S))
Rafael Espindola300b3862017-07-12 23:56:53 +00001782 if (IS->Name == ".debug_info")
George Rimar86665622017-06-07 16:59:11 +00001783 Ret.push_back(IS);
1784 return Ret;
1785}
1786
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001787void GdbIndexSection::fixCuIndex() {
1788 uint32_t Idx = 0;
1789 for (GdbIndexChunk &Chunk : Chunks) {
1790 for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1791 Ent.CuIndex += Idx;
1792 Idx += Chunk.CompilationUnits.size();
George Rimar86665622017-06-07 16:59:11 +00001793 }
1794}
1795
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001796std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
1797 std::vector<std::vector<uint32_t>> Ret;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001798 uint32_t Idx = 0;
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001799 uint32_t Off = 0;
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001800
1801 for (GdbIndexChunk &Chunk : Chunks) {
1802 for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001803 GdbSymbol *&Sym = Symbols[Ent.Name];
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001804 if (!Sym) {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001805 Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
1806 Off += Ent.Name.size() + 1;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001807 Ret.push_back({});
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001808 }
Rui Ueyamaf9da2fd2017-09-25 05:30:39 +00001809
1810 // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
1811 // duplicate entries, so we want to dedup them.
1812 std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
1813 uint32_t Val = (Ent.Type << 24) | Idx;
1814 if (Vec.empty() || Vec.back() != Val)
1815 Vec.push_back(Val);
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001816 }
1817 Idx += Chunk.CompilationUnits.size();
1818 }
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001819
1820 StringPoolSize = Off;
George Rimar86665622017-06-07 16:59:11 +00001821 return Ret;
1822}
George Rimar8b547392016-12-15 09:08:13 +00001823
Rafael Espindola300b3862017-07-12 23:56:53 +00001824template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00001825 // Gather debug info to create a .gdb_index section.
George Rimar2d23da02017-08-01 14:57:13 +00001826 std::vector<InputSection *> Sections = getDebugInfoSections();
1827 std::vector<GdbIndexChunk> Chunks(Sections.size());
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001828
George Rimar2d23da02017-08-01 14:57:13 +00001829 parallelForEachN(0, Chunks.size(), [&](size_t I) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001830 ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
1831 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
1832
1833 Chunks[I].DebugInfoSec = Sections[I];
1834 Chunks[I].CompilationUnits = readCuList(Dwarf);
1835 Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
1836 Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
George Rimar2d23da02017-08-01 14:57:13 +00001837 });
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001838
Rui Ueyamaa1b79df2017-10-10 22:59:32 +00001839 // .debug_gnu_pub{names,types} are useless in executables.
1840 // They are present in input object files solely for creating
1841 // a .gdb_index. So we can remove it from the output.
1842 for (InputSectionBase *S : InputSections)
1843 if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
1844 S->Live = false;
1845
1846 // Create a .gdb_index and returns it.
Rafael Espindola300b3862017-07-12 23:56:53 +00001847 return make<GdbIndexSection>(std::move(Chunks));
1848}
1849
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001850static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001851 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001852 for (const GdbIndexChunk &D : Arr)
George Rimar86665622017-06-07 16:59:11 +00001853 Ret += D.CompilationUnits.size();
1854 return Ret;
1855}
George Rimarec02b8d2016-12-15 12:07:53 +00001856
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001857static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
George Rimar86665622017-06-07 16:59:11 +00001858 size_t Ret = 0;
Rui Ueyamae5d642c2017-08-15 17:01:28 +00001859 for (const GdbIndexChunk &D : Arr)
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001860 Ret += D.AddressAreas.size();
1861 return Ret;
1862}
1863
1864std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001865 uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
1866 if (Size < 1024)
1867 Size = 1024;
1868
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001869 uint32_t Mask = Size - 1;
1870 std::vector<GdbSymbol *> Ret(Size);
1871
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001872 for (auto &KV : Symbols) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001873 GdbSymbol *Sym = KV.second;
1874 uint32_t I = Sym->NameHash & Mask;
1875 uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
1876
1877 while (Ret[I])
1878 I = (I + Step) & Mask;
1879 Ret[I] = Sym;
1880 }
George Rimar86665622017-06-07 16:59:11 +00001881 return Ret;
Eugene Levianta113a412016-11-21 09:24:43 +00001882}
1883
Rui Ueyama2b6631b2017-08-15 17:01:39 +00001884GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001885 : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001886 fixCuIndex();
1887 CuVectors = createCuVectors();
1888 GdbSymtab = createGdbSymtab();
Eugene Levianta113a412016-11-21 09:24:43 +00001889
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001890 // Compute offsets early to know the section size.
1891 // Each chunk size needs to be in sync with what we write in writeTo.
1892 CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16;
1893 SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20;
1894 ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8;
George Rimarec02b8d2016-12-15 12:07:53 +00001895
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001896 size_t Off = 0;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001897 for (ArrayRef<uint32_t> Vec : CuVectors) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001898 CuVectorOffsets.push_back(Off);
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001899 Off += (Vec.size() + 1) * 4;
George Rimarec02b8d2016-12-15 12:07:53 +00001900 }
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001901 StringPoolOffset = ConstantPoolOffset + Off;
George Rimar8b547392016-12-15 09:08:13 +00001902}
1903
George Rimar35e846e2017-03-21 08:19:34 +00001904size_t GdbIndexSection::getSize() const {
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001905 return StringPoolOffset + StringPoolSize;
Eugene Levianta113a412016-11-21 09:24:43 +00001906}
1907
George Rimar35e846e2017-03-21 08:19:34 +00001908void GdbIndexSection::writeTo(uint8_t *Buf) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001909 // Write the section header.
1910 write32le(Buf, 7);
1911 write32le(Buf + 4, CuListOffset);
1912 write32le(Buf + 8, CuTypesOffset);
1913 write32le(Buf + 12, CuTypesOffset);
1914 write32le(Buf + 16, SymtabOffset);
1915 write32le(Buf + 20, ConstantPoolOffset);
Eugene Levianta113a412016-11-21 09:24:43 +00001916 Buf += 24;
1917
1918 // Write the CU list.
George Rimar86665622017-06-07 16:59:11 +00001919 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001920 for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) {
Rafael Espindola300b3862017-07-12 23:56:53 +00001921 write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset);
George Rimar86665622017-06-07 16:59:11 +00001922 write64le(Buf + 8, Cu.CuLength);
1923 Buf += 16;
1924 }
Eugene Levianta113a412016-11-21 09:24:43 +00001925 }
George Rimar8b547392016-12-15 09:08:13 +00001926
1927 // Write the address area.
George Rimar86665622017-06-07 16:59:11 +00001928 for (GdbIndexChunk &D : Chunks) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001929 for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) {
George Rimar86665622017-06-07 16:59:11 +00001930 uint64_t BaseAddr =
1931 E.Section->getParent()->Addr + E.Section->getOffset(0);
1932 write64le(Buf, BaseAddr + E.LowAddress);
1933 write64le(Buf + 8, BaseAddr + E.HighAddress);
1934 write32le(Buf + 16, E.CuIndex);
1935 Buf += 20;
1936 }
George Rimar8b547392016-12-15 09:08:13 +00001937 }
George Rimarec02b8d2016-12-15 12:07:53 +00001938
1939 // Write the symbol table.
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001940 for (GdbSymbol *Sym : GdbSymtab) {
George Rimarec02b8d2016-12-15 12:07:53 +00001941 if (Sym) {
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001942 write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset);
1943 write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]);
George Rimarec02b8d2016-12-15 12:07:53 +00001944 }
1945 Buf += 8;
1946 }
1947
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001948 // Write the CU vectors.
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001949 for (ArrayRef<uint32_t> Vec : CuVectors) {
1950 write32le(Buf, Vec.size());
George Rimarec02b8d2016-12-15 12:07:53 +00001951 Buf += 4;
Rui Ueyama17cc6f62017-09-25 04:55:27 +00001952 for (uint32_t Val : Vec) {
George Rimar5f5905e2017-05-26 12:01:40 +00001953 write32le(Buf, Val);
George Rimarec02b8d2016-12-15 12:07:53 +00001954 Buf += 4;
1955 }
1956 }
1957
Rui Ueyama9f4f4902017-09-24 21:45:35 +00001958 // Write the string pool.
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001959 for (auto &KV : Symbols) {
1960 CachedHashStringRef S = KV.first;
1961 GdbSymbol *Sym = KV.second;
1962 size_t Off = Sym->NameOffset;
1963 memcpy(Buf + Off, S.val().data(), S.size());
Rui Ueyama8f222b82017-09-25 03:40:45 +00001964 Buf[Off + S.size()] = '\0';
Rui Ueyamabbc477c2017-09-25 02:29:51 +00001965 }
Eugene Levianta113a412016-11-21 09:24:43 +00001966}
1967
George Rimar67c60722017-07-18 11:55:35 +00001968bool GdbIndexSection::empty() const { return !Out::DebugInfo; }
George Rimar3fb5a6d2016-11-29 16:05:27 +00001969
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001970template <class ELFT>
1971EhFrameHeader<ELFT>::EhFrameHeader()
Rui Ueyama9320cb02017-02-27 02:56:02 +00001972 : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {}
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001973
1974// .eh_frame_hdr contains a binary search table of pointers to FDEs.
1975// Each entry of the search table consists of two values,
1976// the starting PC from where FDEs covers, and the FDE's address.
1977// It is sorted by PC.
1978template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
1979 const endianness E = ELFT::TargetEndianness;
1980
1981 // Sort the FDE list by their PC and uniqueify. Usually there is only
1982 // one FDE for a PC (i.e. function), but if ICF merges two functions
1983 // into one, there can be more than one FDEs pointing to the address.
1984 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
1985 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
1986 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
1987 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
1988
1989 Buf[0] = 1;
1990 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
1991 Buf[2] = DW_EH_PE_udata4;
1992 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00001993 write32<E>(Buf + 4, In<ELFT>::EhFrame->getParent()->Addr - this->getVA() - 4);
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001994 write32<E>(Buf + 8, Fdes.size());
1995 Buf += 12;
1996
Rui Ueyamac49bdd62017-04-14 01:34:45 +00001997 uint64_t VA = this->getVA();
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001998 for (FdeData &Fde : Fdes) {
1999 write32<E>(Buf, Fde.Pc - VA);
2000 write32<E>(Buf + 4, Fde.FdeVA - VA);
2001 Buf += 8;
2002 }
2003}
2004
2005template <class ELFT> size_t EhFrameHeader<ELFT>::getSize() const {
2006 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola66b4e212017-02-23 22:06:28 +00002007 return 12 + In<ELFT>::EhFrame->NumFdes * 8;
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002008}
2009
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002010template <class ELFT>
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002011void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
2012 Fdes.push_back({Pc, FdeVA});
2013}
2014
George Rimar11992c862016-11-25 08:05:41 +00002015template <class ELFT> bool EhFrameHeader<ELFT>::empty() const {
Rafael Espindola66b4e212017-02-23 22:06:28 +00002016 return In<ELFT>::EhFrame->empty();
George Rimar11992c862016-11-25 08:05:41 +00002017}
2018
Rui Ueyamab38ddb12016-11-21 19:46:04 +00002019template <class ELFT>
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002020VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002021 : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t),
2022 ".gnu.version_d") {}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002023
2024static StringRef getFileDefName() {
2025 if (!Config->SoName.empty())
2026 return Config->SoName;
2027 return Config->OutputFile;
2028}
2029
Rui Ueyama945055a2017-02-27 03:07:41 +00002030template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() {
Rafael Espindola895aea62017-05-11 22:02:41 +00002031 FileDefNameOff = InX::DynStrTab->addString(getFileDefName());
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002032 for (VersionDefinition &V : Config->VersionDefinitions)
Rafael Espindola895aea62017-05-11 22:02:41 +00002033 V.NameOff = InX::DynStrTab->addString(V.Name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002034
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002035 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002036
2037 // sh_info should be set to the number of definitions. This fact is missed in
2038 // documentation, but confirmed by binutils community:
2039 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002040 getParent()->Info = getVerDefNum();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002041}
2042
2043template <class ELFT>
2044void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
2045 StringRef Name, size_t NameOff) {
2046 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2047 Verdef->vd_version = 1;
2048 Verdef->vd_cnt = 1;
2049 Verdef->vd_aux = sizeof(Elf_Verdef);
2050 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2051 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
2052 Verdef->vd_ndx = Index;
2053 Verdef->vd_hash = hashSysV(Name);
2054
2055 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
2056 Verdaux->vda_name = NameOff;
2057 Verdaux->vda_next = 0;
2058}
2059
2060template <class ELFT>
2061void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
2062 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
2063
2064 for (VersionDefinition &V : Config->VersionDefinitions) {
2065 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
2066 writeOne(Buf, V.Id, V.Name, V.NameOff);
2067 }
2068
2069 // Need to terminate the last version definition.
2070 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
2071 Verdef->vd_next = 0;
2072}
2073
2074template <class ELFT> size_t VersionDefinitionSection<ELFT>::getSize() const {
2075 return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
2076}
2077
2078template <class ELFT>
2079VersionTableSection<ELFT>::VersionTableSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002080 : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t),
Rui Ueyama27876642017-03-01 04:04:23 +00002081 ".gnu.version") {
2082 this->Entsize = sizeof(Elf_Versym);
2083}
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002084
Rui Ueyama945055a2017-02-27 03:07:41 +00002085template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002086 // At the moment of june 2016 GNU docs does not mention that sh_link field
2087 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002088 getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002089}
2090
2091template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const {
George Rimar69b17c32017-05-16 10:04:42 +00002092 return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002093}
2094
2095template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
2096 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
George Rimar69b17c32017-05-16 10:04:42 +00002097 for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002098 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
2099 ++OutVersym;
2100 }
2101}
2102
George Rimar11992c862016-11-25 08:05:41 +00002103template <class ELFT> bool VersionTableSection<ELFT>::empty() const {
2104 return !In<ELFT>::VerDef && In<ELFT>::VerNeed->empty();
2105}
2106
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002107template <class ELFT>
2108VersionNeedSection<ELFT>::VersionNeedSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002109 : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t),
2110 ".gnu.version_r") {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002111 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
2112 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
2113 // First identifiers are reserved by verdef section if it exist.
2114 NextIndex = getVerDefNum() + 1;
2115}
2116
2117template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +00002118void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) {
2119 auto *Ver = reinterpret_cast<const typename ELFT::Verdef *>(SS->Verdef);
2120 if (!Ver) {
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002121 SS->symbol()->VersionId = VER_NDX_GLOBAL;
2122 return;
2123 }
Rui Ueyama4076fa12017-02-26 23:35:34 +00002124
Rafael Espindola6e93d052017-08-04 22:31:42 +00002125 SharedFile<ELFT> *File = SS->getFile<ELFT>();
Rui Ueyama4076fa12017-02-26 23:35:34 +00002126
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002127 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
2128 // to create one by adding it to our needed list and creating a dynstr entry
2129 // for the soname.
Rui Ueyama4076fa12017-02-26 23:35:34 +00002130 if (File->VerdefMap.empty())
Rafael Espindola895aea62017-05-11 22:02:41 +00002131 Needed.push_back({File, InX::DynStrTab->addString(File->SoName)});
Rui Ueyama4076fa12017-02-26 23:35:34 +00002132 typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver];
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002133 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
2134 // prepare to create one by allocating a version identifier and creating a
2135 // dynstr entry for the version name.
2136 if (NV.Index == 0) {
Rafael Espindola895aea62017-05-11 22:02:41 +00002137 NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() +
2138 Ver->getAux()->vda_name);
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002139 NV.Index = NextIndex++;
2140 }
2141 SS->symbol()->VersionId = NV.Index;
2142}
2143
2144template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
2145 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
2146 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
2147 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
2148
2149 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
2150 // Create an Elf_Verneed for this DSO.
2151 Verneed->vn_version = 1;
2152 Verneed->vn_cnt = P.first->VerdefMap.size();
2153 Verneed->vn_file = P.second;
2154 Verneed->vn_aux =
2155 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
2156 Verneed->vn_next = sizeof(Elf_Verneed);
2157 ++Verneed;
2158
2159 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
2160 // VerdefMap, which will only contain references to needed version
2161 // definitions. Each Elf_Vernaux is based on the information contained in
2162 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
2163 // pointers, but is deterministic because the pointers refer to Elf_Verdef
2164 // data structures within a single input file.
2165 for (auto &NV : P.first->VerdefMap) {
2166 Vernaux->vna_hash = NV.first->vd_hash;
2167 Vernaux->vna_flags = 0;
2168 Vernaux->vna_other = NV.second.Index;
2169 Vernaux->vna_name = NV.second.StrTab;
2170 Vernaux->vna_next = sizeof(Elf_Vernaux);
2171 ++Vernaux;
2172 }
2173
2174 Vernaux[-1].vna_next = 0;
2175 }
2176 Verneed[-1].vn_next = 0;
2177}
2178
Rui Ueyama945055a2017-02-27 03:07:41 +00002179template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002180 getParent()->Link = InX::DynStrTab->getParent()->SectionIndex;
2181 getParent()->Info = Needed.size();
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002182}
2183
2184template <class ELFT> size_t VersionNeedSection<ELFT>::getSize() const {
2185 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
2186 for (const std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
2187 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
2188 return Size;
2189}
2190
George Rimar11992c862016-11-25 08:05:41 +00002191template <class ELFT> bool VersionNeedSection<ELFT>::empty() const {
2192 return getNeedNum() == 0;
2193}
2194
Rafael Espindola6119b862017-03-06 20:23:56 +00002195void MergeSyntheticSection::addSection(MergeInputSection *MS) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002196 MS->Parent = this;
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002197 Sections.push_back(MS);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002198}
2199
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002200MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type,
2201 uint64_t Flags, uint32_t Alignment)
2202 : MergeSyntheticSection(Name, Type, Flags, Alignment),
2203 Builder(StringTableBuilder::RAW, Alignment) {}
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002204
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002205size_t MergeTailSection::getSize() const { return Builder.getSize(); }
2206
2207void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); }
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002208
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002209void MergeTailSection::finalizeContents() {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002210 // Add all string pieces to the string table builder to create section
2211 // contents.
Rafael Espindola6119b862017-03-06 20:23:56 +00002212 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002213 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2214 if (Sec->Pieces[I].Live)
2215 Builder.add(Sec->getData(I));
2216
2217 // Fix the string table content. After this, the contents will never change.
2218 Builder.finalize();
2219
2220 // finalize() fixed tail-optimized strings, so we can now get
2221 // offsets of strings. Get an offset for each string and save it
2222 // to a corresponding StringPiece for easy access.
Rafael Espindola6119b862017-03-06 20:23:56 +00002223 for (MergeInputSection *Sec : Sections)
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002224 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2225 if (Sec->Pieces[I].Live)
2226 Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
2227}
2228
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002229void MergeNoTailSection::writeTo(uint8_t *Buf) {
2230 for (size_t I = 0; I < NumShards; ++I)
2231 Shards[I].write(Buf + ShardOffsets[I]);
2232}
2233
2234// This function is very hot (i.e. it can take several seconds to finish)
2235// because sometimes the number of inputs is in an order of magnitude of
2236// millions. So, we use multi-threading.
2237//
2238// For any strings S and T, we know S is not mergeable with T if S's hash
2239// value is different from T's. If that's the case, we can safely put S and
2240// T into different string builders without worrying about merge misses.
2241// We do it in parallel.
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002242void MergeNoTailSection::finalizeContents() {
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002243 // Initializes string table builders.
2244 for (size_t I = 0; I < NumShards; ++I)
2245 Shards.emplace_back(StringTableBuilder::RAW, Alignment);
2246
Rui Ueyamaf3f9bae2017-10-03 00:45:24 +00002247 // Concurrency level. Must be a power of 2 to avoid expensive modulo
2248 // operations in the following tight loop.
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002249 size_t Concurrency = 1;
Bob Haarman4f5c8c22017-10-13 18:22:55 +00002250 if (ThreadsEnabled)
Rafael Espindola0038dfa2017-10-04 20:35:05 +00002251 Concurrency =
2252 std::min<size_t>(PowerOf2Floor(hardware_concurrency()), NumShards);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002253
2254 // Add section pieces to the builders.
2255 parallelForEachN(0, Concurrency, [&](size_t ThreadId) {
2256 for (MergeInputSection *Sec : Sections) {
2257 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) {
2258 if (!Sec->Pieces[I].Live)
2259 continue;
Rui Ueyama95bf5092017-10-21 23:20:13 +00002260 size_t ShardId = getShardId(Sec->Pieces[I].Hash);
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002261 if ((ShardId & (Concurrency - 1)) == ThreadId)
Rui Ueyama95bf5092017-10-21 23:20:13 +00002262 Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I));
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002263 }
2264 }
2265 });
2266
2267 // Compute an in-section offset for each shard.
2268 size_t Off = 0;
2269 for (size_t I = 0; I < NumShards; ++I) {
2270 Shards[I].finalizeInOrder();
2271 if (Shards[I].getSize() > 0)
2272 Off = alignTo(Off, Alignment);
2273 ShardOffsets[I] = Off;
2274 Off += Shards[I].getSize();
2275 }
2276 Size = Off;
2277
2278 // So far, section pieces have offsets from beginning of shards, but
2279 // we want offsets from beginning of the whole section. Fix them.
2280 parallelForEach(Sections, [&](MergeInputSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002281 for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
2282 if (Sec->Pieces[I].Live)
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002283 Sec->Pieces[I].OutputOff +=
Rui Ueyama95bf5092017-10-21 23:20:13 +00002284 ShardOffsets[getShardId(Sec->Pieces[I].Hash)];
Rui Ueyamac97a70c2017-09-30 11:46:26 +00002285 });
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002286}
2287
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002288static MergeSyntheticSection *createMergeSynthetic(StringRef Name,
2289 uint32_t Type,
2290 uint64_t Flags,
2291 uint32_t Alignment) {
2292 bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2;
2293 if (ShouldTailMerge)
2294 return make<MergeTailSection>(Name, Type, Flags, Alignment);
2295 return make<MergeNoTailSection>(Name, Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +00002296}
2297
Rui Ueyama2b714b52017-10-11 03:12:53 +00002298// Debug sections may be compressed by zlib. Uncompress if exists.
2299void elf::decompressSections() {
2300 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2301 if (Sec->Live)
2302 Sec->maybeUncompress();
2303 });
2304}
2305
2306// This function scans over the inputsections to create mergeable
2307// synthetic sections.
2308//
2309// It removes MergeInputSections from the input section array and adds
2310// new synthetic sections at the location of the first input section
2311// that it replaces. It then finalizes each synthetic section in order
2312// to compute an output offset for each piece of each input section.
2313void elf::mergeSections() {
2314 // splitIntoPieces needs to be called on each MergeInputSection
2315 // before calling finalizeContents(). Do that first.
2316 parallelForEach(InputSections, [](InputSectionBase *Sec) {
2317 if (Sec->Live)
2318 if (auto *S = dyn_cast<MergeInputSection>(Sec))
2319 S->splitIntoPieces();
George Rimara9b07142017-08-04 08:30:16 +00002320 });
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002321
2322 std::vector<MergeSyntheticSection *> MergeSections;
2323 for (InputSectionBase *&S : InputSections) {
2324 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
2325 if (!MS)
2326 continue;
2327
2328 // We do not want to handle sections that are not alive, so just remove
2329 // them instead of trying to merge.
2330 if (!MS->Live)
2331 continue;
2332
2333 StringRef OutsecName = getOutputSectionName(MS->Name);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002334 uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize);
2335
2336 auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rui Ueyamabc2c9e02017-07-20 21:42:30 +00002337 return Sec->Name == OutsecName && Sec->Flags == MS->Flags &&
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002338 Sec->Alignment == Alignment;
2339 });
2340 if (I == MergeSections.end()) {
Rui Ueyamae26b7aa2017-09-26 00:54:24 +00002341 MergeSyntheticSection *Syn =
2342 createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment);
Peter Collingbournedc7936e2017-06-12 00:00:51 +00002343 MergeSections.push_back(Syn);
2344 I = std::prev(MergeSections.end());
2345 S = Syn;
2346 } else {
2347 S = nullptr;
2348 }
2349 (*I)->addSection(MS);
2350 }
2351 for (auto *MS : MergeSections)
2352 MS->finalizeContents();
2353
2354 std::vector<InputSectionBase *> &V = InputSections;
2355 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
2356}
2357
George Rimar42886c42017-03-15 12:02:31 +00002358MipsRldMapSection::MipsRldMapSection()
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002359 : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize,
2360 ".rld_map") {}
Eugene Leviant17b7a572016-11-22 17:49:14 +00002361
George Rimar90a528b2017-03-21 09:01:39 +00002362ARMExidxSentinelSection::ARMExidxSentinelSection()
Rui Ueyama9320cb02017-02-27 02:56:02 +00002363 : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX,
George Rimar90a528b2017-03-21 09:01:39 +00002364 Config->Wordsize, ".ARM.exidx") {}
Peter Smith719eb8e2016-11-24 11:43:55 +00002365
2366// Write a terminating sentinel entry to the end of the .ARM.exidx table.
2367// This section will have been sorted last in the .ARM.exidx table.
2368// This table entry will have the form:
2369// | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND |
Peter Smithea79b212017-05-31 09:02:21 +00002370// The sentinel must have the PREL31 value of an address higher than any
2371// address described by any other table entry.
George Rimar90a528b2017-03-21 09:01:39 +00002372void ARMExidxSentinelSection::writeTo(uint8_t *Buf) {
Peter Smithea79b212017-05-31 09:02:21 +00002373 // The Sections are sorted in order of ascending PREL31 address with the
2374 // sentinel last. We need to find the InputSection that precedes the
2375 // sentinel. By construction the Sentinel is in the last
2376 // InputSectionDescription as the InputSection that precedes it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +00002377 OutputSection *C = getParent();
Rui Ueyama6b394ca2017-10-11 01:50:56 +00002378 auto ISD =
2379 std::find_if(C->SectionCommands.rbegin(), C->SectionCommands.rend(),
2380 [](const BaseCommand *Base) {
2381 return isa<InputSectionDescription>(Base);
2382 });
Peter Smithea79b212017-05-31 09:02:21 +00002383 auto L = cast<InputSectionDescription>(*ISD);
2384 InputSection *Highest = L->Sections[L->Sections.size() - 2];
Rafael Espindolab47c6e52017-05-31 19:09:52 +00002385 InputSection *LS = Highest->getLinkOrderDep();
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002386 uint64_t S = LS->getParent()->Addr + LS->getOffset(LS->getSize());
Peter Smithea79b212017-05-31 09:02:21 +00002387 uint64_t P = getVA();
Peter Smith719eb8e2016-11-24 11:43:55 +00002388 Target->relocateOne(Buf, R_ARM_PREL31, S - P);
2389 write32le(Buf + 4, 0x1);
2390}
2391
George Rimar7b827042017-03-16 10:40:50 +00002392ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off)
Rui Ueyama9320cb02017-02-27 02:56:02 +00002393 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
Rui Ueyamad57e74b72017-03-17 23:29:01 +00002394 Config->Wordsize, ".text.thunk") {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +00002395 this->Parent = OS;
Peter Smith3a52eb02017-02-01 10:26:03 +00002396 this->OutSecOff = Off;
2397}
2398
George Rimar7b827042017-03-16 10:40:50 +00002399void ThunkSection::addThunk(Thunk *T) {
George Rimarb939d322017-07-18 11:59:19 +00002400 uint64_t Off = alignTo(Size, T->Alignment);
Peter Smith3a52eb02017-02-01 10:26:03 +00002401 T->Offset = Off;
2402 Thunks.push_back(T);
2403 T->addSymbols(*this);
2404 Size = Off + T->size();
2405}
2406
George Rimar7b827042017-03-16 10:40:50 +00002407void ThunkSection::writeTo(uint8_t *Buf) {
2408 for (const Thunk *T : Thunks)
Peter Smith3a52eb02017-02-01 10:26:03 +00002409 T->writeTo(Buf + T->Offset, *this);
2410}
2411
George Rimar7b827042017-03-16 10:40:50 +00002412InputSection *ThunkSection::getTargetInputSection() const {
2413 const Thunk *T = Thunks.front();
Peter Smith3a52eb02017-02-01 10:26:03 +00002414 return T->getTargetInputSection();
2415}
2416
George Rimar9782ca52017-03-15 15:29:29 +00002417InputSection *InX::ARMAttributes;
George Rimar1ab9cf42017-03-17 10:14:53 +00002418BssSection *InX::Bss;
2419BssSection *InX::BssRelRo;
George Rimar6c2949d2017-03-20 16:40:21 +00002420BuildIdSection *InX::BuildId;
Rafael Espindola5ab19892017-05-11 23:16:43 +00002421SyntheticSection *InX::Dynamic;
George Rimar9782ca52017-03-15 15:29:29 +00002422StringTableSection *InX::DynStrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002423SymbolTableBaseSection *InX::DynSymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002424InputSection *InX::Interp;
George Rimar35e846e2017-03-21 08:19:34 +00002425GdbIndexSection *InX::GdbIndex;
Rafael Espindolaa6465bb2017-05-18 16:45:36 +00002426GotSection *InX::Got;
George Rimar9782ca52017-03-15 15:29:29 +00002427GotPltSection *InX::GotPlt;
George Rimarf45f6812017-05-16 08:53:30 +00002428GnuHashTableSection *InX::GnuHashTab;
George Rimaraaf54712017-09-27 09:14:59 +00002429HashTableSection *InX::HashTab;
George Rimar9782ca52017-03-15 15:29:29 +00002430IgotPltSection *InX::IgotPlt;
George Rimar14534eb2017-03-20 16:44:28 +00002431MipsGotSection *InX::MipsGot;
George Rimar9782ca52017-03-15 15:29:29 +00002432MipsRldMapSection *InX::MipsRldMap;
George Rimardfc020e2017-03-17 11:01:57 +00002433PltSection *InX::Plt;
2434PltSection *InX::Iplt;
George Rimar9782ca52017-03-15 15:29:29 +00002435StringTableSection *InX::ShStrTab;
2436StringTableSection *InX::StrTab;
George Rimarf45f6812017-05-16 08:53:30 +00002437SymbolTableBaseSection *InX::SymTab;
George Rimar9782ca52017-03-15 15:29:29 +00002438
Rafael Espindola300b3862017-07-12 23:56:53 +00002439template GdbIndexSection *elf::createGdbIndex<ELF32LE>();
2440template GdbIndexSection *elf::createGdbIndex<ELF32BE>();
2441template GdbIndexSection *elf::createGdbIndex<ELF64LE>();
2442template GdbIndexSection *elf::createGdbIndex<ELF64BE>();
2443
George Rimara9189572017-03-17 16:50:07 +00002444template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym);
2445template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym);
2446template void PltSection::addEntry<ELF64LE>(SymbolBody &Sym);
2447template void PltSection::addEntry<ELF64BE>(SymbolBody &Sym);
2448
Ben Dunbobbin73eabf22017-09-29 09:08:26 +00002449template void elf::createCommonSections<ELF32LE>();
2450template void elf::createCommonSections<ELF32BE>();
2451template void elf::createCommonSections<ELF64LE>();
2452template void elf::createCommonSections<ELF64BE>();
2453
Rafael Espindola6119b862017-03-06 20:23:56 +00002454template MergeInputSection *elf::createCommentSection<ELF32LE>();
2455template MergeInputSection *elf::createCommentSection<ELF32BE>();
2456template MergeInputSection *elf::createCommentSection<ELF64LE>();
2457template MergeInputSection *elf::createCommentSection<ELF64BE>();
Rui Ueyama3da3f062016-11-10 20:20:37 +00002458
Simon Atanasyanfa03b0f2016-11-09 21:37:06 +00002459template class elf::MipsAbiFlagsSection<ELF32LE>;
2460template class elf::MipsAbiFlagsSection<ELF32BE>;
2461template class elf::MipsAbiFlagsSection<ELF64LE>;
2462template class elf::MipsAbiFlagsSection<ELF64BE>;
2463
Simon Atanasyance02cf02016-11-09 21:36:56 +00002464template class elf::MipsOptionsSection<ELF32LE>;
2465template class elf::MipsOptionsSection<ELF32BE>;
2466template class elf::MipsOptionsSection<ELF64LE>;
2467template class elf::MipsOptionsSection<ELF64BE>;
2468
2469template class elf::MipsReginfoSection<ELF32LE>;
2470template class elf::MipsReginfoSection<ELF32BE>;
2471template class elf::MipsReginfoSection<ELF64LE>;
2472template class elf::MipsReginfoSection<ELF64BE>;
2473
Eugene Leviant6380ce22016-11-15 12:26:55 +00002474template class elf::DynamicSection<ELF32LE>;
2475template class elf::DynamicSection<ELF32BE>;
2476template class elf::DynamicSection<ELF64LE>;
2477template class elf::DynamicSection<ELF64BE>;
Eugene Levianta96d9022016-11-16 10:02:27 +00002478
2479template class elf::RelocationSection<ELF32LE>;
2480template class elf::RelocationSection<ELF32BE>;
2481template class elf::RelocationSection<ELF64LE>;
2482template class elf::RelocationSection<ELF64BE>;
Eugene Leviant9230db92016-11-17 09:16:34 +00002483
2484template class elf::SymbolTableSection<ELF32LE>;
2485template class elf::SymbolTableSection<ELF32BE>;
2486template class elf::SymbolTableSection<ELF64LE>;
2487template class elf::SymbolTableSection<ELF64BE>;
Eugene Leviantbe809a72016-11-18 06:44:18 +00002488
Eugene Leviant952eb4d2016-11-21 15:52:10 +00002489template class elf::EhFrameHeader<ELF32LE>;
2490template class elf::EhFrameHeader<ELF32BE>;
2491template class elf::EhFrameHeader<ELF64LE>;
2492template class elf::EhFrameHeader<ELF64BE>;
Eugene Leviante9bab5d2016-11-21 16:59:33 +00002493
2494template class elf::VersionTableSection<ELF32LE>;
2495template class elf::VersionTableSection<ELF32BE>;
2496template class elf::VersionTableSection<ELF64LE>;
2497template class elf::VersionTableSection<ELF64BE>;
2498
2499template class elf::VersionNeedSection<ELF32LE>;
2500template class elf::VersionNeedSection<ELF32BE>;
2501template class elf::VersionNeedSection<ELF64LE>;
2502template class elf::VersionNeedSection<ELF64BE>;
2503
2504template class elf::VersionDefinitionSection<ELF32LE>;
2505template class elf::VersionDefinitionSection<ELF32BE>;
2506template class elf::VersionDefinitionSection<ELF64LE>;
2507template class elf::VersionDefinitionSection<ELF64BE>;
Eugene Leviant17b7a572016-11-22 17:49:14 +00002508
Rafael Espindola66b4e212017-02-23 22:06:28 +00002509template class elf::EhFrameSection<ELF32LE>;
2510template class elf::EhFrameSection<ELF32BE>;
2511template class elf::EhFrameSection<ELF64LE>;
2512template class elf::EhFrameSection<ELF64BE>;