blob: 5cf0a61c036f9863665ef3fe0964f8e9c7812931 [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"
49
50#include "llvm/Support/Endian.h"
51#include "llvm/Support/raw_ostream.h"
52
53using namespace llvm;
54using namespace llvm::ELF;
55using namespace llvm::object;
56using namespace llvm::support::endian;
57
58namespace lld {
59namespace elf {
60
61static bool refersToGotEntry(RelExpr Expr) {
Simon Atanasyan41325112016-06-19 21:39:37 +000062 return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL_PAGE ||
63 Expr == R_MIPS_GOT_OFF || Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC ||
64 Expr == R_GOT_FROM_END || Expr == R_TLSGD || Expr == R_TLSGD_PC ||
65 Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +000066}
67
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000068static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
69 // In case of MIPS GP-relative relocations always resolve to a definition
70 // in a regular input file, ignoring the one-definition rule. So we,
71 // for example, should not attempt to create a dynamic relocation even
72 // if the target symbol is preemptible. There are two two MIPS GP-relative
73 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
74 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000075 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000076 // relocation types occupy eight bit. In case of N64 ABI we extract first
77 // relocation from 3-in-1 packet because only the first relocation can
78 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000079 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000080 return false;
81 return Body.isPreemptible();
82}
83
Rui Ueyama0fcdc732016-05-24 20:24:43 +000084// Returns the number of relocations processed.
85template <class ELFT>
86static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
87 InputSectionBase<ELFT> &C,
88 typename ELFT::uint Offset,
89 typename ELFT::uint Addend, RelExpr Expr) {
90 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
91 return 0;
92
93 if (!Body.isTls())
94 return 0;
95
96 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +000097
98 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
99 Config->Shared) {
100 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
101 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
102 Out<ELFT>::RelaDyn->addReloc(
103 {Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
104 }
105 if (Expr != R_HINT)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000106 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000107 return 1;
108 }
109
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000110 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
111 // Local-Dynamic relocs can be relaxed to Local-Exec.
112 if (!Config->Shared) {
113 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000114 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000115 return 2;
116 }
117 if (Out<ELFT>::Got->addTlsIndex())
118 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
119 Out<ELFT>::Got->getTlsIndexOff(), false,
120 nullptr, 0});
Rui Ueyama809d8e22016-06-23 04:33:42 +0000121 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000122 return 1;
123 }
124
125 // Local-Dynamic relocs can be relaxed to Local-Exec.
126 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
127 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000128 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000129 return 1;
130 }
131
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000132 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
133 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000134 if (Config->Shared) {
135 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
136 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
137 Out<ELFT>::RelaDyn->addReloc(
138 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000139
140 // If the symbol is preemptible we need the dynamic linker to write
141 // the offset too.
Simon Atanasyan9b861182016-06-10 12:26:39 +0000142 if (isPreemptible(Body, Type))
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000143 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
144 Off + (uintX_t)sizeof(uintX_t), false,
145 &Body, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000146 }
Rui Ueyama809d8e22016-06-23 04:33:42 +0000147 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000148 return 1;
149 }
150
151 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
152 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000153 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000154 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000155 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rui Ueyama809d8e22016-06-23 04:33:42 +0000156 &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000157 if (!Body.isInGot()) {
158 Out<ELFT>::Got->addEntry(Body);
159 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
160 Body.getGotOffset<ELFT>(), false, &Body,
161 0});
162 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000163 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000164 }
165 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000166 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, &C,
Rafael Espindola69f54022016-06-04 23:22:34 +0000167 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000168 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000169 }
170
171 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
172 // defined.
173 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000174 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000175 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000176 {R_RELAX_TLS_IE_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000177 return 1;
178 }
179 return 0;
180}
181
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000182template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
183 return read32<E>(Loc) & 0xffff;
184}
185
186template <class RelTy>
187static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
188 switch (Rel->getType(Config->Mips64EL)) {
189 case R_MIPS_HI16:
190 return R_MIPS_LO16;
191 case R_MIPS_GOT16:
192 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
193 case R_MIPS_PCHI16:
194 return R_MIPS_PCLO16;
195 case R_MICROMIPS_HI16:
196 return R_MICROMIPS_LO16;
197 default:
198 return R_MIPS_NONE;
199 }
200}
201
202template <class ELFT, class RelTy>
203static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
204 SymbolBody &Sym, const RelTy *Rel,
205 const RelTy *End) {
206 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
207 uint32_t Type = getMipsPairType(Rel, Sym);
208
209 // Some MIPS relocations use addend calculated from addend of the relocation
210 // itself and addend of paired relocation. ABI requires to compute such
211 // combined addend in case of REL relocation record format only.
212 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
213 if (RelTy::IsRela || Type == R_MIPS_NONE)
214 return 0;
215
216 for (const RelTy *RI = Rel; RI != End; ++RI) {
217 if (RI->getType(Config->Mips64EL) != Type)
218 continue;
219 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
220 continue;
221 const endianness E = ELFT::TargetEndianness;
222 return ((read32<E>(BufLoc) & 0xffff) << 16) +
223 readSignedLo16<E>(Buf + RI->r_offset);
224 }
George Rimare6389d12016-06-08 12:22:26 +0000225 warning("can't find matching " + getRelName(Type) + " relocation for " +
226 getRelName(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000227 return 0;
228}
229
230// True if non-preemptable symbol always has the same value regardless of where
231// the DSO is loaded.
232template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
233 if (Body.isUndefined())
234 return !Body.isLocal() && Body.symbol()->isWeak();
235 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
236 return DR->Section == nullptr; // Absolute symbol.
237 return false;
238}
239
240static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000241 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
242 Expr == R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000243}
244
245// True if this expression is of the form Sym - X, where X is a position in the
246// file (PC, or GOT for example).
247static bool isRelExpr(RelExpr Expr) {
George Rimar5c33b912016-05-25 14:31:37 +0000248 return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Rafael Espindolaa8433c12016-06-01 06:15:22 +0000249 Expr == R_RELAX_GOT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000250}
251
252template <class ELFT>
253static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
254 const SymbolBody &Body) {
255 // These expressions always compute a constant
256 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
Simon Atanasyan41325112016-06-19 21:39:37 +0000257 E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF || E == R_GOT_PAGE_PC ||
258 E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC || E == R_TLSGD ||
259 E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE || E == R_HINT)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000260 return true;
261
262 // These never do, except if the entire file is position dependent or if
263 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000264 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000265 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
266
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000267 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000268 return false;
269
270 if (!Config->Pic)
271 return true;
272
273 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
274 bool RelE = isRelExpr(E);
275 if (AbsVal && !RelE)
276 return true;
277 if (!AbsVal && RelE)
278 return true;
279
280 // Relative relocation to an absolute value. This is normally unrepresentable,
281 // but if the relocation refers to a weak undefined symbol, we allow it to
282 // resolve to the image base. This is a little strange, but it allows us to
283 // link function calls to such symbols. Normally such a call will be guarded
284 // with a comparison, which will load a zero from the GOT.
285 if (AbsVal && RelE) {
286 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
287 return true;
George Rimare6389d12016-06-08 12:22:26 +0000288 error("relocation " + getRelName(Type) +
289 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000290 return true;
291 }
292
293 return Target->usesOnlyLowPageBits(Type);
294}
295
296static RelExpr toPlt(RelExpr Expr) {
297 if (Expr == R_PPC_OPD)
298 return R_PPC_PLT_OPD;
299 if (Expr == R_PC)
300 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000301 if (Expr == R_PAGE_PC)
302 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000303 if (Expr == R_ABS)
304 return R_PLT;
305 return Expr;
306}
307
308static RelExpr fromPlt(RelExpr Expr) {
309 // We decided not to use a plt. Optimize a reference to the plt to a
310 // reference to the symbol itself.
311 if (Expr == R_PLT_PC)
312 return R_PC;
313 if (Expr == R_PPC_PLT_OPD)
314 return R_PPC_OPD;
315 if (Expr == R_PLT)
316 return R_ABS;
317 return Expr;
318}
319
320template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
321 typedef typename ELFT::uint uintX_t;
322
323 uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
324 uintX_t SymValue = SS->Sym.st_value;
325 int TrailingZeros =
326 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
327 return 1 << TrailingZeros;
328}
329
330// Reserve space in .bss for copy relocation.
331template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
332 typedef typename ELFT::uint uintX_t;
333 typedef typename ELFT::Sym Elf_Sym;
334
335 // Copy relocation against zero-sized symbol doesn't make sense.
336 uintX_t SymSize = SS->template getSize<ELFT>();
337 if (SymSize == 0)
338 fatal("cannot create a copy relocation for " + SS->getName());
339
Rui Ueyama424b4082016-06-17 01:18:46 +0000340 uintX_t Alignment = getAlignment(SS);
341 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000342 Out<ELFT>::Bss->setSize(Off + SymSize);
Rui Ueyama424b4082016-06-17 01:18:46 +0000343 Out<ELFT>::Bss->updateAlignment(Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000344 uintX_t Shndx = SS->Sym.st_shndx;
345 uintX_t Value = SS->Sym.st_value;
346 // Look through the DSO's dynamic symbol table for aliases and create a
347 // dynamic symbol for each one. This causes the copy relocation to correctly
348 // interpose any aliases.
349 for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
350 if (S.st_shndx != Shndx || S.st_value != Value)
351 continue;
352 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
353 Symtab<ELFT>::X->find(check(S.getName(SS->File->getStringTable()))));
354 if (!Alias)
355 continue;
356 Alias->OffsetInBss = Off;
357 Alias->NeedsCopyOrPltAddr = true;
358 Alias->symbol()->IsUsedInRegularObj = true;
359 }
360 Out<ELFT>::RelaDyn->addReloc(
361 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
362}
363
364template <class ELFT>
365static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000366 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000367 const uint8_t *Data) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000368 if (Target->needsThunk(Type, File, Body))
369 return R_THUNK;
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000370 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000371 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000372 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000373 } else if (!Preemptible) {
374 if (needsPlt(Expr))
375 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000376 if (Expr == R_GOT_PC)
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000377 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000378 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000379
380 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
381 return Expr;
382
383 // This relocation would require the dynamic linker to write a value to read
384 // only memory. We can hack around it if we are producing an executable and
385 // the refered symbol can be preemepted to refer to the executable.
386 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
George Rimar3ed2b082016-06-10 08:00:01 +0000387 error("can't create dynamic relocation " + getRelName(Type) +
388 " against readonly segment");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000389 return Expr;
390 }
391 if (Body.getVisibility() != STV_DEFAULT) {
George Rimar35728c32016-06-20 13:48:16 +0000392 error("cannot preempt symbol");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000393 return Expr;
394 }
395 if (Body.isObject()) {
396 // Produce a copy relocation.
397 auto *B = cast<SharedSymbol<ELFT>>(&Body);
398 if (!B->needsCopy())
399 addCopyRelSymbol(B);
400 return Expr;
401 }
402 if (Body.isFunc()) {
403 // This handles a non PIC program call to function in a shared library. In
404 // an ideal world, we could just report an error saying the relocation can
405 // overflow at runtime. In the real world with glibc, crt1.o has a
406 // R_X86_64_PC32 pointing to libc.so.
407 //
408 // The general idea on how to handle such cases is to create a PLT entry and
409 // use that as the function value.
410 //
411 // For the static linking part, we just return a plt expr and everything
412 // else will use the the PLT entry as the address.
413 //
414 // The remaining problem is making sure pointer equality still works. We
415 // need the help of the dynamic linker for that. We let it know that we have
416 // a direct reference to a so symbol by creating an undefined symbol with a
417 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
418 // the value of the symbol we created. This is true even for got entries, so
419 // pointer equality is maintained. To avoid an infinite loop, the only entry
420 // that points to the real function is a dedicated got entry used by the
421 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
422 // R_386_JMP_SLOT, etc).
423 Body.NeedsCopyOrPltAddr = true;
424 return toPlt(Expr);
425 }
George Rimar35728c32016-06-20 13:48:16 +0000426 error("symbol is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000427
428 return Expr;
429}
430
431template <class ELFT, class RelTy>
432static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
433 const uint8_t *SectionData,
434 const RelTy *End, const RelTy &RI,
435 RelExpr Expr, SymbolBody &Body) {
436 typedef typename ELFT::uint uintX_t;
437
438 uint32_t Type = RI.getType(Config->Mips64EL);
439 uintX_t Addend = getAddend<ELFT>(RI);
440 const uint8_t *BufLoc = SectionData + RI.r_offset;
441 if (!RelTy::IsRela)
442 Addend += Target->getImplicitAddend(BufLoc, Type);
443 if (Config->EMachine == EM_MIPS) {
444 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
445 if (Type == R_MIPS_LO16 && Expr == R_PC)
446 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
447 // symbol. In that case we should use the following formula for
448 // calculation "AHL + GP - P + 4". Let's add 4 right here.
449 // For details see p. 4-19 at
450 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
451 Addend += 4;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000452 if (Expr == R_GOTREL) {
453 Addend -= MipsGPOffset;
454 if (Body.isLocal())
455 Addend += File.getMipsGp0();
456 }
457 }
458 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
459 Addend += getPPC64TocBase();
460 return Addend;
461}
462
463// The reason we have to do this early scan is as follows
464// * To mmap the output file, we need to know the size
465// * For that, we need to know how many dynamic relocs we will have.
466// It might be possible to avoid this by outputting the file with write:
467// * Write the allocated output sections, computing addresses.
468// * Apply relocations, recording which ones require a dynamic reloc.
469// * Write the dynamic relocations.
470// * Write the rest of the file.
471// This would have some drawbacks. For example, we would only know if .rela.dyn
472// is needed after applying relocations. If it is, it will go after rw and rx
473// sections. Given that it is ro, we will need an extra PT_LOAD. This
474// complicates things for the dynamic linker and means we would have to reserve
475// space for the extra PT_LOAD even if we end up not using it.
476template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000477static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000478 typedef typename ELFT::uint uintX_t;
479
George Rimardb0168d2016-06-09 15:17:29 +0000480 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000481
482 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
483 Out<ELFT>::RelaDyn->addReloc(Reloc);
484 };
485
486 const elf::ObjectFile<ELFT> &File = *C.getFile();
487 ArrayRef<uint8_t> SectionData = C.getSectionData();
488 const uint8_t *Buf = SectionData.begin();
489 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
490 const RelTy &RI = *I;
491 SymbolBody &Body = File.getRelocTargetSym(RI);
492 uint32_t Type = RI.getType(Config->Mips64EL);
493
494 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000495 bool Preemptible = isPreemptible(Body, Type);
496 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
497 if (HasError)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000498 continue;
499
Rui Ueyama809d8e22016-06-23 04:33:42 +0000500 // Skip a relocation that points to a dead piece
501 // in a mergeable section.
502 if (C.getOffset(RI.r_offset) == (uintX_t)-1)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000503 continue;
504
505 // This relocation does not require got entry, but it is relative to got and
506 // needs it to be created. Here we request for that.
507 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
508 Out<ELFT>::Got->HasGotOffRel = true;
509
510 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
511
Rui Ueyama809d8e22016-06-23 04:33:42 +0000512 if (unsigned Processed = handleTlsRelocation<ELFT>(
513 Type, Body, C, RI.r_offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000514 I += (Processed - 1);
515 continue;
516 }
517
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000518 // Ignore "hint" relocation because it is for optional code optimization.
519 if (Expr == R_HINT)
520 continue;
521
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000522 if (needsPlt(Expr) || Expr == R_THUNK || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000523 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000524 // If the relocation points to something in the file, we can process it.
525 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
526
527 // If the output being produced is position independent, the final value
528 // is still not known. In that case we still need some help from the
529 // dynamic linker. We can however do better than just copying the incoming
530 // relocation. We can process some of it and and just ask the dynamic
531 // linker to add the load address.
532 if (!Constant)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000533 AddDyn({Target->RelativeRel, &C, RI.r_offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000534
535 // If the produced value is a constant, we just remember to write it
536 // when outputting this section. We also have to do it if the format
537 // uses Elf_Rel, since in that case the written value is the addend.
538 if (Constant || !RelTy::IsRela)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000539 C.Relocations.push_back({Expr, Type, &C, RI.r_offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000540 } else {
541 // We don't know anything about the finaly symbol. Just ask the dynamic
542 // linker to handle the relocation for us.
Rui Ueyama809d8e22016-06-23 04:33:42 +0000543 AddDyn({Target->getDynRel(Type), &C, RI.r_offset, false, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000544 // MIPS ABI turns using of GOT and dynamic relocations inside out.
545 // While regular ABI uses dynamic relocations to fill up GOT entries
546 // MIPS ABI requires dynamic linker to fills up GOT entries using
547 // specially sorted dynamic symbol table. This affects even dynamic
548 // relocations against symbols which do not require GOT entries
549 // creation explicitly, i.e. do not have any GOT-relocations. So if
550 // a preemptible symbol has a dynamic relocation we anyway have
551 // to create a GOT entry for it.
552 // If a non-preemptible symbol has a dynamic relocation against it,
553 // dynamic linker takes it st_value, adds offset and writes down
554 // result of the dynamic relocation. In case of preemptible symbol
555 // dynamic linker performs symbol resolution, writes the symbol value
556 // to the GOT entry and reads the GOT entry when it needs to perform
557 // a dynamic relocation.
558 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000559 if (Config->EMachine == EM_MIPS)
560 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000561 continue;
562 }
563
Rui Ueyamad2ada2e2016-06-22 00:57:09 +0000564 // Some targets might require creation of thunks for relocations.
565 // Now we support only MIPS which requires LA25 thunk to call PIC
566 // code from non-PIC one.
567 if (Expr == R_THUNK) {
568 if (!Body.hasThunk()) {
569 auto *Sec = cast<InputSection<ELFT>>(
570 cast<DefinedRegular<ELFT>>(&Body)->Section);
571 Sec->addThunk(Body);
572 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000573 continue;
Rui Ueyamad2ada2e2016-06-22 00:57:09 +0000574 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000575
576 // At this point we are done with the relocated position. Some relocations
577 // also require us to create a got or plt entry.
578
579 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
580 if (needsPlt(Expr)) {
581 if (Body.isInPlt())
582 continue;
583 Out<ELFT>::Plt->addEntry(Body);
584
585 uint32_t Rel;
586 if (Body.isGnuIFunc() && !Preemptible)
587 Rel = Target->IRelativeRel;
588 else
589 Rel = Target->PltRel;
590
591 Out<ELFT>::GotPlt->addEntry(Body);
592 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
593 Body.getGotPltOffset<ELFT>(), !Preemptible,
594 &Body, 0});
595 continue;
596 }
597
598 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000599 if (Config->EMachine == EM_MIPS) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000600 // MIPS ABI has special rules to process GOT entries
601 // and doesn't require relocation entries for them.
602 // See "Global Offset Table" in Chapter 5 in the following document
603 // for detailed description:
604 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan41325112016-06-19 21:39:37 +0000605 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
606 continue;
607 }
608
609 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000610 continue;
611
Simon Atanasyan41325112016-06-19 21:39:37 +0000612 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000613 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
614 uint32_t DynType;
615 if (Body.isTls())
616 DynType = Target->TlsGotRel;
617 else if (Preemptible)
618 DynType = Target->GotRel;
619 else
620 DynType = Target->RelativeRel;
621 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
622 !Preemptible, &Body, 0});
623 }
624 continue;
625 }
626 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000627}
628
629template <class ELFT> void scanRelocations(InputSection<ELFT> &C) {
630 typedef typename ELFT::Shdr Elf_Shdr;
631
632 // Scan all relocations. Each relocation goes through a series
633 // of tests to determine if it needs special treatment, such as
634 // creating GOT, PLT, copy relocations, etc.
635 // Note that relocations for non-alloc sections are directly
Rui Ueyamae178c2f2016-06-20 08:34:50 +0000636 // processed by InputSection::relocateNonAlloc.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000637 if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
638 for (const Elf_Shdr *RelSec : C.RelocSections)
639 scanRelocations(C, *RelSec);
640}
641
642template <class ELFT>
643void scanRelocations(InputSectionBase<ELFT> &S,
644 const typename ELFT::Shdr &RelSec) {
645 ELFFile<ELFT> &EObj = S.getFile()->getObj();
646 if (RelSec.sh_type == SHT_RELA)
647 scanRelocs(S, EObj.relas(&RelSec));
648 else
649 scanRelocs(S, EObj.rels(&RelSec));
650}
651
652template void scanRelocations<ELF32LE>(InputSection<ELF32LE> &);
653template void scanRelocations<ELF32BE>(InputSection<ELF32BE> &);
654template void scanRelocations<ELF64LE>(InputSection<ELF64LE> &);
655template void scanRelocations<ELF64BE>(InputSection<ELF64BE> &);
656
657template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
658 const ELF32LE::Shdr &);
659template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
660 const ELF32BE::Shdr &);
661template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
662 const ELF64LE::Shdr &);
663template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
664 const ELF64BE::Shdr &);
665}
666}