blob: 0f03857985b0725cbd9f4e939414d66a334fe5b7 [file] [log] [blame]
Rui Ueyama0fcdc732016-05-24 20:24:43 +00001//===- Relocations.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//
George Rimar95912d02016-06-08 12:29:29 +000010// This file contains platform-independent functions to process relocations.
Rui Ueyama0fcdc732016-05-24 20:24:43 +000011// I'll describe the overview of this file here.
12//
13// Simple relocations are easy to handle for the linker. For example,
14// for R_X86_64_PC64 relocs, the linker just has to fix up locations
15// with the relative offsets to the target symbols. It would just be
16// reading records from relocation sections and applying them to output.
17//
18// But not all relocations are that easy to handle. For example, for
19// R_386_GOTOFF relocs, the linker has to create new GOT entries for
20// symbols if they don't exist, and fix up locations with GOT entry
21// offsets from the beginning of GOT section. So there is more than
22// fixing addresses in relocation processing.
23//
24// ELF defines a large number of complex relocations.
25//
26// The functions in this file analyze relocations and do whatever needs
27// to be done. It includes, but not limited to, the following.
28//
29// - create GOT/PLT entries
30// - create new relocations in .dynsym to let the dynamic linker resolve
31// them at runtime (since ELF supports dynamic linking, not all
32// relocations can be resolved at link-time)
33// - create COPY relocs and reserve space in .bss
34// - replace expensive relocs (in terms of runtime cost) with cheap ones
35// - error out infeasible combinations such as PIC and non-relative relocs
36//
37// Note that the functions in this file don't actually apply relocations
38// because it doesn't know about the output file nor the output file buffer.
39// It instead stores Relocation objects to InputSection's Relocations
40// vector to let it apply later in InputSection::writeTo.
41//
42//===----------------------------------------------------------------------===//
43
44#include "Relocations.h"
45#include "Config.h"
46#include "OutputSections.h"
47#include "SymbolTable.h"
48#include "Target.h"
Peter Smithfb05cd92016-07-08 16:10:27 +000049#include "Thunks.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000050
51#include "llvm/Support/Endian.h"
52#include "llvm/Support/raw_ostream.h"
53
54using namespace llvm;
55using namespace llvm::ELF;
56using namespace llvm::object;
57using namespace llvm::support::endian;
58
59namespace lld {
60namespace elf {
61
62static bool refersToGotEntry(RelExpr Expr) {
Simon Atanasyan41325112016-06-19 21:39:37 +000063 return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL_PAGE ||
Simon Atanasyan002e2442016-06-23 15:26:31 +000064 Expr == R_MIPS_GOT_OFF || Expr == R_MIPS_TLSGD ||
65 Expr == R_MIPS_TLSLD || Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC ||
Simon Atanasyan41325112016-06-19 21:39:37 +000066 Expr == R_GOT_FROM_END || Expr == R_TLSGD || Expr == R_TLSGD_PC ||
67 Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +000068}
69
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000070static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
71 // In case of MIPS GP-relative relocations always resolve to a definition
72 // in a regular input file, ignoring the one-definition rule. So we,
73 // for example, should not attempt to create a dynamic relocation even
74 // if the target symbol is preemptible. There are two two MIPS GP-relative
75 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
76 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000077 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000078 // relocation types occupy eight bit. In case of N64 ABI we extract first
79 // relocation from 3-in-1 packet because only the first relocation can
80 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000081 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000082 return false;
83 return Body.isPreemptible();
84}
85
Simon Atanasyan002e2442016-06-23 15:26:31 +000086// This function is similar to the `handleTlsRelocation`. MIPS does not support
87// any relaxations for TLS relocations so by factoring out MIPS handling into
88// the separate function we can simplify the code and does not pollute
89// `handleTlsRelocation` by MIPS `ifs` statements.
90template <class ELFT>
91static unsigned
92handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body,
93 InputSectionBase<ELFT> &C, typename ELFT::uint Offset,
94 typename ELFT::uint Addend, RelExpr Expr) {
95 if (Expr == R_MIPS_TLSLD) {
96 if (Out<ELFT>::Got->addTlsIndex())
97 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
98 Out<ELFT>::Got->getTlsIndexOff(), false,
99 nullptr, 0});
100 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
101 return 1;
102 }
103 if (Target->isTlsGlobalDynamicRel(Type)) {
104 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
105 typedef typename ELFT::uint uintX_t;
106 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
107 Out<ELFT>::RelaDyn->addReloc(
108 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
109 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
110 Off + (uintX_t)sizeof(uintX_t), false,
111 &Body, 0});
112 }
113 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
114 return 1;
115 }
116 return 0;
117}
118
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000119// Returns the number of relocations processed.
120template <class ELFT>
121static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
122 InputSectionBase<ELFT> &C,
123 typename ELFT::uint Offset,
124 typename ELFT::uint Addend, RelExpr Expr) {
125 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
126 return 0;
127
128 if (!Body.isTls())
129 return 0;
130
131 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000132
Simon Atanasyan002e2442016-06-23 15:26:31 +0000133 if (Config->EMachine == EM_MIPS)
134 return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
135
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000136 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
137 Config->Shared) {
138 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
139 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
140 Out<ELFT>::RelaDyn->addReloc(
141 {Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
142 }
143 if (Expr != R_HINT)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000144 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000145 return 1;
146 }
147
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000148 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
149 // Local-Dynamic relocs can be relaxed to Local-Exec.
150 if (!Config->Shared) {
151 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000152 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000153 return 2;
154 }
155 if (Out<ELFT>::Got->addTlsIndex())
156 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
157 Out<ELFT>::Got->getTlsIndexOff(), false,
158 nullptr, 0});
Rui Ueyama809d8e22016-06-23 04:33:42 +0000159 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000160 return 1;
161 }
162
163 // Local-Dynamic relocs can be relaxed to Local-Exec.
164 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
165 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000166 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000167 return 1;
168 }
169
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000170 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
171 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000172 if (Config->Shared) {
173 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
174 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
175 Out<ELFT>::RelaDyn->addReloc(
176 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000177
178 // If the symbol is preemptible we need the dynamic linker to write
179 // the offset too.
Simon Atanasyan9b861182016-06-10 12:26:39 +0000180 if (isPreemptible(Body, Type))
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000181 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
182 Off + (uintX_t)sizeof(uintX_t), false,
183 &Body, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000184 }
Rui Ueyama809d8e22016-06-23 04:33:42 +0000185 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000186 return 1;
187 }
188
189 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
190 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000191 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000192 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000193 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rui Ueyama809d8e22016-06-23 04:33:42 +0000194 &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000195 if (!Body.isInGot()) {
196 Out<ELFT>::Got->addEntry(Body);
197 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
198 Body.getGotOffset<ELFT>(), false, &Body,
199 0});
200 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000201 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000202 }
203 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000204 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, &C,
Rafael Espindola69f54022016-06-04 23:22:34 +0000205 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000206 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000207 }
208
209 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
210 // defined.
211 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000212 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000213 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000214 {R_RELAX_TLS_IE_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000215 return 1;
216 }
217 return 0;
218}
219
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000220template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
221 return read32<E>(Loc) & 0xffff;
222}
223
224template <class RelTy>
225static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
226 switch (Rel->getType(Config->Mips64EL)) {
227 case R_MIPS_HI16:
228 return R_MIPS_LO16;
229 case R_MIPS_GOT16:
230 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
231 case R_MIPS_PCHI16:
232 return R_MIPS_PCLO16;
233 case R_MICROMIPS_HI16:
234 return R_MICROMIPS_LO16;
235 default:
236 return R_MIPS_NONE;
237 }
238}
239
240template <class ELFT, class RelTy>
241static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
242 SymbolBody &Sym, const RelTy *Rel,
243 const RelTy *End) {
244 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
245 uint32_t Type = getMipsPairType(Rel, Sym);
246
247 // Some MIPS relocations use addend calculated from addend of the relocation
248 // itself and addend of paired relocation. ABI requires to compute such
249 // combined addend in case of REL relocation record format only.
250 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
251 if (RelTy::IsRela || Type == R_MIPS_NONE)
252 return 0;
253
254 for (const RelTy *RI = Rel; RI != End; ++RI) {
255 if (RI->getType(Config->Mips64EL) != Type)
256 continue;
257 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
258 continue;
259 const endianness E = ELFT::TargetEndianness;
260 return ((read32<E>(BufLoc) & 0xffff) << 16) +
261 readSignedLo16<E>(Buf + RI->r_offset);
262 }
George Rimare6389d12016-06-08 12:22:26 +0000263 warning("can't find matching " + getRelName(Type) + " relocation for " +
264 getRelName(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000265 return 0;
266}
267
268// True if non-preemptable symbol always has the same value regardless of where
269// the DSO is loaded.
270template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
271 if (Body.isUndefined())
272 return !Body.isLocal() && Body.symbol()->isWeak();
273 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
274 return DR->Section == nullptr; // Absolute symbol.
275 return false;
276}
277
278static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000279 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
Peter Smithfb05cd92016-07-08 16:10:27 +0000280 Expr == R_PLT_PAGE_PC || Expr == R_THUNK_PLT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000281}
282
283// True if this expression is of the form Sym - X, where X is a position in the
284// file (PC, or GOT for example).
285static bool isRelExpr(RelExpr Expr) {
George Rimar5c33b912016-05-25 14:31:37 +0000286 return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Peter Smithfb05cd92016-07-08 16:10:27 +0000287 Expr == R_RELAX_GOT_PC || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000288}
289
290template <class ELFT>
291static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
292 const SymbolBody &Body) {
293 // These expressions always compute a constant
294 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
Simon Atanasyan002e2442016-06-23 15:26:31 +0000295 E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF || E == R_MIPS_TLSGD ||
296 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
Peter Smithfb05cd92016-07-08 16:10:27 +0000297 E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE ||
298 E == R_HINT || E == R_THUNK_PC || E == R_THUNK_PLT_PC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000299 return true;
300
301 // These never do, except if the entire file is position dependent or if
302 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000303 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000304 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
305
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000306 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000307 return false;
308
309 if (!Config->Pic)
310 return true;
311
312 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
313 bool RelE = isRelExpr(E);
314 if (AbsVal && !RelE)
315 return true;
316 if (!AbsVal && RelE)
317 return true;
318
319 // Relative relocation to an absolute value. This is normally unrepresentable,
320 // but if the relocation refers to a weak undefined symbol, we allow it to
321 // resolve to the image base. This is a little strange, but it allows us to
322 // link function calls to such symbols. Normally such a call will be guarded
323 // with a comparison, which will load a zero from the GOT.
324 if (AbsVal && RelE) {
325 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
326 return true;
George Rimare6389d12016-06-08 12:22:26 +0000327 error("relocation " + getRelName(Type) +
328 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000329 return true;
330 }
331
332 return Target->usesOnlyLowPageBits(Type);
333}
334
335static RelExpr toPlt(RelExpr Expr) {
336 if (Expr == R_PPC_OPD)
337 return R_PPC_PLT_OPD;
338 if (Expr == R_PC)
339 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000340 if (Expr == R_PAGE_PC)
341 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000342 if (Expr == R_ABS)
343 return R_PLT;
344 return Expr;
345}
346
347static RelExpr fromPlt(RelExpr Expr) {
348 // We decided not to use a plt. Optimize a reference to the plt to a
349 // reference to the symbol itself.
350 if (Expr == R_PLT_PC)
351 return R_PC;
352 if (Expr == R_PPC_PLT_OPD)
353 return R_PPC_OPD;
354 if (Expr == R_PLT)
355 return R_ABS;
356 return Expr;
357}
358
359template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
360 typedef typename ELFT::uint uintX_t;
361
Rui Ueyama434b5612016-07-17 03:11:46 +0000362 uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000363 uintX_t SymValue = SS->Sym.st_value;
364 int TrailingZeros =
365 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
366 return 1 << TrailingZeros;
367}
368
369// Reserve space in .bss for copy relocation.
370template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
371 typedef typename ELFT::uint uintX_t;
372 typedef typename ELFT::Sym Elf_Sym;
373
374 // Copy relocation against zero-sized symbol doesn't make sense.
375 uintX_t SymSize = SS->template getSize<ELFT>();
376 if (SymSize == 0)
Petr Hosek4071b1b2016-08-18 21:55:23 +0000377 fatal("cannot create a copy relocation for symbol " + SS->getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000378
Rui Ueyama424b4082016-06-17 01:18:46 +0000379 uintX_t Alignment = getAlignment(SS);
380 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000381 Out<ELFT>::Bss->setSize(Off + SymSize);
Rui Ueyama424b4082016-06-17 01:18:46 +0000382 Out<ELFT>::Bss->updateAlignment(Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000383 uintX_t Shndx = SS->Sym.st_shndx;
384 uintX_t Value = SS->Sym.st_value;
385 // Look through the DSO's dynamic symbol table for aliases and create a
386 // dynamic symbol for each one. This causes the copy relocation to correctly
387 // interpose any aliases.
Rui Ueyama434b5612016-07-17 03:11:46 +0000388 for (const Elf_Sym &S : SS->file()->getElfSymbols(true)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000389 if (S.st_shndx != Shndx || S.st_value != Value)
390 continue;
391 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
Rui Ueyama434b5612016-07-17 03:11:46 +0000392 Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000393 if (!Alias)
394 continue;
395 Alias->OffsetInBss = Off;
396 Alias->NeedsCopyOrPltAddr = true;
397 Alias->symbol()->IsUsedInRegularObj = true;
398 }
399 Out<ELFT>::RelaDyn->addReloc(
400 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
401}
402
403template <class ELFT>
Petr Hosek4071b1b2016-08-18 21:55:23 +0000404static StringRef getLocalSymbolName(const elf::ObjectFile<ELFT> &File,
405 SymbolBody &Body) {
406 return File.getStringTable().data() + Body.getNameOffset();
407}
408
409template <class ELFT>
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000410static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000411 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000412 const uint8_t *Data) {
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000413 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000414 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000415 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000416 } else if (!Preemptible) {
417 if (needsPlt(Expr))
418 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000419 if (Expr == R_GOT_PC)
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000420 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000421 }
Peter Smithfb05cd92016-07-08 16:10:27 +0000422 Expr = Target->getThunkExpr(Expr, Type, File, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000423
424 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
425 return Expr;
426
427 // This relocation would require the dynamic linker to write a value to read
428 // only memory. We can hack around it if we are producing an executable and
429 // the refered symbol can be preemepted to refer to the executable.
430 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
Petr Hosek4071b1b2016-08-18 21:55:23 +0000431 StringRef Name = Body.isLocal() ? getLocalSymbolName(File, Body)
432 : Body.getName();
George Rimar3ed2b082016-06-10 08:00:01 +0000433 error("can't create dynamic relocation " + getRelName(Type) +
Petr Hosek4071b1b2016-08-18 21:55:23 +0000434 " against symbol " + Name);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000435 return Expr;
436 }
437 if (Body.getVisibility() != STV_DEFAULT) {
Petr Hosek4071b1b2016-08-18 21:55:23 +0000438 error("cannot preempt symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000439 return Expr;
440 }
441 if (Body.isObject()) {
442 // Produce a copy relocation.
443 auto *B = cast<SharedSymbol<ELFT>>(&Body);
444 if (!B->needsCopy())
445 addCopyRelSymbol(B);
446 return Expr;
447 }
448 if (Body.isFunc()) {
449 // This handles a non PIC program call to function in a shared library. In
450 // an ideal world, we could just report an error saying the relocation can
451 // overflow at runtime. In the real world with glibc, crt1.o has a
452 // R_X86_64_PC32 pointing to libc.so.
453 //
454 // The general idea on how to handle such cases is to create a PLT entry and
455 // use that as the function value.
456 //
457 // For the static linking part, we just return a plt expr and everything
458 // else will use the the PLT entry as the address.
459 //
460 // The remaining problem is making sure pointer equality still works. We
461 // need the help of the dynamic linker for that. We let it know that we have
462 // a direct reference to a so symbol by creating an undefined symbol with a
463 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
464 // the value of the symbol we created. This is true even for got entries, so
465 // pointer equality is maintained. To avoid an infinite loop, the only entry
466 // that points to the real function is a dedicated got entry used by the
467 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
468 // R_386_JMP_SLOT, etc).
469 Body.NeedsCopyOrPltAddr = true;
470 return toPlt(Expr);
471 }
Petr Hosek4071b1b2016-08-18 21:55:23 +0000472 error("symbol " + Body.getName() + " is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000473
474 return Expr;
475}
476
477template <class ELFT, class RelTy>
478static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
479 const uint8_t *SectionData,
480 const RelTy *End, const RelTy &RI,
481 RelExpr Expr, SymbolBody &Body) {
482 typedef typename ELFT::uint uintX_t;
483
484 uint32_t Type = RI.getType(Config->Mips64EL);
485 uintX_t Addend = getAddend<ELFT>(RI);
486 const uint8_t *BufLoc = SectionData + RI.r_offset;
487 if (!RelTy::IsRela)
488 Addend += Target->getImplicitAddend(BufLoc, Type);
489 if (Config->EMachine == EM_MIPS) {
490 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
491 if (Type == R_MIPS_LO16 && Expr == R_PC)
492 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
493 // symbol. In that case we should use the following formula for
494 // calculation "AHL + GP - P + 4". Let's add 4 right here.
495 // For details see p. 4-19 at
496 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
497 Addend += 4;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000498 if (Expr == R_GOTREL) {
499 Addend -= MipsGPOffset;
500 if (Body.isLocal())
501 Addend += File.getMipsGp0();
502 }
503 }
504 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
505 Addend += getPPC64TocBase();
506 return Addend;
507}
508
509// The reason we have to do this early scan is as follows
510// * To mmap the output file, we need to know the size
511// * For that, we need to know how many dynamic relocs we will have.
512// It might be possible to avoid this by outputting the file with write:
513// * Write the allocated output sections, computing addresses.
514// * Apply relocations, recording which ones require a dynamic reloc.
515// * Write the dynamic relocations.
516// * Write the rest of the file.
517// This would have some drawbacks. For example, we would only know if .rela.dyn
518// is needed after applying relocations. If it is, it will go after rw and rx
519// sections. Given that it is ro, we will need an extra PT_LOAD. This
520// complicates things for the dynamic linker and means we would have to reserve
521// space for the extra PT_LOAD even if we end up not using it.
522template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000523static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000524 typedef typename ELFT::uint uintX_t;
525
George Rimardb0168d2016-06-09 15:17:29 +0000526 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000527
528 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
529 Out<ELFT>::RelaDyn->addReloc(Reloc);
530 };
531
532 const elf::ObjectFile<ELFT> &File = *C.getFile();
533 ArrayRef<uint8_t> SectionData = C.getSectionData();
534 const uint8_t *Buf = SectionData.begin();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000535
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000536 ArrayRef<EhSectionPiece> Pieces;
537 if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
538 Pieces = Eh->Pieces;
539
540 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
541 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000542
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000543 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
544 const RelTy &RI = *I;
545 SymbolBody &Body = File.getRelocTargetSym(RI);
546 uint32_t Type = RI.getType(Config->Mips64EL);
547
548 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000549 bool Preemptible = isPreemptible(Body, Type);
550 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
551 if (HasError)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000552 continue;
553
Rui Ueyama809d8e22016-06-23 04:33:42 +0000554 // Skip a relocation that points to a dead piece
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000555 // in a eh_frame section.
556 while (PieceI != PieceE &&
557 (PieceI->InputOff + PieceI->size() <= RI.r_offset))
558 ++PieceI;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000559
560 // Compute the offset of this section in the output section. We do it here
561 // to try to compute it only once.
562 uintX_t Offset;
563 if (PieceI != PieceE) {
564 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
George Rimare37dde82016-07-21 15:35:06 +0000565 if (PieceI->OutputOff == (size_t)-1)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000566 continue;
567 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000568 } else {
George Rimar3e6833b2016-08-19 15:46:28 +0000569 Offset = RI.r_offset;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000570 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000571
572 // This relocation does not require got entry, but it is relative to got and
573 // needs it to be created. Here we request for that.
574 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
575 Out<ELFT>::Got->HasGotOffRel = true;
576
577 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
578
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000579 if (unsigned Processed =
580 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000581 I += (Processed - 1);
582 continue;
583 }
584
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000585 // Ignore "hint" relocation because it is for optional code optimization.
586 if (Expr == R_HINT)
587 continue;
588
Peter Smithfb05cd92016-07-08 16:10:27 +0000589 if (needsPlt(Expr) || Expr == R_THUNK_ABS || Expr == R_THUNK_PC ||
590 Expr == R_THUNK_PLT_PC || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000591 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000592 // If the relocation points to something in the file, we can process it.
593 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
594
595 // If the output being produced is position independent, the final value
596 // is still not known. In that case we still need some help from the
597 // dynamic linker. We can however do better than just copying the incoming
598 // relocation. We can process some of it and and just ask the dynamic
599 // linker to add the load address.
600 if (!Constant)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000601 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000602
603 // If the produced value is a constant, we just remember to write it
604 // when outputting this section. We also have to do it if the format
605 // uses Elf_Rel, since in that case the written value is the addend.
606 if (Constant || !RelTy::IsRela)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000607 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000608 } else {
609 // We don't know anything about the finaly symbol. Just ask the dynamic
610 // linker to handle the relocation for us.
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000611 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000612 // MIPS ABI turns using of GOT and dynamic relocations inside out.
613 // While regular ABI uses dynamic relocations to fill up GOT entries
614 // MIPS ABI requires dynamic linker to fills up GOT entries using
615 // specially sorted dynamic symbol table. This affects even dynamic
616 // relocations against symbols which do not require GOT entries
617 // creation explicitly, i.e. do not have any GOT-relocations. So if
618 // a preemptible symbol has a dynamic relocation we anyway have
619 // to create a GOT entry for it.
620 // If a non-preemptible symbol has a dynamic relocation against it,
621 // dynamic linker takes it st_value, adds offset and writes down
622 // result of the dynamic relocation. In case of preemptible symbol
623 // dynamic linker performs symbol resolution, writes the symbol value
624 // to the GOT entry and reads the GOT entry when it needs to perform
625 // a dynamic relocation.
626 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000627 if (Config->EMachine == EM_MIPS)
628 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000629 continue;
630 }
631
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000632 // At this point we are done with the relocated position. Some relocations
633 // also require us to create a got or plt entry.
634
635 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
636 if (needsPlt(Expr)) {
637 if (Body.isInPlt())
638 continue;
639 Out<ELFT>::Plt->addEntry(Body);
640
641 uint32_t Rel;
642 if (Body.isGnuIFunc() && !Preemptible)
643 Rel = Target->IRelativeRel;
644 else
645 Rel = Target->PltRel;
646
647 Out<ELFT>::GotPlt->addEntry(Body);
648 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
649 Body.getGotPltOffset<ELFT>(), !Preemptible,
650 &Body, 0});
651 continue;
652 }
653
654 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000655 if (Config->EMachine == EM_MIPS) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000656 // MIPS ABI has special rules to process GOT entries
657 // and doesn't require relocation entries for them.
658 // See "Global Offset Table" in Chapter 5 in the following document
659 // for detailed description:
660 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan41325112016-06-19 21:39:37 +0000661 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000662 if (Body.isTls())
663 AddDyn({Target->TlsGotRel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
664 !Preemptible, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000665 continue;
666 }
667
668 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000669 continue;
670
Simon Atanasyan41325112016-06-19 21:39:37 +0000671 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000672 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
673 uint32_t DynType;
674 if (Body.isTls())
675 DynType = Target->TlsGotRel;
676 else if (Preemptible)
677 DynType = Target->GotRel;
678 else
679 DynType = Target->RelativeRel;
680 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
681 !Preemptible, &Body, 0});
682 }
683 continue;
684 }
685 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000686}
687
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000688template <class ELFT>
689void scanRelocations(InputSectionBase<ELFT> &S,
690 const typename ELFT::Shdr &RelSec) {
691 ELFFile<ELFT> &EObj = S.getFile()->getObj();
692 if (RelSec.sh_type == SHT_RELA)
693 scanRelocs(S, EObj.relas(&RelSec));
694 else
695 scanRelocs(S, EObj.rels(&RelSec));
696}
697
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000698template <class ELFT, class RelTy>
699static void createThunks(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
700 const elf::ObjectFile<ELFT> &File = *C.getFile();
701 for (const RelTy &Rel : Rels) {
702 SymbolBody &Body = File.getRelocTargetSym(Rel);
703 uint32_t Type = Rel.getType(Config->Mips64EL);
704 RelExpr Expr = Target->getRelExpr(Type, Body);
705 if (!isPreemptible(Body, Type) && needsPlt(Expr))
706 Expr = fromPlt(Expr);
707 Expr = Target->getThunkExpr(Expr, Type, File, Body);
708 // Some targets might require creation of thunks for relocations.
709 // Now we support only MIPS which requires LA25 thunk to call PIC
710 // code from non-PIC one, and ARM which requires interworking.
711 if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) {
712 auto *Sec = cast<InputSection<ELFT>>(&C);
713 addThunk<ELFT>(Type, Body, *Sec);
714 }
715 }
716}
717
718template <class ELFT>
719void createThunks(InputSectionBase<ELFT> &S,
720 const typename ELFT::Shdr &RelSec) {
721 ELFFile<ELFT> &EObj = S.getFile()->getObj();
722 if (RelSec.sh_type == SHT_RELA)
723 createThunks(S, EObj.relas(&RelSec));
724 else
725 createThunks(S, EObj.rels(&RelSec));
726}
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000727
728template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
729 const ELF32LE::Shdr &);
730template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
731 const ELF32BE::Shdr &);
732template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
733 const ELF64LE::Shdr &);
734template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
735 const ELF64BE::Shdr &);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000736
737template void createThunks<ELF32LE>(InputSectionBase<ELF32LE> &,
738 const ELF32LE::Shdr &);
739template void createThunks<ELF32BE>(InputSectionBase<ELF32BE> &,
740 const ELF32BE::Shdr &);
741template void createThunks<ELF64LE>(InputSectionBase<ELF64LE> &,
742 const ELF64LE::Shdr &);
743template void createThunks<ELF64BE>(InputSectionBase<ELF64BE> &,
744 const ELF64BE::Shdr &);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000745}
746}