blob: a54c449c6440fdd4def3f7374b4259b78f7a9766 [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 ||
Simon Atanasyan002e2442016-06-23 15:26:31 +000063 Expr == R_MIPS_GOT_OFF || Expr == R_MIPS_TLSGD ||
64 Expr == R_MIPS_TLSLD || Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC ||
Simon Atanasyan41325112016-06-19 21:39:37 +000065 Expr == R_GOT_FROM_END || Expr == R_TLSGD || Expr == R_TLSGD_PC ||
66 Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +000067}
68
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000069static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
70 // In case of MIPS GP-relative relocations always resolve to a definition
71 // in a regular input file, ignoring the one-definition rule. So we,
72 // for example, should not attempt to create a dynamic relocation even
73 // if the target symbol is preemptible. There are two two MIPS GP-relative
74 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
75 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000076 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000077 // relocation types occupy eight bit. In case of N64 ABI we extract first
78 // relocation from 3-in-1 packet because only the first relocation can
79 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000080 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000081 return false;
82 return Body.isPreemptible();
83}
84
Simon Atanasyan002e2442016-06-23 15:26:31 +000085// This function is similar to the `handleTlsRelocation`. MIPS does not support
86// any relaxations for TLS relocations so by factoring out MIPS handling into
87// the separate function we can simplify the code and does not pollute
88// `handleTlsRelocation` by MIPS `ifs` statements.
89template <class ELFT>
90static unsigned
91handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body,
92 InputSectionBase<ELFT> &C, typename ELFT::uint Offset,
93 typename ELFT::uint Addend, RelExpr Expr) {
94 if (Expr == R_MIPS_TLSLD) {
95 if (Out<ELFT>::Got->addTlsIndex())
96 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
97 Out<ELFT>::Got->getTlsIndexOff(), false,
98 nullptr, 0});
99 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
100 return 1;
101 }
102 if (Target->isTlsGlobalDynamicRel(Type)) {
103 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
104 typedef typename ELFT::uint uintX_t;
105 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
106 Out<ELFT>::RelaDyn->addReloc(
107 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
108 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
109 Off + (uintX_t)sizeof(uintX_t), false,
110 &Body, 0});
111 }
112 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
113 return 1;
114 }
115 return 0;
116}
117
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000118// Returns the number of relocations processed.
119template <class ELFT>
120static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
121 InputSectionBase<ELFT> &C,
122 typename ELFT::uint Offset,
123 typename ELFT::uint Addend, RelExpr Expr) {
124 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
125 return 0;
126
127 if (!Body.isTls())
128 return 0;
129
130 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000131
Simon Atanasyan002e2442016-06-23 15:26:31 +0000132 if (Config->EMachine == EM_MIPS)
133 return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
134
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000135 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
136 Config->Shared) {
137 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
138 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
139 Out<ELFT>::RelaDyn->addReloc(
140 {Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
141 }
142 if (Expr != R_HINT)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000143 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000144 return 1;
145 }
146
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000147 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
148 // Local-Dynamic relocs can be relaxed to Local-Exec.
149 if (!Config->Shared) {
150 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000151 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000152 return 2;
153 }
154 if (Out<ELFT>::Got->addTlsIndex())
155 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
156 Out<ELFT>::Got->getTlsIndexOff(), false,
157 nullptr, 0});
Rui Ueyama809d8e22016-06-23 04:33:42 +0000158 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000159 return 1;
160 }
161
162 // Local-Dynamic relocs can be relaxed to Local-Exec.
163 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
164 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000165 {R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000166 return 1;
167 }
168
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000169 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
170 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000171 if (Config->Shared) {
172 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
173 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
174 Out<ELFT>::RelaDyn->addReloc(
175 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000176
177 // If the symbol is preemptible we need the dynamic linker to write
178 // the offset too.
Simon Atanasyan9b861182016-06-10 12:26:39 +0000179 if (isPreemptible(Body, Type))
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000180 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
181 Off + (uintX_t)sizeof(uintX_t), false,
182 &Body, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000183 }
Rui Ueyama809d8e22016-06-23 04:33:42 +0000184 C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000185 return 1;
186 }
187
188 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
189 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000190 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000191 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000192 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rui Ueyama809d8e22016-06-23 04:33:42 +0000193 &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000194 if (!Body.isInGot()) {
195 Out<ELFT>::Got->addEntry(Body);
196 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
197 Body.getGotOffset<ELFT>(), false, &Body,
198 0});
199 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000200 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000201 }
202 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000203 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, &C,
Rafael Espindola69f54022016-06-04 23:22:34 +0000204 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000205 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000206 }
207
208 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
209 // defined.
210 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000211 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000212 C.Relocations.push_back(
Rui Ueyama809d8e22016-06-23 04:33:42 +0000213 {R_RELAX_TLS_IE_TO_LE, Type, &C, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000214 return 1;
215 }
216 return 0;
217}
218
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000219template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
220 return read32<E>(Loc) & 0xffff;
221}
222
223template <class RelTy>
224static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
225 switch (Rel->getType(Config->Mips64EL)) {
226 case R_MIPS_HI16:
227 return R_MIPS_LO16;
228 case R_MIPS_GOT16:
229 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
230 case R_MIPS_PCHI16:
231 return R_MIPS_PCLO16;
232 case R_MICROMIPS_HI16:
233 return R_MICROMIPS_LO16;
234 default:
235 return R_MIPS_NONE;
236 }
237}
238
239template <class ELFT, class RelTy>
240static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
241 SymbolBody &Sym, const RelTy *Rel,
242 const RelTy *End) {
243 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
244 uint32_t Type = getMipsPairType(Rel, Sym);
245
246 // Some MIPS relocations use addend calculated from addend of the relocation
247 // itself and addend of paired relocation. ABI requires to compute such
248 // combined addend in case of REL relocation record format only.
249 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
250 if (RelTy::IsRela || Type == R_MIPS_NONE)
251 return 0;
252
253 for (const RelTy *RI = Rel; RI != End; ++RI) {
254 if (RI->getType(Config->Mips64EL) != Type)
255 continue;
256 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
257 continue;
258 const endianness E = ELFT::TargetEndianness;
259 return ((read32<E>(BufLoc) & 0xffff) << 16) +
260 readSignedLo16<E>(Buf + RI->r_offset);
261 }
George Rimare6389d12016-06-08 12:22:26 +0000262 warning("can't find matching " + getRelName(Type) + " relocation for " +
263 getRelName(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000264 return 0;
265}
266
267// True if non-preemptable symbol always has the same value regardless of where
268// the DSO is loaded.
269template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
270 if (Body.isUndefined())
271 return !Body.isLocal() && Body.symbol()->isWeak();
272 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
273 return DR->Section == nullptr; // Absolute symbol.
274 return false;
275}
276
277static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000278 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
279 Expr == R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000280}
281
282// True if this expression is of the form Sym - X, where X is a position in the
283// file (PC, or GOT for example).
284static bool isRelExpr(RelExpr Expr) {
George Rimar5c33b912016-05-25 14:31:37 +0000285 return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Rafael Espindolaa8433c12016-06-01 06:15:22 +0000286 Expr == R_RELAX_GOT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000287}
288
289template <class ELFT>
290static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
291 const SymbolBody &Body) {
292 // These expressions always compute a constant
293 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
Simon Atanasyan002e2442016-06-23 15:26:31 +0000294 E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF || E == R_MIPS_TLSGD ||
295 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
296 E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE || E == R_HINT)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000297 return true;
298
299 // These never do, except if the entire file is position dependent or if
300 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000301 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000302 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
303
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000304 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000305 return false;
306
307 if (!Config->Pic)
308 return true;
309
310 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
311 bool RelE = isRelExpr(E);
312 if (AbsVal && !RelE)
313 return true;
314 if (!AbsVal && RelE)
315 return true;
316
317 // Relative relocation to an absolute value. This is normally unrepresentable,
318 // but if the relocation refers to a weak undefined symbol, we allow it to
319 // resolve to the image base. This is a little strange, but it allows us to
320 // link function calls to such symbols. Normally such a call will be guarded
321 // with a comparison, which will load a zero from the GOT.
322 if (AbsVal && RelE) {
323 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
324 return true;
George Rimare6389d12016-06-08 12:22:26 +0000325 error("relocation " + getRelName(Type) +
326 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000327 return true;
328 }
329
330 return Target->usesOnlyLowPageBits(Type);
331}
332
333static RelExpr toPlt(RelExpr Expr) {
334 if (Expr == R_PPC_OPD)
335 return R_PPC_PLT_OPD;
336 if (Expr == R_PC)
337 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000338 if (Expr == R_PAGE_PC)
339 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000340 if (Expr == R_ABS)
341 return R_PLT;
342 return Expr;
343}
344
345static RelExpr fromPlt(RelExpr Expr) {
346 // We decided not to use a plt. Optimize a reference to the plt to a
347 // reference to the symbol itself.
348 if (Expr == R_PLT_PC)
349 return R_PC;
350 if (Expr == R_PPC_PLT_OPD)
351 return R_PPC_OPD;
352 if (Expr == R_PLT)
353 return R_ABS;
354 return Expr;
355}
356
357template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
358 typedef typename ELFT::uint uintX_t;
359
360 uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
361 uintX_t SymValue = SS->Sym.st_value;
362 int TrailingZeros =
363 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
364 return 1 << TrailingZeros;
365}
366
367// Reserve space in .bss for copy relocation.
368template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
369 typedef typename ELFT::uint uintX_t;
370 typedef typename ELFT::Sym Elf_Sym;
371
372 // Copy relocation against zero-sized symbol doesn't make sense.
373 uintX_t SymSize = SS->template getSize<ELFT>();
374 if (SymSize == 0)
375 fatal("cannot create a copy relocation for " + SS->getName());
376
Rui Ueyama424b4082016-06-17 01:18:46 +0000377 uintX_t Alignment = getAlignment(SS);
378 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000379 Out<ELFT>::Bss->setSize(Off + SymSize);
Rui Ueyama424b4082016-06-17 01:18:46 +0000380 Out<ELFT>::Bss->updateAlignment(Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000381 uintX_t Shndx = SS->Sym.st_shndx;
382 uintX_t Value = SS->Sym.st_value;
383 // Look through the DSO's dynamic symbol table for aliases and create a
384 // dynamic symbol for each one. This causes the copy relocation to correctly
385 // interpose any aliases.
386 for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
387 if (S.st_shndx != Shndx || S.st_value != Value)
388 continue;
389 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
390 Symtab<ELFT>::X->find(check(S.getName(SS->File->getStringTable()))));
391 if (!Alias)
392 continue;
393 Alias->OffsetInBss = Off;
394 Alias->NeedsCopyOrPltAddr = true;
395 Alias->symbol()->IsUsedInRegularObj = true;
396 }
397 Out<ELFT>::RelaDyn->addReloc(
398 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
399}
400
401template <class ELFT>
402static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000403 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000404 const uint8_t *Data) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000405 if (Target->needsThunk(Type, File, Body))
406 return R_THUNK;
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000407 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000408 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000409 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000410 } else if (!Preemptible) {
411 if (needsPlt(Expr))
412 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000413 if (Expr == R_GOT_PC)
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000414 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000415 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000416
417 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
418 return Expr;
419
420 // This relocation would require the dynamic linker to write a value to read
421 // only memory. We can hack around it if we are producing an executable and
422 // the refered symbol can be preemepted to refer to the executable.
423 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
George Rimar3ed2b082016-06-10 08:00:01 +0000424 error("can't create dynamic relocation " + getRelName(Type) +
425 " against readonly segment");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000426 return Expr;
427 }
428 if (Body.getVisibility() != STV_DEFAULT) {
George Rimar35728c32016-06-20 13:48:16 +0000429 error("cannot preempt symbol");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000430 return Expr;
431 }
432 if (Body.isObject()) {
433 // Produce a copy relocation.
434 auto *B = cast<SharedSymbol<ELFT>>(&Body);
435 if (!B->needsCopy())
436 addCopyRelSymbol(B);
437 return Expr;
438 }
439 if (Body.isFunc()) {
440 // This handles a non PIC program call to function in a shared library. In
441 // an ideal world, we could just report an error saying the relocation can
442 // overflow at runtime. In the real world with glibc, crt1.o has a
443 // R_X86_64_PC32 pointing to libc.so.
444 //
445 // The general idea on how to handle such cases is to create a PLT entry and
446 // use that as the function value.
447 //
448 // For the static linking part, we just return a plt expr and everything
449 // else will use the the PLT entry as the address.
450 //
451 // The remaining problem is making sure pointer equality still works. We
452 // need the help of the dynamic linker for that. We let it know that we have
453 // a direct reference to a so symbol by creating an undefined symbol with a
454 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
455 // the value of the symbol we created. This is true even for got entries, so
456 // pointer equality is maintained. To avoid an infinite loop, the only entry
457 // that points to the real function is a dedicated got entry used by the
458 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
459 // R_386_JMP_SLOT, etc).
460 Body.NeedsCopyOrPltAddr = true;
461 return toPlt(Expr);
462 }
George Rimar35728c32016-06-20 13:48:16 +0000463 error("symbol is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000464
465 return Expr;
466}
467
468template <class ELFT, class RelTy>
469static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
470 const uint8_t *SectionData,
471 const RelTy *End, const RelTy &RI,
472 RelExpr Expr, SymbolBody &Body) {
473 typedef typename ELFT::uint uintX_t;
474
475 uint32_t Type = RI.getType(Config->Mips64EL);
476 uintX_t Addend = getAddend<ELFT>(RI);
477 const uint8_t *BufLoc = SectionData + RI.r_offset;
478 if (!RelTy::IsRela)
479 Addend += Target->getImplicitAddend(BufLoc, Type);
480 if (Config->EMachine == EM_MIPS) {
481 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
482 if (Type == R_MIPS_LO16 && Expr == R_PC)
483 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
484 // symbol. In that case we should use the following formula for
485 // calculation "AHL + GP - P + 4". Let's add 4 right here.
486 // For details see p. 4-19 at
487 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
488 Addend += 4;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000489 if (Expr == R_GOTREL) {
490 Addend -= MipsGPOffset;
491 if (Body.isLocal())
492 Addend += File.getMipsGp0();
493 }
494 }
495 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
496 Addend += getPPC64TocBase();
497 return Addend;
498}
499
500// The reason we have to do this early scan is as follows
501// * To mmap the output file, we need to know the size
502// * For that, we need to know how many dynamic relocs we will have.
503// It might be possible to avoid this by outputting the file with write:
504// * Write the allocated output sections, computing addresses.
505// * Apply relocations, recording which ones require a dynamic reloc.
506// * Write the dynamic relocations.
507// * Write the rest of the file.
508// This would have some drawbacks. For example, we would only know if .rela.dyn
509// is needed after applying relocations. If it is, it will go after rw and rx
510// sections. Given that it is ro, we will need an extra PT_LOAD. This
511// complicates things for the dynamic linker and means we would have to reserve
512// space for the extra PT_LOAD even if we end up not using it.
513template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000514static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000515 typedef typename ELFT::uint uintX_t;
516
George Rimardb0168d2016-06-09 15:17:29 +0000517 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000518
519 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
520 Out<ELFT>::RelaDyn->addReloc(Reloc);
521 };
522
523 const elf::ObjectFile<ELFT> &File = *C.getFile();
524 ArrayRef<uint8_t> SectionData = C.getSectionData();
525 const uint8_t *Buf = SectionData.begin();
526 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
527 const RelTy &RI = *I;
528 SymbolBody &Body = File.getRelocTargetSym(RI);
529 uint32_t Type = RI.getType(Config->Mips64EL);
530
531 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000532 bool Preemptible = isPreemptible(Body, Type);
533 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
534 if (HasError)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000535 continue;
536
Rui Ueyama809d8e22016-06-23 04:33:42 +0000537 // Skip a relocation that points to a dead piece
538 // in a mergeable section.
539 if (C.getOffset(RI.r_offset) == (uintX_t)-1)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000540 continue;
541
542 // This relocation does not require got entry, but it is relative to got and
543 // needs it to be created. Here we request for that.
544 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
545 Out<ELFT>::Got->HasGotOffRel = true;
546
547 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
548
Rui Ueyama809d8e22016-06-23 04:33:42 +0000549 if (unsigned Processed = handleTlsRelocation<ELFT>(
550 Type, Body, C, RI.r_offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000551 I += (Processed - 1);
552 continue;
553 }
554
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000555 // Ignore "hint" relocation because it is for optional code optimization.
556 if (Expr == R_HINT)
557 continue;
558
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000559 if (needsPlt(Expr) || Expr == R_THUNK || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000560 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000561 // If the relocation points to something in the file, we can process it.
562 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
563
564 // If the output being produced is position independent, the final value
565 // is still not known. In that case we still need some help from the
566 // dynamic linker. We can however do better than just copying the incoming
567 // relocation. We can process some of it and and just ask the dynamic
568 // linker to add the load address.
569 if (!Constant)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000570 AddDyn({Target->RelativeRel, &C, RI.r_offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000571
572 // If the produced value is a constant, we just remember to write it
573 // when outputting this section. We also have to do it if the format
574 // uses Elf_Rel, since in that case the written value is the addend.
575 if (Constant || !RelTy::IsRela)
Rui Ueyama809d8e22016-06-23 04:33:42 +0000576 C.Relocations.push_back({Expr, Type, &C, RI.r_offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000577 } else {
578 // We don't know anything about the finaly symbol. Just ask the dynamic
579 // linker to handle the relocation for us.
Rui Ueyama809d8e22016-06-23 04:33:42 +0000580 AddDyn({Target->getDynRel(Type), &C, RI.r_offset, false, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000581 // MIPS ABI turns using of GOT and dynamic relocations inside out.
582 // While regular ABI uses dynamic relocations to fill up GOT entries
583 // MIPS ABI requires dynamic linker to fills up GOT entries using
584 // specially sorted dynamic symbol table. This affects even dynamic
585 // relocations against symbols which do not require GOT entries
586 // creation explicitly, i.e. do not have any GOT-relocations. So if
587 // a preemptible symbol has a dynamic relocation we anyway have
588 // to create a GOT entry for it.
589 // If a non-preemptible symbol has a dynamic relocation against it,
590 // dynamic linker takes it st_value, adds offset and writes down
591 // result of the dynamic relocation. In case of preemptible symbol
592 // dynamic linker performs symbol resolution, writes the symbol value
593 // to the GOT entry and reads the GOT entry when it needs to perform
594 // a dynamic relocation.
595 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000596 if (Config->EMachine == EM_MIPS)
597 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000598 continue;
599 }
600
Rui Ueyamad2ada2e2016-06-22 00:57:09 +0000601 // Some targets might require creation of thunks for relocations.
602 // Now we support only MIPS which requires LA25 thunk to call PIC
603 // code from non-PIC one.
604 if (Expr == R_THUNK) {
605 if (!Body.hasThunk()) {
606 auto *Sec = cast<InputSection<ELFT>>(
607 cast<DefinedRegular<ELFT>>(&Body)->Section);
608 Sec->addThunk(Body);
609 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000610 continue;
Rui Ueyamad2ada2e2016-06-22 00:57:09 +0000611 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000612
613 // At this point we are done with the relocated position. Some relocations
614 // also require us to create a got or plt entry.
615
616 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
617 if (needsPlt(Expr)) {
618 if (Body.isInPlt())
619 continue;
620 Out<ELFT>::Plt->addEntry(Body);
621
622 uint32_t Rel;
623 if (Body.isGnuIFunc() && !Preemptible)
624 Rel = Target->IRelativeRel;
625 else
626 Rel = Target->PltRel;
627
628 Out<ELFT>::GotPlt->addEntry(Body);
629 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
630 Body.getGotPltOffset<ELFT>(), !Preemptible,
631 &Body, 0});
632 continue;
633 }
634
635 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000636 if (Config->EMachine == EM_MIPS) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000637 // MIPS ABI has special rules to process GOT entries
638 // and doesn't require relocation entries for them.
639 // See "Global Offset Table" in Chapter 5 in the following document
640 // for detailed description:
641 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan41325112016-06-19 21:39:37 +0000642 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000643 if (Body.isTls())
644 AddDyn({Target->TlsGotRel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
645 !Preemptible, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000646 continue;
647 }
648
649 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000650 continue;
651
Simon Atanasyan41325112016-06-19 21:39:37 +0000652 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000653 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
654 uint32_t DynType;
655 if (Body.isTls())
656 DynType = Target->TlsGotRel;
657 else if (Preemptible)
658 DynType = Target->GotRel;
659 else
660 DynType = Target->RelativeRel;
661 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
662 !Preemptible, &Body, 0});
663 }
664 continue;
665 }
666 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000667}
668
669template <class ELFT> void scanRelocations(InputSection<ELFT> &C) {
670 typedef typename ELFT::Shdr Elf_Shdr;
671
672 // Scan all relocations. Each relocation goes through a series
673 // of tests to determine if it needs special treatment, such as
674 // creating GOT, PLT, copy relocations, etc.
675 // Note that relocations for non-alloc sections are directly
Rui Ueyamae178c2f2016-06-20 08:34:50 +0000676 // processed by InputSection::relocateNonAlloc.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000677 if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
678 for (const Elf_Shdr *RelSec : C.RelocSections)
679 scanRelocations(C, *RelSec);
680}
681
682template <class ELFT>
683void scanRelocations(InputSectionBase<ELFT> &S,
684 const typename ELFT::Shdr &RelSec) {
685 ELFFile<ELFT> &EObj = S.getFile()->getObj();
686 if (RelSec.sh_type == SHT_RELA)
687 scanRelocs(S, EObj.relas(&RelSec));
688 else
689 scanRelocs(S, EObj.rels(&RelSec));
690}
691
692template void scanRelocations<ELF32LE>(InputSection<ELF32LE> &);
693template void scanRelocations<ELF32BE>(InputSection<ELF32BE> &);
694template void scanRelocations<ELF64LE>(InputSection<ELF64LE> &);
695template void scanRelocations<ELF64BE>(InputSection<ELF64BE> &);
696
697template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
698 const ELF32LE::Shdr &);
699template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
700 const ELF32BE::Shdr &);
701template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
702 const ELF64LE::Shdr &);
703template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
704 const ELF64BE::Shdr &);
705}
706}