blob: 5402c3a40a5b5401961d6386d1ab7749ae710e6c [file] [log] [blame]
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001//===- OutputSections.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#include "OutputSections.h"
11#include "Config.h"
Rui Ueyamaf5febef2016-05-24 02:55:45 +000012#include "EhFrame.h"
George Rimar58fa5242016-10-20 09:19:48 +000013#include "GdbIndex.h"
Rui Ueyama95642b92016-11-01 23:09:07 +000014#include "LinkerScript.h"
15#include "Memory.h"
Rui Ueyamafbbde542016-06-29 09:08:02 +000016#include "Strings.h"
George Rimar1a33c0f2016-11-10 09:05:20 +000017#include "SymbolListFile.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000018#include "SymbolTable.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000019#include "SyntheticSections.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000020#include "Target.h"
Rui Ueyamae9809502016-03-11 04:23:12 +000021#include "lld/Core/Parallel.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000022#include "llvm/Support/Dwarf.h"
Rui Ueyama3a41be22016-04-07 22:49:21 +000023#include "llvm/Support/MD5.h"
Igor Kudrin1b0d7062015-10-22 08:21:35 +000024#include "llvm/Support/MathExtras.h"
Rafael Espindolaa42b3bc2016-09-27 16:43:49 +000025#include "llvm/Support/SHA1.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000026
Rafael Espindola5805c4f2015-09-21 21:38:08 +000027using namespace llvm;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +000028using namespace llvm::dwarf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000029using namespace llvm::object;
Rafael Espindolaa6627382015-10-06 23:56:53 +000030using namespace llvm::support::endian;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000031using namespace llvm::ELF;
32
33using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000034using namespace lld::elf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000035
Rafael Espindolae08e78d2016-11-09 23:23:45 +000036OutputSectionBase::OutputSectionBase(StringRef Name, uint32_t Type,
37 uint64_t Flags)
Rafael Espindola5805c4f2015-09-21 21:38:08 +000038 : Name(Name) {
Rafael Espindola04a2e342016-11-09 01:42:41 +000039 this->Type = Type;
40 this->Flags = Flags;
41 this->Addralign = 1;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000042}
43
Rafael Espindolae08e78d2016-11-09 23:23:45 +000044uint32_t OutputSectionBase::getPhdrFlags() const {
Rafael Espindola0b113672016-07-27 14:10:56 +000045 uint32_t Ret = PF_R;
46 if (Flags & SHF_WRITE)
47 Ret |= PF_W;
48 if (Flags & SHF_EXECINSTR)
49 Ret |= PF_X;
50 return Ret;
51}
52
Rafael Espindola35c6af32015-09-25 17:19:10 +000053template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +000054void OutputSectionBase::writeHeaderTo(typename ELFT::Shdr *Shdr) {
Rafael Espindola04a2e342016-11-09 01:42:41 +000055 Shdr->sh_entsize = Entsize;
56 Shdr->sh_addralign = Addralign;
57 Shdr->sh_type = Type;
58 Shdr->sh_offset = Offset;
59 Shdr->sh_flags = Flags;
60 Shdr->sh_info = Info;
61 Shdr->sh_link = Link;
62 Shdr->sh_addr = Addr;
63 Shdr->sh_size = Size;
64 Shdr->sh_name = ShName;
Rui Ueyamac63c1db2016-03-13 06:50:33 +000065}
66
67template <class ELFT>
George Rimar58fa5242016-10-20 09:19:48 +000068GdbIndexSection<ELFT>::GdbIndexSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +000069 : OutputSectionBase(".gdb_index", SHT_PROGBITS, 0) {}
George Rimar58fa5242016-10-20 09:19:48 +000070
71template <class ELFT> void GdbIndexSection<ELFT>::parseDebugSections() {
72 std::vector<InputSection<ELFT> *> &IS =
73 static_cast<OutputSection<ELFT> *>(Out<ELFT>::DebugInfo)->Sections;
74
75 for (InputSection<ELFT> *I : IS)
76 readDwarf(I);
77}
78
79template <class ELFT>
80void GdbIndexSection<ELFT>::readDwarf(InputSection<ELFT> *I) {
81 std::vector<std::pair<uintX_t, uintX_t>> CuList = readCuList(I);
82 CompilationUnits.insert(CompilationUnits.end(), CuList.begin(), CuList.end());
83}
84
85template <class ELFT> void GdbIndexSection<ELFT>::finalize() {
86 parseDebugSections();
87
88 // GdbIndex header consist from version fields
89 // and 5 more fields with different kinds of offsets.
90 CuTypesOffset = CuListOffset + CompilationUnits.size() * CompilationUnitSize;
Rafael Espindola04a2e342016-11-09 01:42:41 +000091 this->Size = CuTypesOffset;
George Rimar58fa5242016-10-20 09:19:48 +000092}
93
94template <class ELFT> void GdbIndexSection<ELFT>::writeTo(uint8_t *Buf) {
95 write32le(Buf, 7); // Write Version
96 write32le(Buf + 4, CuListOffset); // CU list offset
97 write32le(Buf + 8, CuTypesOffset); // Types CU list offset
98 write32le(Buf + 12, CuTypesOffset); // Address area offset
99 write32le(Buf + 16, CuTypesOffset); // Symbol table offset
100 write32le(Buf + 20, CuTypesOffset); // Constant pool offset
101 Buf += 24;
102
103 // Write the CU list.
104 for (std::pair<uintX_t, uintX_t> CU : CompilationUnits) {
105 write64le(Buf, CU.first);
106 write64le(Buf + 8, CU.second);
107 Buf += 16;
108 }
109}
110
111template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000112GotSection<ELFT>::GotSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000113 : OutputSectionBase(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000114 if (Config->EMachine == EM_MIPS)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000115 this->Flags |= SHF_MIPS_GPREL;
116 this->Addralign = Target->GotEntrySize;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000117}
118
George Rimara4c7e742016-10-20 08:36:42 +0000119template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Rafael Espindola67d72c02016-03-11 12:06:30 +0000120 Sym.GotIndex = Entries.size();
121 Entries.push_back(&Sym);
George Rimar687138c2015-11-13 16:28:53 +0000122}
123
Simon Atanasyan41325112016-06-19 21:39:37 +0000124template <class ELFT>
125void GotSection<ELFT>::addMipsEntry(SymbolBody &Sym, uintX_t Addend,
126 RelExpr Expr) {
127 // For "true" local symbols which can be referenced from the same module
128 // only compiler creates two instructions for address loading:
129 //
130 // lw $8, 0($gp) # R_MIPS_GOT16
131 // addi $8, $8, 0 # R_MIPS_LO16
132 //
133 // The first instruction loads high 16 bits of the symbol address while
134 // the second adds an offset. That allows to reduce number of required
135 // GOT entries because only one global offset table entry is necessary
136 // for every 64 KBytes of local data. So for local symbols we need to
137 // allocate number of GOT entries to hold all required "page" addresses.
138 //
139 // All global symbols (hidden and regular) considered by compiler uniformly.
140 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
141 // to load address of the symbol. So for each such symbol we need to
142 // allocate dedicated GOT entry to store its address.
143 //
144 // If a symbol is preemptible we need help of dynamic linker to get its
145 // final address. The corresponding GOT entries are allocated in the
146 // "global" part of GOT. Entries for non preemptible global symbol allocated
147 // in the "local" part of GOT.
148 //
149 // See "Global Offset Table" in Chapter 5:
150 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
151 if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
152 // At this point we do not know final symbol value so to reduce number
153 // of allocated GOT entries do the following trick. Save all output
154 // sections referenced by GOT relocations. Then later in the `finalize`
155 // method calculate number of "pages" required to cover all saved output
156 // section and allocate appropriate number of GOT entries.
157 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
158 MipsOutSections.insert(OutSec);
159 return;
160 }
Simon Atanasyan002e2442016-06-23 15:26:31 +0000161 if (Sym.isTls()) {
162 // GOT entries created for MIPS TLS relocations behave like
163 // almost GOT entries from other ABIs. They go to the end
164 // of the global offset table.
165 Sym.GotIndex = Entries.size();
166 Entries.push_back(&Sym);
167 return;
168 }
Simon Atanasyan41325112016-06-19 21:39:37 +0000169 auto AddEntry = [&](SymbolBody &S, uintX_t A, MipsGotEntries &Items) {
170 if (S.isInGot() && !A)
171 return;
172 size_t NewIndex = Items.size();
173 if (!MipsGotMap.insert({{&S, A}, NewIndex}).second)
174 return;
175 Items.emplace_back(&S, A);
176 if (!A)
177 S.GotIndex = NewIndex;
178 };
179 if (Sym.isPreemptible()) {
180 // Ignore addends for preemptible symbols. They got single GOT entry anyway.
181 AddEntry(Sym, 0, MipsGlobal);
182 Sym.IsInGlobalMipsGot = true;
Simon Atanasyanbed04bf2016-10-21 07:22:30 +0000183 } else if (Expr == R_MIPS_GOT_OFF32) {
184 AddEntry(Sym, Addend, MipsLocal32);
185 Sym.Is32BitMipsGot = true;
186 } else {
187 // Hold local GOT entries accessed via a 16-bit index separately.
188 // That allows to write them in the beginning of the GOT and keep
189 // their indexes as less as possible to escape relocation's overflow.
Simon Atanasyan41325112016-06-19 21:39:37 +0000190 AddEntry(Sym, Addend, MipsLocal);
Simon Atanasyanbed04bf2016-10-21 07:22:30 +0000191 }
Simon Atanasyan41325112016-06-19 21:39:37 +0000192}
193
Rafael Espindola67d72c02016-03-11 12:06:30 +0000194template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000195 if (Sym.GlobalDynIndex != -1U)
George Rimar90cd0a82015-12-01 19:20:26 +0000196 return false;
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000197 Sym.GlobalDynIndex = Entries.size();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000198 // Global Dynamic TLS entries take two GOT slots.
George Rimar687138c2015-11-13 16:28:53 +0000199 Entries.push_back(nullptr);
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000200 Entries.push_back(&Sym);
George Rimar90cd0a82015-12-01 19:20:26 +0000201 return true;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000202}
203
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000204// Reserves TLS entries for a TLS module ID and a TLS block offset.
205// In total it takes two GOT slots.
206template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
207 if (TlsIndexOff != uint32_t(-1))
George Rimarb17f7392015-12-01 18:24:07 +0000208 return false;
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000209 TlsIndexOff = Entries.size() * sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000210 Entries.push_back(nullptr);
211 Entries.push_back(nullptr);
George Rimarb17f7392015-12-01 18:24:07 +0000212 return true;
Michael J. Spencer1e225612015-11-11 01:00:24 +0000213}
214
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000215template <class ELFT>
216typename GotSection<ELFT>::uintX_t
Rafael Espindola58cd5db2016-04-19 22:46:03 +0000217GotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000218 // Initialize the entry by the %hi(EntryValue) expression
219 // but without right-shifting.
Simon Atanasyan41325112016-06-19 21:39:37 +0000220 EntryValue = (EntryValue + 0x8000) & ~0xffff;
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000221 // Take into account MIPS GOT header.
222 // See comment in the GotSection::writeTo.
223 size_t NewIndex = MipsLocalGotPos.size() + 2;
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000224 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
Simon Atanasyan41325112016-06-19 21:39:37 +0000225 assert(!P.second || MipsLocalGotPos.size() <= MipsPageEntries);
George Rimar71e64b22016-05-11 09:41:15 +0000226 return (uintX_t)P.first->second * sizeof(uintX_t) - MipsGPOffset;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000227}
228
Igor Kudrin304860a2015-11-12 04:39:49 +0000229template <class ELFT>
George Rimar90cd0a82015-12-01 19:20:26 +0000230typename GotSection<ELFT>::uintX_t
Simon Atanasyan41325112016-06-19 21:39:37 +0000231GotSection<ELFT>::getMipsGotOffset(const SymbolBody &B, uintX_t Addend) const {
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000232 // Calculate offset of the GOT entries block: TLS, global, local.
233 uintX_t GotBlockOff;
Simon Atanasyan002e2442016-06-23 15:26:31 +0000234 if (B.isTls())
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000235 GotBlockOff = getMipsTlsOffset();
Simon Atanasyan002e2442016-06-23 15:26:31 +0000236 else if (B.IsInGlobalMipsGot)
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000237 GotBlockOff = getMipsLocalEntriesNum() * sizeof(uintX_t);
Simon Atanasyanbed04bf2016-10-21 07:22:30 +0000238 else if (B.Is32BitMipsGot)
239 GotBlockOff = (MipsPageEntries + MipsLocal.size()) * sizeof(uintX_t);
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000240 else
241 GotBlockOff = MipsPageEntries * sizeof(uintX_t);
242 // Calculate index of the GOT entry in the block.
243 uintX_t GotIndex;
244 if (B.isInGot())
245 GotIndex = B.GotIndex;
Simon Atanasyan41325112016-06-19 21:39:37 +0000246 else {
247 auto It = MipsGotMap.find({&B, Addend});
248 assert(It != MipsGotMap.end());
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000249 GotIndex = It->second;
Simon Atanasyan41325112016-06-19 21:39:37 +0000250 }
Simon Atanasyanf4415a32016-10-20 17:53:55 +0000251 return GotBlockOff + GotIndex * sizeof(uintX_t) - MipsGPOffset;
Simon Atanasyan41325112016-06-19 21:39:37 +0000252}
253
254template <class ELFT>
Simon Atanasyanbc946932016-10-19 17:13:43 +0000255typename GotSection<ELFT>::uintX_t GotSection<ELFT>::getMipsTlsOffset() const {
Simon Atanasyanbadd5b32016-10-20 17:53:59 +0000256 return (getMipsLocalEntriesNum() + MipsGlobal.size()) * sizeof(uintX_t);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000257}
258
259template <class ELFT>
Simon Atanasyan41325112016-06-19 21:39:37 +0000260typename GotSection<ELFT>::uintX_t
George Rimar90cd0a82015-12-01 19:20:26 +0000261GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000262 return this->Addr + B.GlobalDynIndex * sizeof(uintX_t);
George Rimar90cd0a82015-12-01 19:20:26 +0000263}
264
265template <class ELFT>
Rafael Espindola74031ba2016-04-07 15:20:56 +0000266typename GotSection<ELFT>::uintX_t
267GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
Rafael Espindola6211d9a2016-06-05 19:03:28 +0000268 return B.GlobalDynIndex * sizeof(uintX_t);
Rafael Espindola74031ba2016-04-07 15:20:56 +0000269}
270
271template <class ELFT>
Igor Kudrin304860a2015-11-12 04:39:49 +0000272const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
Simon Atanasyan41325112016-06-19 21:39:37 +0000273 return MipsGlobal.empty() ? nullptr : MipsGlobal.front().first;
Igor Kudrin304860a2015-11-12 04:39:49 +0000274}
275
276template <class ELFT>
277unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
Simon Atanasyanbed04bf2016-10-21 07:22:30 +0000278 return MipsPageEntries + MipsLocal.size() + MipsLocal32.size();
Igor Kudrin304860a2015-11-12 04:39:49 +0000279}
280
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000281template <class ELFT> void GotSection<ELFT>::finalize() {
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000282 size_t EntriesNum = Entries.size();
283 if (Config->EMachine == EM_MIPS) {
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000284 // Take into account MIPS GOT header.
285 // See comment in the GotSection::writeTo.
Simon Atanasyan41325112016-06-19 21:39:37 +0000286 MipsPageEntries += 2;
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000287 for (const OutputSectionBase *OutSec : MipsOutSections) {
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000288 // Calculate an upper bound of MIPS GOT entries required to store page
289 // addresses of local symbols. We assume the worst case - each 64kb
290 // page of the output section has at least one GOT relocation against it.
291 // Add 0x8000 to the section's size because the page address stored
292 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000293 MipsPageEntries += (OutSec->Size + 0x8000 + 0xfffe) / 0xffff;
Simon Atanasyan311b4b12016-06-10 12:26:28 +0000294 }
Simon Atanasyanbadd5b32016-10-20 17:53:59 +0000295 EntriesNum += getMipsLocalEntriesNum() + MipsGlobal.size();
Simon Atanasyand2980d32016-03-29 14:07:22 +0000296 }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000297 this->Size = EntriesNum * sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000298}
299
Rui Ueyamac442cff2016-09-08 21:46:21 +0000300template <class ELFT>
301static void writeUint(uint8_t *Buf, typename ELFT::uint Val) {
302 typedef typename ELFT::uint uintX_t;
303 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Buf, Val);
304}
305
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000306template <class ELFT> void GotSection<ELFT>::writeMipsGot(uint8_t *Buf) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000307 // Set the MSB of the second GOT slot. This is not required by any
308 // MIPS ABI documentation, though.
309 //
310 // There is a comment in glibc saying that "The MSB of got[1] of a
311 // gnu object is set to identify gnu objects," and in GNU gold it
312 // says "the second entry will be used by some runtime loaders".
313 // But how this field is being used is unclear.
314 //
315 // We are not really willing to mimic other linkers behaviors
316 // without understanding why they do that, but because all files
317 // generated by GNU tools have this special GOT value, and because
318 // we've been doing this for years, it is probably a safe bet to
319 // keep doing this for now. We really need to revisit this to see
320 // if we had to do this.
321 auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
322 P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
323 // Write 'page address' entries to the local part of the GOT.
324 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
325 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
Rui Ueyamac442cff2016-09-08 21:46:21 +0000326 writeUint<ELFT>(Entry, L.first);
Simon Atanasyan1ef1bf82016-04-25 20:25:05 +0000327 }
Simon Atanasyan41325112016-06-19 21:39:37 +0000328 Buf += MipsPageEntries * sizeof(uintX_t);
329 auto AddEntry = [&](const MipsGotEntry &SA) {
330 uint8_t *Entry = Buf;
331 Buf += sizeof(uintX_t);
George Rimara4c7e742016-10-20 08:36:42 +0000332 const SymbolBody *Body = SA.first;
George Rimar06e930d2016-06-20 10:01:50 +0000333 uintX_t VA = Body->template getVA<ELFT>(SA.second);
Rui Ueyamac442cff2016-09-08 21:46:21 +0000334 writeUint<ELFT>(Entry, VA);
Simon Atanasyan41325112016-06-19 21:39:37 +0000335 };
336 std::for_each(std::begin(MipsLocal), std::end(MipsLocal), AddEntry);
Simon Atanasyanbed04bf2016-10-21 07:22:30 +0000337 std::for_each(std::begin(MipsLocal32), std::end(MipsLocal32), AddEntry);
Simon Atanasyan41325112016-06-19 21:39:37 +0000338 std::for_each(std::begin(MipsGlobal), std::end(MipsGlobal), AddEntry);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000339 // Initialize TLS-related GOT entries. If the entry has a corresponding
340 // dynamic relocations, leave it initialized by zero. Write down adjusted
341 // TLS symbol's values otherwise. To calculate the adjustments use offsets
342 // for thread-local storage.
343 // https://www.linux-mips.org/wiki/NPTL
344 if (TlsIndexOff != -1U && !Config->Pic)
Rui Ueyamac442cff2016-09-08 21:46:21 +0000345 writeUint<ELFT>(Buf + TlsIndexOff, 1);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000346 for (const SymbolBody *B : Entries) {
347 if (!B || B->isPreemptible())
348 continue;
349 uintX_t VA = B->getVA<ELFT>();
350 if (B->GotIndex != -1U) {
351 uint8_t *Entry = Buf + B->GotIndex * sizeof(uintX_t);
Rui Ueyamac442cff2016-09-08 21:46:21 +0000352 writeUint<ELFT>(Entry, VA - 0x7000);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000353 }
354 if (B->GlobalDynIndex != -1U) {
355 uint8_t *Entry = Buf + B->GlobalDynIndex * sizeof(uintX_t);
Rui Ueyamac442cff2016-09-08 21:46:21 +0000356 writeUint<ELFT>(Entry, 1);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000357 Entry += sizeof(uintX_t);
Rui Ueyamac442cff2016-09-08 21:46:21 +0000358 writeUint<ELFT>(Entry, VA - 0x8000);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000359 }
360 }
Simon Atanasyan41325112016-06-19 21:39:37 +0000361}
362
363template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000364 if (Config->EMachine == EM_MIPS) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000365 writeMipsGot(Buf);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000366 return;
367 }
Rafael Espindolaa6627382015-10-06 23:56:53 +0000368 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000369 uint8_t *Entry = Buf;
370 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000371 if (!B)
372 continue;
Simon Atanasyan41325112016-06-19 21:39:37 +0000373 if (B->isPreemptible())
Rafael Espindolaa6627382015-10-06 23:56:53 +0000374 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000375 uintX_t VA = B->getVA<ELFT>();
Rui Ueyamac442cff2016-09-08 21:46:21 +0000376 writeUint<ELFT>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000377 }
378}
379
Rafael Espindola35c6af32015-09-25 17:19:10 +0000380template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000381PltSection<ELFT>::PltSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000382 : OutputSectionBase(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000383 this->Addralign = 16;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000384}
385
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000386template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000387 // At beginning of PLT, we have code to call the dynamic linker
388 // to resolve dynsyms at runtime. Write such code.
Rui Ueyama4a90f572016-06-16 16:28:50 +0000389 Target->writePltHeader(Buf);
390 size_t Off = Target->PltHeaderSize;
Rui Ueyamaf57a5902016-05-20 21:39:07 +0000391
George Rimarfb5d7f22015-11-26 19:58:51 +0000392 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000393 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000394 unsigned RelOff = I.second;
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000395 uint64_t Got = B->getGotPltVA<ELFT>();
Rafael Espindola04a2e342016-11-09 01:42:41 +0000396 uint64_t Plt = this->Addr + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000397 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000398 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000399 }
400}
401
Rafael Espindola67d72c02016-03-11 12:06:30 +0000402template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
403 Sym.PltIndex = Entries.size();
Rafael Espindolae4c86d832016-05-18 21:03:36 +0000404 unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000405 Entries.push_back(std::make_pair(&Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000406}
407
George Rimar648a2c32015-10-20 08:54:27 +0000408template <class ELFT> void PltSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000409 this->Size = Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000410}
411
412template <class ELFT>
George Rimarc191acf2016-05-10 15:47:57 +0000413RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000414 : OutputSectionBase(Name, Config->Rela ? SHT_RELA : SHT_REL, SHF_ALLOC),
George Rimarc191acf2016-05-10 15:47:57 +0000415 Sort(Sort) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000416 this->Entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
417 this->Addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000418}
419
George Rimar5828c232015-11-30 17:49:19 +0000420template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000421void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
Eugene Leviantaa498192016-08-31 08:51:39 +0000422 if (Reloc.Type == Target->RelativeRel)
423 ++NumRelativeRelocs;
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000424 Relocs.push_back(Reloc);
425}
426
George Rimarc191acf2016-05-10 15:47:57 +0000427template <class ELFT, class RelTy>
428static bool compRelocations(const RelTy &A, const RelTy &B) {
Eugene Leviantaa498192016-08-31 08:51:39 +0000429 bool AIsRel = A.getType(Config->Mips64EL) == Target->RelativeRel;
430 bool BIsRel = B.getType(Config->Mips64EL) == Target->RelativeRel;
431 if (AIsRel != BIsRel)
432 return AIsRel;
433
George Rimarc191acf2016-05-10 15:47:57 +0000434 return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
435}
436
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000437template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimarc191acf2016-05-10 15:47:57 +0000438 uint8_t *BufBegin = Buf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000439 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rui Ueyama614be592016-03-13 05:23:40 +0000440 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000441 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyamab0210e832016-01-26 00:24:57 +0000442
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000443 if (Config->Rela)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000444 P->r_addend = Rel.getAddend();
445 P->r_offset = Rel.getOffset();
Simon Atanasyan002e2442016-06-23 15:26:31 +0000446 if (Config->EMachine == EM_MIPS && Rel.getOutputSec() == Out<ELFT>::Got)
447 // Dynamic relocation against MIPS GOT section make deal TLS entries
448 // allocated in the end of the GOT. We need to adjust the offset to take
449 // in account 'local' and 'global' GOT entries.
450 P->r_offset += Out<ELFT>::Got->getMipsTlsOffset();
Rui Ueyama809d8e22016-06-23 04:33:42 +0000451 P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000452 }
George Rimarc191acf2016-05-10 15:47:57 +0000453
454 if (Sort) {
455 if (Config->Rela)
456 std::stable_sort((Elf_Rela *)BufBegin,
457 (Elf_Rela *)BufBegin + Relocs.size(),
458 compRelocations<ELFT, Elf_Rela>);
459 else
460 std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
461 compRelocations<ELFT, Elf_Rel>);
462 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000463}
464
George Rimar77b77792015-11-25 22:15:01 +0000465template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000466 return this->Entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000467}
468
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000469template <class ELFT> void RelocationSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000470 this->Link = Out<ELFT>::DynSymTab ? Out<ELFT>::DynSymTab->SectionIndex
471 : Out<ELFT>::SymTab->SectionIndex;
472 this->Size = Relocs.size() * this->Entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000473}
474
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000475template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000476HashTableSection<ELFT>::HashTableSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000477 : OutputSectionBase(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000478 this->Entsize = sizeof(Elf_Word);
479 this->Addralign = sizeof(Elf_Word);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000480}
481
Rui Ueyama0db335f2015-10-07 16:58:54 +0000482template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000483 this->Link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000484
George Rimare9e1d322016-02-18 15:17:01 +0000485 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000486 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000487
488 // Create as many buckets as there are symbols.
489 // FIXME: This is simplistic. We can try to optimize it, but implementing
490 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000491 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rafael Espindola04a2e342016-11-09 01:42:41 +0000492 this->Size = NumEntries * sizeof(Elf_Word);
Rui Ueyama0db335f2015-10-07 16:58:54 +0000493}
494
495template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000496 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000497 auto *P = reinterpret_cast<Elf_Word *>(Buf);
498 *P++ = NumSymbols; // nbucket
499 *P++ = NumSymbols; // nchain
500
501 Elf_Word *Buckets = P;
502 Elf_Word *Chains = P + NumSymbols;
503
Michael J. Spencerf8a81482016-10-19 23:49:27 +0000504 for (const SymbolTableEntry &S : Out<ELFT>::DynSymTab->getSymbols()) {
505 SymbolBody *Body = S.Symbol;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000506 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000507 unsigned I = Body->DynsymIndex;
Davide Italianoe7fd0be2016-11-07 21:56:56 +0000508 uint32_t Hash = hashSysV(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000509 Chains[I] = Buckets[Hash];
510 Buckets[Hash] = I;
511 }
512}
513
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000514static uint32_t hashGnu(StringRef Name) {
515 uint32_t H = 5381;
516 for (uint8_t C : Name)
517 H = (H << 5) + H + C;
518 return H;
519}
520
521template <class ELFT>
522GnuHashTableSection<ELFT>::GnuHashTableSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000523 : OutputSectionBase(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000524 this->Entsize = ELFT::Is64Bits ? 0 : 4;
525 this->Addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000526}
527
528template <class ELFT>
529unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
530 if (!NumHashed)
531 return 0;
532
533 // These values are prime numbers which are not greater than 2^(N-1) + 1.
534 // In result, for any particular NumHashed we return a prime number
535 // which is not greater than NumHashed.
536 static const unsigned Primes[] = {
537 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
538 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
539
540 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
541 array_lengthof(Primes) - 1)];
542}
543
544// Bloom filter estimation: at least 8 bits for each hashed symbol.
545// GNU Hash table requirement: it should be a power of 2,
546// the minimum value is 1, even for an empty table.
547// Expected results for a 32-bit target:
548// calcMaskWords(0..4) = 1
549// calcMaskWords(5..8) = 2
550// calcMaskWords(9..16) = 4
551// For a 64-bit target:
552// calcMaskWords(0..8) = 1
553// calcMaskWords(9..16) = 2
554// calcMaskWords(17..32) = 4
555template <class ELFT>
556unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
557 if (!NumHashed)
558 return 1;
559 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
560}
561
562template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000563 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000564 NBuckets = calcNBuckets(NumHashed);
565 MaskWords = calcMaskWords(NumHashed);
566 // Second hash shift estimation: just predefined values.
567 Shift2 = ELFT::Is64Bits ? 6 : 5;
568
Rafael Espindola04a2e342016-11-09 01:42:41 +0000569 this->Link = Out<ELFT>::DynSymTab->SectionIndex;
570 this->Size = sizeof(Elf_Word) * 4 // Header
571 + sizeof(Elf_Off) * MaskWords // Bloom Filter
572 + sizeof(Elf_Word) * NBuckets // Hash Buckets
573 + sizeof(Elf_Word) * NumHashed; // Hash Values
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000574}
575
576template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
577 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000578 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000579 return;
580 writeBloomFilter(Buf);
581 writeHashTable(Buf);
582}
583
584template <class ELFT>
585void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
586 auto *P = reinterpret_cast<Elf_Word *>(Buf);
587 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000588 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000589 *P++ = MaskWords;
590 *P++ = Shift2;
591 Buf = reinterpret_cast<uint8_t *>(P);
592}
593
594template <class ELFT>
595void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
596 unsigned C = sizeof(Elf_Off) * 8;
597
598 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000599 for (const SymbolData &Sym : Symbols) {
600 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
601 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
602 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000603 Masks[Pos] |= V;
604 }
605 Buf += sizeof(Elf_Off) * MaskWords;
606}
607
608template <class ELFT>
609void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
610 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
611 Elf_Word *Values = Buckets + NBuckets;
612
613 int PrevBucket = -1;
614 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000615 for (const SymbolData &Sym : Symbols) {
616 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000617 assert(PrevBucket <= Bucket);
618 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000619 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000620 PrevBucket = Bucket;
621 if (I > 0)
622 Values[I - 1] |= 1;
623 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000624 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000625 ++I;
626 }
627 if (I > 0)
628 Values[I - 1] |= 1;
629}
630
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000631// Add symbols to this symbol hash table. Note that this function
632// destructively sort a given vector -- which is needed because
633// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000634template <class ELFT>
Michael J. Spencerf8a81482016-10-19 23:49:27 +0000635void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) {
Davide Italianob4b68b62016-07-04 19:49:55 +0000636 // Ideally this will just be 'auto' but GCC 6.1 is not able
637 // to deduce it correctly.
Michael J. Spencerf8a81482016-10-19 23:49:27 +0000638 std::vector<SymbolTableEntry>::iterator Mid =
639 std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
640 return S.Symbol->isUndefined();
641 });
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000642 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000643 return;
Davide Italianof8591cf2016-07-06 17:41:55 +0000644 for (auto I = Mid, E = V.end(); I != E; ++I) {
Michael J. Spencerf8a81482016-10-19 23:49:27 +0000645 SymbolBody *B = I->Symbol;
Reid Kleckner2918d0b2016-10-20 00:13:34 +0000646 size_t StrOff = I->StrTabOffset;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000647 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
648 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000649
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000650 unsigned NBuckets = calcNBuckets(Symbols.size());
651 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000652 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000653 return L.Hash % NBuckets < R.Hash % NBuckets;
654 });
655
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000656 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000657 for (const SymbolData &Sym : Symbols)
658 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000659}
660
George Rimard3566302016-06-20 11:55:12 +0000661// Returns the number of version definition entries. Because the first entry
662// is for the version definition itself, it is the number of versioned symbols
663// plus one. Note that we don't support multiple versions yet.
Rui Ueyamaaf469d42016-07-16 04:09:27 +0000664static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
George Rimard3566302016-06-20 11:55:12 +0000665
Igor Kudrinf1d60292015-10-28 07:05:56 +0000666template <class ELFT>
Rui Ueyamaace4f902016-05-24 04:25:47 +0000667DynamicSection<ELFT>::DynamicSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000668 : OutputSectionBase(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000669 this->Addralign = sizeof(uintX_t);
670 this->Entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000671
672 // .dynamic section is not writable on MIPS.
673 // See "Special Section" in Chapter 4 in the following document:
674 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
675 if (Config->EMachine == EM_MIPS)
Rafael Espindola04a2e342016-11-09 01:42:41 +0000676 this->Flags = SHF_ALLOC;
Rui Ueyamaa9593932016-11-02 02:18:01 +0000677
678 addEntries();
Rafael Espindola35c6af32015-09-25 17:19:10 +0000679}
680
Rui Ueyamaa9593932016-11-02 02:18:01 +0000681// There are some dynamic entries that don't depend on other sections.
682// Such entries can be set early.
683template <class ELFT> void DynamicSection<ELFT>::addEntries() {
684 // Add strings to .dynstr early so that .dynstr's size will be
685 // fixed early.
George Rimarb952ece2016-09-02 09:13:05 +0000686 for (StringRef S : Config->AuxiliaryList)
687 Add({DT_AUXILIARY, Out<ELFT>::DynStrTab->addString(S)});
Rafael Espindolade069362016-01-25 21:32:04 +0000688 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000689 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
690 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000691 for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles())
Rafael Espindolade069362016-01-25 21:32:04 +0000692 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000693 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
694 if (!Config->SoName.empty())
695 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
696
Rui Ueyamaa9593932016-11-02 02:18:01 +0000697 // Set DT_FLAGS and DT_FLAGS_1.
698 uint32_t DtFlags = 0;
699 uint32_t DtFlags1 = 0;
700 if (Config->Bsymbolic)
701 DtFlags |= DF_SYMBOLIC;
702 if (Config->ZNodelete)
703 DtFlags1 |= DF_1_NODELETE;
704 if (Config->ZNow) {
705 DtFlags |= DF_BIND_NOW;
706 DtFlags1 |= DF_1_NOW;
707 }
708 if (Config->ZOrigin) {
709 DtFlags |= DF_ORIGIN;
710 DtFlags1 |= DF_1_ORIGIN;
711 }
712
713 if (DtFlags)
714 Add({DT_FLAGS, DtFlags});
715 if (DtFlags1)
716 Add({DT_FLAGS_1, DtFlags1});
717
718 if (!Config->Entry.empty())
719 Add({DT_DEBUG, (uint64_t)0});
720}
721
722// Add remaining entries to complete .dynamic contents.
723template <class ELFT> void DynamicSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000724 if (this->Size)
Rui Ueyamaa9593932016-11-02 02:18:01 +0000725 return; // Already finalized.
726
Rafael Espindola04a2e342016-11-09 01:42:41 +0000727 this->Link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindolade069362016-01-25 21:32:04 +0000728
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000729 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000730 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000731 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
Rafael Espindola04a2e342016-11-09 01:42:41 +0000732 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->Size});
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000733 Add({IsRela ? DT_RELAENT : DT_RELENT,
734 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Eugene Leviantaa498192016-08-31 08:51:39 +0000735
Simon Atanasyan65b24612016-09-04 17:40:12 +0000736 // MIPS dynamic loader does not support RELCOUNT tag.
737 // The problem is in the tight relation between dynamic
738 // relocations and GOT. So do not emit this tag on MIPS.
739 if (Config->EMachine != EM_MIPS) {
740 size_t NumRelativeRels = Out<ELFT>::RelaDyn->getRelativeRelocCount();
741 if (Config->ZCombreloc && NumRelativeRels)
742 Add({IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels});
743 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000744 }
George Rimar648a2c32015-10-20 08:54:27 +0000745 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000746 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
Rafael Espindola04a2e342016-11-09 01:42:41 +0000747 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->Size});
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000748 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
Eugene Leviant41ca3272016-11-10 09:48:29 +0000749 In<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000750 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000751 }
752
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000753 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
754 Add({DT_SYMENT, sizeof(Elf_Sym)});
755 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
Rafael Espindola04a2e342016-11-09 01:42:41 +0000756 Add({DT_STRSZ, Out<ELFT>::DynStrTab->Size});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000757 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000758 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000759 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000760 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000761
Rui Ueyamaa8f6fea2016-08-09 04:25:20 +0000762 if (Out<ELFT>::PreinitArray) {
763 Add({DT_PREINIT_ARRAY, Out<ELFT>::PreinitArray});
George Rimar03e05602016-08-19 15:23:39 +0000764 Add({DT_PREINIT_ARRAYSZ, Out<ELFT>::PreinitArray, Entry::SecSize});
Rafael Espindolade069362016-01-25 21:32:04 +0000765 }
Rui Ueyamaa8f6fea2016-08-09 04:25:20 +0000766 if (Out<ELFT>::InitArray) {
767 Add({DT_INIT_ARRAY, Out<ELFT>::InitArray});
George Rimar03e05602016-08-19 15:23:39 +0000768 Add({DT_INIT_ARRAYSZ, Out<ELFT>::InitArray, Entry::SecSize});
Rafael Espindolade069362016-01-25 21:32:04 +0000769 }
Rui Ueyamaa8f6fea2016-08-09 04:25:20 +0000770 if (Out<ELFT>::FiniArray) {
771 Add({DT_FINI_ARRAY, Out<ELFT>::FiniArray});
George Rimar03e05602016-08-19 15:23:39 +0000772 Add({DT_FINI_ARRAYSZ, Out<ELFT>::FiniArray, Entry::SecSize});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000773 }
774
Rui Ueyamaace4f902016-05-24 04:25:47 +0000775 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000776 Add({DT_INIT, B});
Rui Ueyamaace4f902016-05-24 04:25:47 +0000777 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000778 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000779
George Rimard3566302016-06-20 11:55:12 +0000780 bool HasVerNeed = Out<ELFT>::VerNeed->getNeedNum() != 0;
781 if (HasVerNeed || Out<ELFT>::VerDef)
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000782 Add({DT_VERSYM, Out<ELFT>::VerSym});
George Rimard3566302016-06-20 11:55:12 +0000783 if (Out<ELFT>::VerDef) {
784 Add({DT_VERDEF, Out<ELFT>::VerDef});
785 Add({DT_VERDEFNUM, getVerDefNum()});
786 }
787 if (HasVerNeed) {
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000788 Add({DT_VERNEED, Out<ELFT>::VerNeed});
George Rimard3566302016-06-20 11:55:12 +0000789 Add({DT_VERNEEDNUM, Out<ELFT>::VerNeed->getNeedNum()});
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000790 }
791
Igor Kudrin304860a2015-11-12 04:39:49 +0000792 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000793 Add({DT_MIPS_RLD_VERSION, 1});
794 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
Rui Ueyamacafc0f2e2016-07-14 17:40:18 +0000795 Add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000796 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
797 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000798 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000799 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000800 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000801 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
802 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000803 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000804 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000805 }
806
Rafael Espindolade069362016-01-25 21:32:04 +0000807 // +1 for DT_NULL
Rafael Espindola04a2e342016-11-09 01:42:41 +0000808 this->Size = (Entries.size() + 1) * this->Entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000809}
810
811template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000812 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
813
Rafael Espindolade069362016-01-25 21:32:04 +0000814 for (const Entry &E : Entries) {
815 P->d_tag = E.Tag;
816 switch (E.Kind) {
817 case Entry::SecAddr:
Rafael Espindola04a2e342016-11-09 01:42:41 +0000818 P->d_un.d_ptr = E.OutSec->Addr;
Rafael Espindolade069362016-01-25 21:32:04 +0000819 break;
Eugene Leviant41ca3272016-11-10 09:48:29 +0000820 case Entry::InSecAddr:
821 P->d_un.d_ptr = E.InSec->OutSec->Addr + E.InSec->OutSecOff;
822 break;
George Rimar03e05602016-08-19 15:23:39 +0000823 case Entry::SecSize:
Rafael Espindola04a2e342016-11-09 01:42:41 +0000824 P->d_un.d_val = E.OutSec->Size;
George Rimar03e05602016-08-19 15:23:39 +0000825 break;
Rafael Espindolade069362016-01-25 21:32:04 +0000826 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000827 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000828 break;
829 case Entry::PlainInt:
830 P->d_un.d_val = E.Val;
831 break;
832 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000833 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000834 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000835}
836
837template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000838EhFrameHeader<ELFT>::EhFrameHeader()
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000839 : OutputSectionBase(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
George Rimarf6bc65a2016-01-15 13:34:52 +0000840
Rui Ueyama95a232e2016-05-23 01:45:05 +0000841// .eh_frame_hdr contains a binary search table of pointers to FDEs.
842// Each entry of the search table consists of two values,
843// the starting PC from where FDEs covers, and the FDE's address.
844// It is sorted by PC.
George Rimarf6bc65a2016-01-15 13:34:52 +0000845template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
846 const endianness E = ELFT::TargetEndianness;
847
Rui Ueyamae75e9332016-05-23 03:00:33 +0000848 // Sort the FDE list by their PC and uniqueify. Usually there is only
849 // one FDE for a PC (i.e. function), but if ICF merges two functions
850 // into one, there can be more than one FDEs pointing to the address.
851 auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
852 std::stable_sort(Fdes.begin(), Fdes.end(), Less);
853 auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
854 Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
Peter Collingbournec98de132016-04-11 16:40:08 +0000855
Rui Ueyama1b2936f2016-05-23 01:31:10 +0000856 Buf[0] = 1;
857 Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
858 Buf[2] = DW_EH_PE_udata4;
859 Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000860 write32<E>(Buf + 4, Out<ELFT>::EhFrame->Addr - this->Addr - 4);
Rui Ueyamae75e9332016-05-23 03:00:33 +0000861 write32<E>(Buf + 8, Fdes.size());
George Rimarf6bc65a2016-01-15 13:34:52 +0000862 Buf += 12;
863
Rafael Espindola04a2e342016-11-09 01:42:41 +0000864 uintX_t VA = this->Addr;
Rui Ueyamae75e9332016-05-23 03:00:33 +0000865 for (FdeData &Fde : Fdes) {
866 write32<E>(Buf, Fde.Pc - VA);
867 write32<E>(Buf + 4, Fde.FdeVA - VA);
George Rimarf6bc65a2016-01-15 13:34:52 +0000868 Buf += 8;
869 }
870}
871
Rui Ueyamade9777a2016-05-23 16:30:41 +0000872template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
873 // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000874 this->Size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
Rui Ueyamade9777a2016-05-23 16:30:41 +0000875}
876
George Rimarf6bc65a2016-01-15 13:34:52 +0000877template <class ELFT>
Rui Ueyamae75e9332016-05-23 03:00:33 +0000878void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
879 Fdes.push_back({Pc, FdeVA});
George Rimarf6bc65a2016-01-15 13:34:52 +0000880}
881
Rui Ueyamadf5d14d2016-11-09 22:32:42 +0000882template <class ELFT> static uint64_t getEntsize(uint32_t Type) {
883 switch (Type) {
884 case SHT_RELA:
885 return sizeof(typename ELFT::Rela);
886 case SHT_REL:
887 return sizeof(typename ELFT::Rel);
888 case SHT_MIPS_REGINFO:
889 return sizeof(Elf_Mips_RegInfo<ELFT>);
890 case SHT_MIPS_OPTIONS:
891 return sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
892 case SHT_MIPS_ABIFLAGS:
893 return sizeof(Elf_Mips_ABIFlags<ELFT>);
894 default:
895 return 0;
896 }
897}
898
George Rimarf6bc65a2016-01-15 13:34:52 +0000899template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000900OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000901 : OutputSectionBase(Name, Type, Flags) {
Rui Ueyamadf5d14d2016-11-09 22:32:42 +0000902 this->Entsize = getEntsize<ELFT>(Type);
George Rimar58941ee2016-02-25 08:23:37 +0000903}
904
905template <class ELFT> void OutputSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000906 uint32_t Type = this->Type;
907 if (this->Flags & SHF_LINK_ORDER) {
Peter Smith580ba952016-10-21 11:25:33 +0000908 if (!Config->Relocatable) {
909 // SHF_LINK_ORDER only has meaning in relocatable objects
Rafael Espindola04a2e342016-11-09 01:42:41 +0000910 this->Flags &= ~SHF_LINK_ORDER;
Peter Smith580ba952016-10-21 11:25:33 +0000911 }
912 else if (!this->Sections.empty()) {
913 // When doing a relocatable link we must preserve the link order
914 // dependency of sections with the SHF_LINK_ORDER flag. The dependency
915 // is indicated by the sh_link field. We need to translate the
916 // InputSection sh_link to the OutputSection sh_link, all InputSections
917 // in the OutputSection have the same dependency.
918 if (auto *D = this->Sections.front()->getLinkOrderDep())
Rafael Espindola04a2e342016-11-09 01:42:41 +0000919 this->Link = D->OutSec->SectionIndex;
Peter Smith580ba952016-10-21 11:25:33 +0000920 }
921 }
George Rimar58941ee2016-02-25 08:23:37 +0000922 if (Type != SHT_RELA && Type != SHT_REL)
923 return;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000924 this->Link = Out<ELFT>::SymTab->SectionIndex;
George Rimar58941ee2016-02-25 08:23:37 +0000925 // sh_info for SHT_REL[A] sections should contain the section header index of
926 // the section to which the relocation applies.
927 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
Rafael Espindola04a2e342016-11-09 01:42:41 +0000928 this->Info = S->OutSec->SectionIndex;
George Rimar58941ee2016-02-25 08:23:37 +0000929}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000930
931template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000932void OutputSection<ELFT>::addSection(InputSectionData *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000933 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000934 auto *S = cast<InputSection<ELFT>>(C);
935 Sections.push_back(S);
936 S->OutSec = this;
Rui Ueyama424b4082016-06-17 01:18:46 +0000937 this->updateAlignment(S->Alignment);
Simon Atanasyan02b9c3f2016-10-05 07:49:18 +0000938 // Keep sh_entsize value of the input section to be able to perform merging
939 // later during a final linking using the generated relocatable object.
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000940 if (Config->Relocatable && (S->Flags & SHF_MERGE))
Rafael Espindola04a2e342016-11-09 01:42:41 +0000941 this->Entsize = S->Entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000942}
943
Rui Ueyama809d8e22016-06-23 04:33:42 +0000944// This function is called after we sort input sections
945// and scan relocations to setup sections' offsets.
946template <class ELFT> void OutputSection<ELFT>::assignOffsets() {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000947 uintX_t Off = this->Size;
Rui Ueyama809d8e22016-06-23 04:33:42 +0000948 for (InputSection<ELFT> *S : Sections) {
949 Off = alignTo(Off, S->Alignment);
950 S->OutSecOff = Off;
951 Off += S->getSize();
952 }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000953 this->Size = Off;
Rui Ueyama5af83682016-02-11 23:41:38 +0000954}
955
George Rimar1a33c0f2016-11-10 09:05:20 +0000956template <class ELFT>
957void OutputSection<ELFT>::sort(
958 std::function<unsigned(InputSection<ELFT> *S)> Order) {
959 typedef std::pair<unsigned, InputSection<ELFT> *> Pair;
960 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
961
962 std::vector<Pair> V;
963 for (InputSection<ELFT> *S : Sections)
964 V.push_back({Order(S), S});
965 std::stable_sort(V.begin(), V.end(), Comp);
966 Sections.clear();
967 for (Pair &P : V)
968 Sections.push_back(P.second);
969}
970
Rui Ueyamac4185702016-02-10 23:20:42 +0000971// Sorts input sections by section name suffixes, so that .foo.N comes
972// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000973// We want to keep the original order if the priorities are the same
974// because the compiler keeps the original initialization order in a
975// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000976// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000977template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000978 // Sort sections by priority.
George Rimar1a33c0f2016-11-10 09:05:20 +0000979 sort([](InputSection<ELFT> *S) { return getPriority(S->Name); });
Rui Ueyama5af83682016-02-11 23:41:38 +0000980}
Rui Ueyamac4185702016-02-10 23:20:42 +0000981
Rui Ueyama5af83682016-02-11 23:41:38 +0000982// Returns true if S matches /Filename.?\.o$/.
983static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
984 if (!S.endswith(".o"))
985 return false;
986 S = S.drop_back(2);
987 if (S.endswith(Filename))
988 return true;
989 return !S.empty() && S.drop_back().endswith(Filename);
990}
991
992static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
993static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
994
995// .ctors and .dtors are sorted by this priority from highest to lowest.
996//
997// 1. The section was contained in crtbegin (crtbegin contains
998// some sentinel value in its .ctors and .dtors so that the runtime
999// can find the beginning of the sections.)
1000//
1001// 2. The section has an optional priority value in the form of ".ctors.N"
1002// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
1003// they are compared as string rather than number.
1004//
1005// 3. The section is just ".ctors" or ".dtors".
1006//
1007// 4. The section was contained in crtend, which contains an end marker.
1008//
1009// In an ideal world, we don't need this function because .init_array and
1010// .ctors are duplicate features (and .init_array is newer.) However, there
1011// are too many real-world use cases of .ctors, so we had no choice to
1012// support that with this rather ad-hoc semantics.
1013template <class ELFT>
1014static bool compCtors(const InputSection<ELFT> *A,
1015 const InputSection<ELFT> *B) {
1016 bool BeginA = isCrtbegin(A->getFile()->getName());
1017 bool BeginB = isCrtbegin(B->getFile()->getName());
1018 if (BeginA != BeginB)
1019 return BeginA;
1020 bool EndA = isCrtend(A->getFile()->getName());
1021 bool EndB = isCrtend(B->getFile()->getName());
1022 if (EndA != EndB)
1023 return EndB;
Rafael Espindola042a3f22016-09-08 14:06:08 +00001024 StringRef X = A->Name;
1025 StringRef Y = B->Name;
Rui Ueyama5af83682016-02-11 23:41:38 +00001026 assert(X.startswith(".ctors") || X.startswith(".dtors"));
1027 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
1028 X = X.substr(6);
1029 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +00001030 if (X.empty() && Y.empty())
1031 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +00001032 return X < Y;
1033}
1034
1035// Sorts input sections by the special rules for .ctors and .dtors.
1036// Unfortunately, the rules are different from the one for .{init,fini}_array.
1037// Read the comment above.
1038template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
1039 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +00001040}
1041
George Rimare2ee72b2016-02-26 14:48:31 +00001042static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
1043 size_t I = 0;
1044 for (; I + A.size() < Size; I += A.size())
1045 memcpy(Buf + I, A.data(), A.size());
1046 memcpy(Buf + I, A.data(), Size - I);
1047}
1048
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001049template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama07320e42016-04-20 20:13:41 +00001050 ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
George Rimare2ee72b2016-02-26 14:48:31 +00001051 if (!Filler.empty())
Rafael Espindola04a2e342016-11-09 01:42:41 +00001052 fill(Buf, this->Size, Filler);
Rui Ueyamaeb943e82016-11-04 18:22:36 +00001053 if (Config->Threads) {
1054 parallel_for_each(Sections.begin(), Sections.end(),
1055 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
1056 } else {
1057 for (InputSection<ELFT> *C : Sections)
1058 C->writeTo(Buf);
1059 }
George Rimare38cbab2016-09-26 19:22:50 +00001060 // Linker scripts may have BYTE()-family commands with which you
1061 // can write arbitrary bytes to the output. Process them if any.
1062 Script<ELFT>::X->writeDataBytes(this->Name, Buf);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001063}
1064
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001065template <class ELFT>
Rui Ueyamaf86cb902016-05-23 15:12:41 +00001066EhOutputSection<ELFT>::EhOutputSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001067 : OutputSectionBase(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001068
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001069// Search for an existing CIE record or create a new one.
1070// CIE records from input object files are uniquified by their contents
1071// and where their relocations point to.
1072template <class ELFT>
1073template <class RelTy>
Rafael Espindola2deeb602016-07-21 20:18:30 +00001074CieRecord *EhOutputSection<ELFT>::addCie(EhSectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001075 EhInputSection<ELFT> *Sec,
Rafael Espindola2deeb602016-07-21 20:18:30 +00001076 ArrayRef<RelTy> Rels) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001077 const endianness E = ELFT::TargetEndianness;
Rui Ueyamad8849272016-05-25 16:37:01 +00001078 if (read32<E>(Piece.data().data() + 4) != 0)
Rafael Espindola042a3f22016-09-08 14:06:08 +00001079 fatal("CIE expected at beginning of .eh_frame: " + Sec->Name);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001080
1081 SymbolBody *Personality = nullptr;
Rafael Espindola2deeb602016-07-21 20:18:30 +00001082 unsigned FirstRelI = Piece.FirstRelocation;
1083 if (FirstRelI != (unsigned)-1)
1084 Personality = &Sec->getFile()->getRelocTargetSym(Rels[FirstRelI]);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001085
1086 // Search for an existing CIE by CIE contents/relocation target pair.
Rui Ueyamad8849272016-05-25 16:37:01 +00001087 CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001088
1089 // If not found, create a new one.
Rui Ueyamae2060aa2016-05-22 23:52:56 +00001090 if (Cie->Piece == nullptr) {
1091 Cie->Piece = &Piece;
Rui Ueyamae2060aa2016-05-22 23:52:56 +00001092 Cies.push_back(Cie);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001093 }
1094 return Cie;
1095}
1096
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001097// There is one FDE per function. Returns true if a given FDE
1098// points to a live function.
1099template <class ELFT>
1100template <class RelTy>
Rafael Espindola2deeb602016-07-21 20:18:30 +00001101bool EhOutputSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001102 EhInputSection<ELFT> *Sec,
Rafael Espindola2deeb602016-07-21 20:18:30 +00001103 ArrayRef<RelTy> Rels) {
1104 unsigned FirstRelI = Piece.FirstRelocation;
1105 if (FirstRelI == (unsigned)-1)
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001106 fatal("FDE doesn't reference another section");
Rafael Espindola2deeb602016-07-21 20:18:30 +00001107 const RelTy &Rel = Rels[FirstRelI];
1108 SymbolBody &B = Sec->getFile()->getRelocTargetSym(Rel);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001109 auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
1110 if (!D || !D->Section)
1111 return false;
1112 InputSectionBase<ELFT> *Target = D->Section->Repl;
1113 return Target && Target->Live;
1114}
1115
1116// .eh_frame is a sequence of CIE or FDE records. In general, there
1117// is one CIE record per input object file which is followed by
1118// a list of FDEs. This function searches an existing CIE or create a new
1119// one and associates FDEs to the CIE.
Rui Ueyamac0c92602016-02-05 22:56:03 +00001120template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +00001121template <class RelTy>
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001122void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +00001123 ArrayRef<RelTy> Rels) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001124 const endianness E = ELFT::TargetEndianness;
Rafael Espindola820f4bb2016-05-24 15:17:47 +00001125
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001126 DenseMap<size_t, CieRecord *> OffsetToCie;
Rafael Espindola2deeb602016-07-21 20:18:30 +00001127 for (EhSectionPiece &Piece : Sec->Pieces) {
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001128 // The empty record is the end marker.
Rui Ueyamad8849272016-05-25 16:37:01 +00001129 if (Piece.size() == 4)
Rafael Espindola5ee9e7f2016-05-24 19:14:09 +00001130 return;
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001131
1132 size_t Offset = Piece.InputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001133 uint32_t ID = read32<E>(Piece.data().data() + 4);
Rafael Espindola1f5696f2016-05-24 16:03:27 +00001134 if (ID == 0) {
1135 OffsetToCie[Offset] = addCie(Piece, Sec, Rels);
1136 continue;
1137 }
1138
1139 uint32_t CieOffset = Offset + 4 - ID;
1140 CieRecord *Cie = OffsetToCie[CieOffset];
1141 if (!Cie)
1142 fatal("invalid CIE reference");
1143
1144 if (!isFdeLive(Piece, Sec, Rels))
1145 continue;
1146 Cie->FdePieces.push_back(&Piece);
Rui Ueyamade9777a2016-05-23 16:30:41 +00001147 NumFdes++;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001148 }
1149}
1150
1151template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001152void EhOutputSection<ELFT>::addSection(InputSectionData *C) {
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001153 auto *Sec = cast<EhInputSection<ELFT>>(C);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001154 Sec->OutSec = this;
Rui Ueyama424b4082016-06-17 01:18:46 +00001155 this->updateAlignment(Sec->Alignment);
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001156 Sections.push_back(Sec);
1157
1158 // .eh_frame is a sequence of CIE or FDE records. This function
1159 // splits it into pieces so that we can call
1160 // SplitInputSection::getSectionPiece on the section.
Rui Ueyama88abd9b2016-05-22 23:53:00 +00001161 Sec->split();
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001162 if (Sec->Pieces.empty())
1163 return;
1164
1165 if (const Elf_Shdr *RelSec = Sec->RelocSection) {
Rafael Espindolae19abab2016-11-03 20:44:50 +00001166 ELFFile<ELFT> Obj = Sec->getFile()->getObj();
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001167 if (RelSec->sh_type == SHT_RELA)
Rafael Espindola454fe152016-11-03 19:07:44 +00001168 addSectionAux(Sec, check(Obj.relas(RelSec)));
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001169 else
Rafael Espindola454fe152016-11-03 19:07:44 +00001170 addSectionAux(Sec, check(Obj.rels(RelSec)));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001171 return;
1172 }
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001173 addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001174}
1175
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001176template <class ELFT>
Rui Ueyama644ac652016-05-22 00:17:11 +00001177static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1178 memcpy(Buf, D.data(), D.size());
Rui Ueyamac0449a62016-05-21 18:10:13 +00001179
1180 // Fix the size field. -4 since size does not include the size field itself.
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001181 const endianness E = ELFT::TargetEndianness;
Rui Ueyama644ac652016-05-22 00:17:11 +00001182 write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
Rafael Espindola56004c52016-04-07 14:22:09 +00001183}
1184
Rui Ueyama1e479c22016-05-23 15:07:59 +00001185template <class ELFT> void EhOutputSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001186 if (this->Size)
Rui Ueyamae9381bd2016-07-16 02:47:42 +00001187 return; // Already finalized.
Rafael Espindola56004c52016-04-07 14:22:09 +00001188
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001189 size_t Off = 0;
1190 for (CieRecord *Cie : Cies) {
1191 Cie->Piece->OutputOff = Off;
1192 Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001193
Rafael Espindola113860b2016-10-20 10:55:58 +00001194 for (EhSectionPiece *Fde : Cie->FdePieces) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001195 Fde->OutputOff = Off;
1196 Off += alignTo(Fde->size(), sizeof(uintX_t));
Rafael Espindola56004c52016-04-07 14:22:09 +00001197 }
1198 }
Rafael Espindola04a2e342016-11-09 01:42:41 +00001199 this->Size = Off;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001200}
1201
Rui Ueyamae75e9332016-05-23 03:00:33 +00001202template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1203 const endianness E = ELFT::TargetEndianness;
1204 switch (Size) {
1205 case DW_EH_PE_udata2:
1206 return read16<E>(Buf);
1207 case DW_EH_PE_udata4:
1208 return read32<E>(Buf);
1209 case DW_EH_PE_udata8:
1210 return read64<E>(Buf);
1211 case DW_EH_PE_absptr:
1212 if (ELFT::Is64Bits)
1213 return read64<E>(Buf);
1214 return read32<E>(Buf);
1215 }
1216 fatal("unknown FDE size encoding");
1217}
1218
1219// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1220// We need it to create .eh_frame_hdr section.
1221template <class ELFT>
Rui Ueyama1e479c22016-05-23 15:07:59 +00001222typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
Rui Ueyamae75e9332016-05-23 03:00:33 +00001223 uint8_t Enc) {
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001224 // The starting address to which this FDE applies is
Rui Ueyamae75e9332016-05-23 03:00:33 +00001225 // stored at FDE + 8 byte.
1226 size_t Off = FdeOff + 8;
1227 uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1228 if ((Enc & 0x70) == DW_EH_PE_absptr)
1229 return Addr;
1230 if ((Enc & 0x70) == DW_EH_PE_pcrel)
Rafael Espindola04a2e342016-11-09 01:42:41 +00001231 return Addr + this->Addr + Off;
Rui Ueyamae75e9332016-05-23 03:00:33 +00001232 fatal("unknown FDE size relative encoding");
1233}
1234
Rui Ueyama1e479c22016-05-23 15:07:59 +00001235template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001236 const endianness E = ELFT::TargetEndianness;
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001237 for (CieRecord *Cie : Cies) {
1238 size_t CieOffset = Cie->Piece->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001239 writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001240
Rafael Espindola32aca872016-10-05 18:40:00 +00001241 for (EhSectionPiece *Fde : Cie->FdePieces) {
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001242 size_t Off = Fde->OutputOff;
Rui Ueyamad8849272016-05-25 16:37:01 +00001243 writeCieFde<ELFT>(Buf + Off, Fde->data());
Rafael Espindola56004c52016-04-07 14:22:09 +00001244
Rui Ueyamaf8b285c2016-05-22 23:16:14 +00001245 // FDE's second word should have the offset to an associated CIE.
1246 // Write it.
1247 write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001248 }
1249 }
1250
Rui Ueyama0b9a9032016-05-24 04:19:20 +00001251 for (EhInputSection<ELFT> *S : Sections)
Rafael Espindola22ef9562016-04-13 01:40:19 +00001252 S->relocate(Buf, nullptr);
Rui Ueyamae75e9332016-05-23 03:00:33 +00001253
1254 // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
Rui Ueyama2ab3d202016-05-23 16:36:47 +00001255 // to get a FDE from an address to which FDE is applied. So here
Rui Ueyamae75e9332016-05-23 03:00:33 +00001256 // we obtain two addresses and pass them to EhFrameHdr object.
Rui Ueyama3b31e672016-05-23 16:24:16 +00001257 if (Out<ELFT>::EhFrameHdr) {
1258 for (CieRecord *Cie : Cies) {
Rui Ueyamad8849272016-05-25 16:37:01 +00001259 uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->data());
Rui Ueyama3b31e672016-05-23 16:24:16 +00001260 for (SectionPiece *Fde : Cie->FdePieces) {
Rui Ueyama6de2e682016-05-24 02:08:38 +00001261 uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001262 uintX_t FdeVA = this->Addr + Fde->OutputOff;
Rui Ueyama3b31e672016-05-23 16:24:16 +00001263 Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1264 }
Rui Ueyamae75e9332016-05-23 03:00:33 +00001265 }
1266 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001267}
1268
1269template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001270MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001271 uintX_t Flags, uintX_t Alignment)
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001272 : OutputSectionBase(Name, Type, Flags),
Rui Ueyama818bb2f2016-07-16 18:55:47 +00001273 Builder(StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001274
1275template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola259d6452016-10-04 22:43:38 +00001276 Builder.write(Buf);
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001277}
1278
Rafael Espindolac159c962015-10-19 21:00:02 +00001279template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001280void MergeOutputSection<ELFT>::addSection(InputSectionData *C) {
Rui Ueyama10803512016-05-22 00:25:30 +00001281 auto *Sec = cast<MergeInputSection<ELFT>>(C);
1282 Sec->OutSec = this;
Rui Ueyama424b4082016-06-17 01:18:46 +00001283 this->updateAlignment(Sec->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001284 this->Entsize = Sec->Entsize;
Rui Ueyama406b4692016-05-27 14:39:13 +00001285 Sections.push_back(Sec);
Rafael Espindolac159c962015-10-19 21:00:02 +00001286
Rafael Espindola113860b2016-10-20 10:55:58 +00001287 auto HashI = Sec->Hashes.begin();
1288 for (auto I = Sec->Pieces.begin(), E = Sec->Pieces.end(); I != E; ++I) {
1289 SectionPiece &Piece = *I;
1290 uint32_t Hash = *HashI;
1291 ++HashI;
Rui Ueyama3ea87272016-05-22 00:13:04 +00001292 if (!Piece.Live)
Rafael Espindola0b9531c2016-04-22 22:09:35 +00001293 continue;
Rafael Espindola113860b2016-10-20 10:55:58 +00001294 StringRef Data = toStringRef(Sec->getData(I));
1295 CachedHashStringRef V(Data, Hash);
Rafael Espindola5fc2b1d2016-10-05 19:36:02 +00001296 uintX_t OutputOffset = Builder.add(V);
Rafael Espindola7b8bb532016-10-05 15:35:18 +00001297 if (!shouldTailMerge())
Rui Ueyamac6ebb022016-05-22 01:03:41 +00001298 Piece.OutputOff = OutputOffset;
Rafael Espindolac159c962015-10-19 21:00:02 +00001299 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001300}
1301
1302template <class ELFT>
Justin Lebaree34a732016-10-17 22:24:36 +00001303unsigned MergeOutputSection<ELFT>::getOffset(CachedHashStringRef Val) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001304 return Builder.getOffset(Val);
1305}
1306
1307template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001308 return Config->Optimize >= 2 && this->Flags & SHF_STRINGS;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001309}
1310
1311template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1312 if (shouldTailMerge())
1313 Builder.finalize();
Rafael Espindola259d6452016-10-04 22:43:38 +00001314 else
1315 Builder.finalizeInOrder();
Rafael Espindola04a2e342016-11-09 01:42:41 +00001316 this->Size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001317}
1318
Rui Ueyama406b4692016-05-27 14:39:13 +00001319template <class ELFT> void MergeOutputSection<ELFT>::finalizePieces() {
1320 for (MergeInputSection<ELFT> *Sec : Sections)
1321 Sec->finalizePieces();
1322}
1323
Rafael Espindolac159c962015-10-19 21:00:02 +00001324template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001325StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001326 : OutputSectionBase(Name, SHT_STRTAB, Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola08113852016-11-08 20:25:44 +00001327 Dynamic(Dynamic) {
1328 // ELF string tables start with a NUL byte, so 1.
Rafael Espindola04a2e342016-11-09 01:42:41 +00001329 this->Size = 1;
Rafael Espindola08113852016-11-08 20:25:44 +00001330}
Rafael Espindola35c6af32015-09-25 17:19:10 +00001331
Rafael Espindolae2c24612016-01-29 01:24:25 +00001332// Adds a string to the string table. If HashIt is true we hash and check for
1333// duplicates. It is optional because the name of global symbols are already
1334// uniqued and hashing them again has a big cost for a small value: uniquing
1335// them with some other string that happens to be the same.
1336template <class ELFT>
1337unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1338 if (HashIt) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001339 auto R = StringMap.insert(std::make_pair(S, this->Size));
Rafael Espindolae2c24612016-01-29 01:24:25 +00001340 if (!R.second)
1341 return R.first->second;
1342 }
Rafael Espindola04a2e342016-11-09 01:42:41 +00001343 unsigned Ret = this->Size;
1344 this->Size = this->Size + S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001345 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001346 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001347}
1348
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001349template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001350 // ELF string tables start with NUL byte, so advance the pointer by one.
1351 ++Buf;
1352 for (StringRef S : Strings) {
1353 memcpy(Buf, S.data(), S.size());
1354 Buf += S.size() + 1;
1355 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001356}
1357
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001358template <class ELFT>
Rui Ueyama809d8e22016-06-23 04:33:42 +00001359typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
1360 if (OutputSec)
Rafael Espindola04a2e342016-11-09 01:42:41 +00001361 return OutputSec->Addr + OffsetInSec;
1362 return InputSec->OutSec->Addr + InputSec->getOffset(OffsetInSec);
Rui Ueyama809d8e22016-06-23 04:33:42 +00001363}
1364
1365template <class ELFT>
1366typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
1367 if (UseSymVA)
1368 return Sym->getVA<ELFT>(Addend);
1369 return Addend;
1370}
1371
1372template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
1373 if (Sym && !UseSymVA)
1374 return Sym->DynsymIndex;
1375 return 0;
1376}
1377
1378template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001379SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamaace4f902016-05-24 04:25:47 +00001380 StringTableSection<ELFT> &StrTabSec)
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001381 : OutputSectionBase(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1382 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1383 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rui Ueyamaace4f902016-05-24 04:25:47 +00001384 StrTabSec(StrTabSec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001385 this->Entsize = sizeof(Elf_Sym);
1386 this->Addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001387}
1388
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001389// Orders symbols according to their positions in the GOT,
1390// in compliance with MIPS ABI rules.
1391// See "Global Offset Table" in Chapter 5 in the following document
1392// for detailed description:
1393// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001394static bool sortMipsSymbols(const SymbolBody *L, const SymbolBody *R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001395 // Sort entries related to non-local preemptible symbols by GOT indexes.
1396 // All other entries go to the first part of GOT in arbitrary order.
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001397 bool LIsInLocalGot = !L->IsInGlobalMipsGot;
1398 bool RIsInLocalGot = !R->IsInGlobalMipsGot;
Simon Atanasyan7b8481b2016-06-20 11:37:56 +00001399 if (LIsInLocalGot || RIsInLocalGot)
1400 return !RIsInLocalGot;
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001401 return L->GotIndex < R->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001402}
1403
Rafael Espindolabadd3972016-04-08 15:30:56 +00001404static uint8_t getSymbolBinding(SymbolBody *Body) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001405 Symbol *S = Body->symbol();
George Rimar11f83b72016-08-19 08:31:02 +00001406 if (Config->Relocatable)
1407 return S->Binding;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001408 uint8_t Visibility = S->Visibility;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001409 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1410 return STB_LOCAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001411 if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
Rafael Espindolabadd3972016-04-08 15:30:56 +00001412 return STB_GLOBAL;
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001413 return S->Binding;
Rafael Espindolabadd3972016-04-08 15:30:56 +00001414}
1415
Rui Ueyama0db335f2015-10-07 16:58:54 +00001416template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001417 if (this->Size)
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001418 return; // Already finalized.
1419
Rafael Espindola04a2e342016-11-09 01:42:41 +00001420 this->Size = getNumSymbols() * sizeof(Elf_Sym);
1421 this->Link = StrTabSec.SectionIndex;
1422 this->Info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001423
George Rimar58941ee2016-02-25 08:23:37 +00001424 if (Config->Relocatable) {
1425 size_t I = NumLocals;
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001426 for (const SymbolTableEntry &S : Symbols)
1427 S.Symbol->DynsymIndex = ++I;
George Rimar58941ee2016-02-25 08:23:37 +00001428 return;
1429 }
1430
Igor Kudrinab665fc2015-10-20 21:47:58 +00001431 if (!StrTabSec.isDynamic()) {
1432 std::stable_sort(Symbols.begin(), Symbols.end(),
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001433 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1434 return getSymbolBinding(L.Symbol) == STB_LOCAL &&
1435 getSymbolBinding(R.Symbol) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001436 });
1437 return;
1438 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001439 if (Out<ELFT>::GnuHashTab)
1440 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1441 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001442 else if (Config->EMachine == EM_MIPS)
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001443 std::stable_sort(Symbols.begin(), Symbols.end(),
1444 [](const SymbolTableEntry &L, const SymbolTableEntry &R) {
1445 return sortMipsSymbols(L.Symbol, R.Symbol);
1446 });
Igor Kudrinab665fc2015-10-20 21:47:58 +00001447 size_t I = 0;
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001448 for (const SymbolTableEntry &S : Symbols)
1449 S.Symbol->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001450}
1451
George Rimara4c7e742016-10-20 08:36:42 +00001452template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001453 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001454}
1455
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001456template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001457 Buf += sizeof(Elf_Sym);
1458
1459 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1460 // .dynsym only contains global symbols.
George Rimar9503f6d2016-08-31 08:46:30 +00001461 if (Config->Discard != DiscardPolicy::All && !StrTabSec.isDynamic())
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001462 writeLocalSymbols(Buf);
1463
1464 writeGlobalSymbols(Buf);
1465}
1466
1467template <class ELFT>
1468void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1469 // Iterate over all input object files to copy their local symbols
1470 // to the output symbol table pointed by Buf.
Rui Ueyama38dbd3e2016-09-14 00:05:51 +00001471 for (ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001472 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1473 File->KeptLocalSyms) {
1474 const DefinedRegular<ELFT> &Body = *P.first;
1475 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001476 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001477
1478 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001479 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001480 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001481 } else {
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001482 const OutputSectionBase *OutSec = Section->OutSec;
Rafael Espindolac159c962015-10-19 21:00:02 +00001483 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola04a2e342016-11-09 01:42:41 +00001484 ESym->st_value = OutSec->Addr + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001485 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001486 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001487 ESym->st_size = Body.template getSize<ELFT>();
Rafael Espindola9e32e4f2016-04-26 13:50:46 +00001488 ESym->setBindingAndType(STB_LOCAL, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001489 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001490 }
1491 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001492}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001493
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001494template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001495void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001496 // Write the internal symbol table contents to the output symbol table
1497 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001498 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001499 for (const SymbolTableEntry &S : Symbols) {
1500 SymbolBody *Body = S.Symbol;
1501 size_t StrOff = S.StrTabOffset;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001502
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001503 uint8_t Type = Body->Type;
1504 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001505
Igor Kudrin853b88d2015-10-20 20:52:14 +00001506 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001507 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001508 ESym->st_name = StrOff;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001509 ESym->setVisibility(Body->symbol()->Visibility);
Rui Ueyamab5a69702016-02-01 21:00:35 +00001510 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001511
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001512 if (const OutputSectionBase *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001513 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001514 else if (isa<DefinedRegular<ELFT>>(Body))
1515 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001516
Simon Atanasyanf967f092016-09-29 12:58:36 +00001517 if (Config->EMachine == EM_MIPS) {
1518 // On MIPS we need to mark symbol which has a PLT entry and requires
1519 // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1520 // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1521 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1522 if (Body->isInPlt() && Body->NeedsCopyOrPltAddr)
1523 ESym->st_other |= STO_MIPS_PLT;
1524 if (Config->Relocatable) {
1525 auto *D = dyn_cast<DefinedRegular<ELFT>>(Body);
1526 if (D && D->isMipsPIC())
1527 ESym->st_other |= STO_MIPS_PIC;
1528 }
1529 }
Igor Kudrinab665fc2015-10-20 21:47:58 +00001530 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001531 }
1532}
1533
Igor Kudrin853b88d2015-10-20 20:52:14 +00001534template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001535const OutputSectionBase *
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001536SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1537 switch (Sym->kind()) {
1538 case SymbolBody::DefinedSyntheticKind:
Peter Collingbourne6a422592016-05-03 01:21:08 +00001539 return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001540 case SymbolBody::DefinedRegularKind: {
Rafael Espindola5ffa13c2016-04-15 00:15:02 +00001541 auto &D = cast<DefinedRegular<ELFT>>(*Sym);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001542 if (D.Section)
1543 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001544 break;
1545 }
1546 case SymbolBody::DefinedCommonKind:
Rui Ueyamae8a61022016-11-05 23:05:47 +00001547 return In<ELFT>::Common->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001548 case SymbolBody::SharedKind:
1549 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1550 return Out<ELFT>::Bss;
1551 break;
Peter Collingbourne60976ed2016-04-27 00:05:06 +00001552 case SymbolBody::UndefinedKind:
Rui Ueyamaf8baa662016-04-07 19:24:51 +00001553 case SymbolBody::LazyArchiveKind:
1554 case SymbolBody::LazyObjectKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001555 break;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001556 }
1557 return nullptr;
1558}
1559
1560template <class ELFT>
George Rimard3566302016-06-20 11:55:12 +00001561VersionDefinitionSection<ELFT>::VersionDefinitionSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001562 : OutputSectionBase(".gnu.version_d", SHT_GNU_verdef, SHF_ALLOC) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001563 this->Addralign = sizeof(uint32_t);
Rui Ueyamaf5244642016-07-16 02:36:00 +00001564}
George Rimard3566302016-06-20 11:55:12 +00001565
1566static StringRef getFileDefName() {
1567 if (!Config->SoName.empty())
1568 return Config->SoName;
1569 return Config->OutputFile;
1570}
1571
1572template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1573 FileDefNameOff = Out<ELFT>::DynStrTab->addString(getFileDefName());
Rui Ueyamaaf469d42016-07-16 04:09:27 +00001574 for (VersionDefinition &V : Config->VersionDefinitions)
George Rimard3566302016-06-20 11:55:12 +00001575 V.NameOff = Out<ELFT>::DynStrTab->addString(V.Name);
1576
Rafael Espindola04a2e342016-11-09 01:42:41 +00001577 this->Size = (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1578 this->Link = Out<ELFT>::DynStrTab->SectionIndex;
George Rimard3566302016-06-20 11:55:12 +00001579
1580 // sh_info should be set to the number of definitions. This fact is missed in
1581 // documentation, but confirmed by binutils community:
1582 // https://sourceware.org/ml/binutils/2014-11/msg00355.html
Rafael Espindola04a2e342016-11-09 01:42:41 +00001583 this->Info = getVerDefNum();
George Rimard3566302016-06-20 11:55:12 +00001584}
1585
Rui Ueyama9f619642016-07-16 02:29:45 +00001586template <class ELFT>
1587void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1588 StringRef Name, size_t NameOff) {
1589 auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
George Rimard3566302016-06-20 11:55:12 +00001590 Verdef->vd_version = 1;
George Rimar33b9de42016-07-01 11:45:10 +00001591 Verdef->vd_cnt = 1;
Rui Ueyama9f619642016-07-16 02:29:45 +00001592 Verdef->vd_aux = sizeof(Elf_Verdef);
1593 Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1594 Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
George Rimard3566302016-06-20 11:55:12 +00001595 Verdef->vd_ndx = Index;
Davide Italianoe7fd0be2016-11-07 21:56:56 +00001596 Verdef->vd_hash = hashSysV(Name);
George Rimard3566302016-06-20 11:55:12 +00001597
Rui Ueyama9f619642016-07-16 02:29:45 +00001598 auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1599 Verdaux->vda_name = NameOff;
George Rimard3566302016-06-20 11:55:12 +00001600 Verdaux->vda_next = 0;
George Rimard3566302016-06-20 11:55:12 +00001601}
1602
1603template <class ELFT>
1604void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama9f619642016-07-16 02:29:45 +00001605 writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1606
Rui Ueyamaaf469d42016-07-16 04:09:27 +00001607 for (VersionDefinition &V : Config->VersionDefinitions) {
Rui Ueyama9f619642016-07-16 02:29:45 +00001608 Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1609 writeOne(Buf, V.Id, V.Name, V.NameOff);
1610 }
1611
1612 // Need to terminate the last version definition.
George Rimard3566302016-06-20 11:55:12 +00001613 Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
Rui Ueyama9f619642016-07-16 02:29:45 +00001614 Verdef->vd_next = 0;
George Rimard3566302016-06-20 11:55:12 +00001615}
1616
1617template <class ELFT>
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001618VersionTableSection<ELFT>::VersionTableSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001619 : OutputSectionBase(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001620 this->Addralign = sizeof(uint16_t);
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001621}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001622
1623template <class ELFT> void VersionTableSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001624 this->Size =
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001625 sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001626 this->Entsize = sizeof(Elf_Versym);
George Rimar8b3c5f22016-06-06 08:04:53 +00001627 // At the moment of june 2016 GNU docs does not mention that sh_link field
1628 // should be set, but Sun docs do. Also readelf relies on this field.
Rafael Espindola04a2e342016-11-09 01:42:41 +00001629 this->Link = Out<ELFT>::DynSymTab->SectionIndex;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001630}
1631
1632template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1633 auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
Michael J. Spencerf8a81482016-10-19 23:49:27 +00001634 for (const SymbolTableEntry &S : Out<ELFT>::DynSymTab->getSymbols()) {
1635 OutVersym->vs_index = S.Symbol->symbol()->VersionId;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001636 ++OutVersym;
1637 }
1638}
1639
1640template <class ELFT>
1641VersionNeedSection<ELFT>::VersionNeedSection()
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001642 : OutputSectionBase(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001643 this->Addralign = sizeof(uint32_t);
George Rimard3566302016-06-20 11:55:12 +00001644
1645 // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1646 // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1647 // First identifiers are reserved by verdef section if it exist.
1648 NextIndex = getVerDefNum() + 1;
Rafael Espindolaeaaec4a2016-04-29 17:19:45 +00001649}
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001650
1651template <class ELFT>
1652void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1653 if (!SS->Verdef) {
George Rimard3566302016-06-20 11:55:12 +00001654 SS->symbol()->VersionId = VER_NDX_GLOBAL;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001655 return;
1656 }
Rui Ueyama434b5612016-07-17 03:11:46 +00001657 SharedFile<ELFT> *F = SS->file();
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001658 // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1659 // to create one by adding it to our needed list and creating a dynstr entry
1660 // for the soname.
1661 if (F->VerdefMap.empty())
1662 Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1663 typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1664 // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1665 // prepare to create one by allocating a version identifier and creating a
1666 // dynstr entry for the version name.
1667 if (NV.Index == 0) {
1668 NV.StrTab = Out<ELFT>::DynStrTab->addString(
Rui Ueyama434b5612016-07-17 03:11:46 +00001669 SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001670 NV.Index = NextIndex++;
1671 }
George Rimard3566302016-06-20 11:55:12 +00001672 SS->symbol()->VersionId = NV.Index;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001673}
1674
1675template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1676 // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1677 auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1678 auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1679
1680 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1681 // Create an Elf_Verneed for this DSO.
1682 Verneed->vn_version = 1;
1683 Verneed->vn_cnt = P.first->VerdefMap.size();
1684 Verneed->vn_file = P.second;
1685 Verneed->vn_aux =
1686 reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1687 Verneed->vn_next = sizeof(Elf_Verneed);
1688 ++Verneed;
1689
1690 // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1691 // VerdefMap, which will only contain references to needed version
1692 // definitions. Each Elf_Vernaux is based on the information contained in
1693 // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1694 // pointers, but is deterministic because the pointers refer to Elf_Verdef
1695 // data structures within a single input file.
1696 for (auto &NV : P.first->VerdefMap) {
1697 Vernaux->vna_hash = NV.first->vd_hash;
1698 Vernaux->vna_flags = 0;
1699 Vernaux->vna_other = NV.second.Index;
1700 Vernaux->vna_name = NV.second.StrTab;
1701 Vernaux->vna_next = sizeof(Elf_Vernaux);
1702 ++Vernaux;
1703 }
1704
1705 Vernaux[-1].vna_next = 0;
1706 }
1707 Verneed[-1].vn_next = 0;
1708}
1709
1710template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001711 this->Link = Out<ELFT>::DynStrTab->SectionIndex;
1712 this->Info = Needed.size();
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001713 unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1714 for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1715 Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001716 this->Size = Size;
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001717}
1718
1719template <class ELFT>
Rafael Espindola10897f12016-09-13 14:23:14 +00001720static typename ELFT::uint getOutFlags(InputSectionBase<ELFT> *S) {
Rafael Espindola1854a8e2016-10-26 12:36:56 +00001721 return S->Flags & ~SHF_GROUP & ~SHF_COMPRESSED;
Rafael Espindola10897f12016-09-13 14:23:14 +00001722}
1723
1724template <class ELFT>
Rafael Espindola17c35832016-09-13 12:25:30 +00001725static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
1726 StringRef OutsecName) {
Rafael Espindola17c35832016-09-13 12:25:30 +00001727 typedef typename ELFT::uint uintX_t;
Rafael Espindola10897f12016-09-13 14:23:14 +00001728 uintX_t Flags = getOutFlags(C);
Rafael Espindola17c35832016-09-13 12:25:30 +00001729
1730 // For SHF_MERGE we create different output sections for each alignment.
1731 // This makes each output section simple and keeps a single level mapping from
1732 // input to output.
Simon Atanasyan02b9c3f2016-10-05 07:49:18 +00001733 // In case of relocatable object generation we do not try to perform merging
1734 // and treat SHF_MERGE sections as regular ones, but also create different
1735 // output sections for them to allow merging at final linking stage.
Rafael Espindola17c35832016-09-13 12:25:30 +00001736 uintX_t Alignment = 0;
Simon Atanasyan02b9c3f2016-10-05 07:49:18 +00001737 if (isa<MergeInputSection<ELFT>>(C) ||
Rafael Espindola1854a8e2016-10-26 12:36:56 +00001738 (Config->Relocatable && (C->Flags & SHF_MERGE)))
1739 Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
Rafael Espindola17c35832016-09-13 12:25:30 +00001740
Rafael Espindola1854a8e2016-10-26 12:36:56 +00001741 return SectionKey<ELFT::Is64Bits>{OutsecName, C->Type, Flags, Alignment};
Rafael Espindola17c35832016-09-13 12:25:30 +00001742}
1743
1744template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001745std::pair<OutputSectionBase *, bool>
George Rimar6892afa2016-07-12 09:49:43 +00001746OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
1747 StringRef OutsecName) {
1748 SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
Rafael Espindola10897f12016-09-13 14:23:14 +00001749 return create(Key, C);
1750}
George Rimar6892afa2016-07-12 09:49:43 +00001751
Rafael Espindola10897f12016-09-13 14:23:14 +00001752template <class ELFT>
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001753std::pair<OutputSectionBase *, bool>
Rafael Espindola10897f12016-09-13 14:23:14 +00001754OutputSectionFactory<ELFT>::create(const SectionKey<ELFT::Is64Bits> &Key,
1755 InputSectionBase<ELFT> *C) {
1756 uintX_t Flags = getOutFlags(C);
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001757 OutputSectionBase *&Sec = Map[Key];
Rafael Espindola10897f12016-09-13 14:23:14 +00001758 if (Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001759 Sec->Flags |= Flags;
Rafael Espindola10897f12016-09-13 14:23:14 +00001760 return {Sec, false};
1761 }
1762
Rafael Espindola1854a8e2016-10-26 12:36:56 +00001763 uint32_t Type = C->Type;
Rafael Espindola16853bb2016-09-08 12:33:41 +00001764 switch (C->kind()) {
George Rimar6892afa2016-07-12 09:49:43 +00001765 case InputSectionBase<ELFT>::Regular:
Eugene Leviant41ca3272016-11-10 09:48:29 +00001766 case InputSectionBase<ELFT>::Synthetic:
Rui Ueyama95642b92016-11-01 23:09:07 +00001767 Sec = make<OutputSection<ELFT>>(Key.Name, Type, Flags);
George Rimar6892afa2016-07-12 09:49:43 +00001768 break;
1769 case InputSectionBase<ELFT>::EHFrame:
1770 return {Out<ELFT>::EhFrame, false};
1771 case InputSectionBase<ELFT>::Merge:
Rui Ueyama95642b92016-11-01 23:09:07 +00001772 Sec = make<MergeOutputSection<ELFT>>(Key.Name, Type, Flags, Key.Alignment);
George Rimar6892afa2016-07-12 09:49:43 +00001773 break;
George Rimar6892afa2016-07-12 09:49:43 +00001774 }
1775 return {Sec, true};
1776}
1777
George Rimar6892afa2016-07-12 09:49:43 +00001778template <bool Is64Bits>
1779typename lld::elf::SectionKey<Is64Bits>
1780DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getEmptyKey() {
1781 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 0};
1782}
1783
1784template <bool Is64Bits>
1785typename lld::elf::SectionKey<Is64Bits>
1786DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getTombstoneKey() {
1787 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0,
1788 0};
1789}
1790
1791template <bool Is64Bits>
1792unsigned
1793DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getHashValue(const Key &Val) {
1794 return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
1795}
1796
1797template <bool Is64Bits>
1798bool DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::isEqual(const Key &LHS,
1799 const Key &RHS) {
1800 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
1801 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
1802 LHS.Alignment == RHS.Alignment;
1803}
1804
1805namespace llvm {
1806template struct DenseMapInfo<SectionKey<true>>;
1807template struct DenseMapInfo<SectionKey<false>>;
1808}
1809
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001810namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001811namespace elf {
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001812
1813template void OutputSectionBase::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
1814template void OutputSectionBase::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
1815template void OutputSectionBase::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
1816template void OutputSectionBase::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001817
George Rimarf6bc65a2016-01-15 13:34:52 +00001818template class EhFrameHeader<ELF32LE>;
1819template class EhFrameHeader<ELF32BE>;
1820template class EhFrameHeader<ELF64LE>;
1821template class EhFrameHeader<ELF64BE>;
1822
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001823template class GotSection<ELF32LE>;
1824template class GotSection<ELF32BE>;
1825template class GotSection<ELF64LE>;
1826template class GotSection<ELF64BE>;
1827
1828template class PltSection<ELF32LE>;
1829template class PltSection<ELF32BE>;
1830template class PltSection<ELF64LE>;
1831template class PltSection<ELF64BE>;
1832
1833template class RelocationSection<ELF32LE>;
1834template class RelocationSection<ELF32BE>;
1835template class RelocationSection<ELF64LE>;
1836template class RelocationSection<ELF64BE>;
1837
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001838template class GnuHashTableSection<ELF32LE>;
1839template class GnuHashTableSection<ELF32BE>;
1840template class GnuHashTableSection<ELF64LE>;
1841template class GnuHashTableSection<ELF64BE>;
1842
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001843template class HashTableSection<ELF32LE>;
1844template class HashTableSection<ELF32BE>;
1845template class HashTableSection<ELF64LE>;
1846template class HashTableSection<ELF64BE>;
1847
1848template class DynamicSection<ELF32LE>;
1849template class DynamicSection<ELF32BE>;
1850template class DynamicSection<ELF64LE>;
1851template class DynamicSection<ELF64BE>;
1852
1853template class OutputSection<ELF32LE>;
1854template class OutputSection<ELF32BE>;
1855template class OutputSection<ELF64LE>;
1856template class OutputSection<ELF64BE>;
1857
Rui Ueyama1e479c22016-05-23 15:07:59 +00001858template class EhOutputSection<ELF32LE>;
1859template class EhOutputSection<ELF32BE>;
1860template class EhOutputSection<ELF64LE>;
1861template class EhOutputSection<ELF64BE>;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001862
Rafael Espindolac159c962015-10-19 21:00:02 +00001863template class MergeOutputSection<ELF32LE>;
1864template class MergeOutputSection<ELF32BE>;
1865template class MergeOutputSection<ELF64LE>;
1866template class MergeOutputSection<ELF64BE>;
1867
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001868template class StringTableSection<ELF32LE>;
1869template class StringTableSection<ELF32BE>;
1870template class StringTableSection<ELF64LE>;
1871template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001872
1873template class SymbolTableSection<ELF32LE>;
1874template class SymbolTableSection<ELF32BE>;
1875template class SymbolTableSection<ELF64LE>;
1876template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001877
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001878template class VersionTableSection<ELF32LE>;
1879template class VersionTableSection<ELF32BE>;
1880template class VersionTableSection<ELF64LE>;
1881template class VersionTableSection<ELF64BE>;
1882
1883template class VersionNeedSection<ELF32LE>;
1884template class VersionNeedSection<ELF32BE>;
1885template class VersionNeedSection<ELF64LE>;
1886template class VersionNeedSection<ELF64BE>;
1887
George Rimard3566302016-06-20 11:55:12 +00001888template class VersionDefinitionSection<ELF32LE>;
1889template class VersionDefinitionSection<ELF32BE>;
1890template class VersionDefinitionSection<ELF64LE>;
1891template class VersionDefinitionSection<ELF64BE>;
1892
George Rimar58fa5242016-10-20 09:19:48 +00001893template class GdbIndexSection<ELF32LE>;
1894template class GdbIndexSection<ELF32BE>;
1895template class GdbIndexSection<ELF64LE>;
1896template class GdbIndexSection<ELF64BE>;
1897
George Rimar6892afa2016-07-12 09:49:43 +00001898template class OutputSectionFactory<ELF32LE>;
1899template class OutputSectionFactory<ELF32BE>;
1900template class OutputSectionFactory<ELF64LE>;
1901template class OutputSectionFactory<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001902}
1903}