blob: d7228f554a4564c35aaf8c74468d6f571e9fa736 [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"
Eugene Leviant89837592016-10-06 09:45:04 +000050#include "Strings.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000051
52#include "llvm/Support/Endian.h"
53#include "llvm/Support/raw_ostream.h"
54
55using namespace llvm;
56using namespace llvm::ELF;
57using namespace llvm::object;
58using namespace llvm::support::endian;
59
60namespace lld {
61namespace elf {
62
63static bool refersToGotEntry(RelExpr Expr) {
Simon Atanasyan41325112016-06-19 21:39:37 +000064 return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL_PAGE ||
Simon Atanasyan002e2442016-06-23 15:26:31 +000065 Expr == R_MIPS_GOT_OFF || Expr == R_MIPS_TLSGD ||
66 Expr == R_MIPS_TLSLD || Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC ||
Simon Atanasyan41325112016-06-19 21:39:37 +000067 Expr == R_GOT_FROM_END || Expr == R_TLSGD || Expr == R_TLSGD_PC ||
68 Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +000069}
70
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000071static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
72 // In case of MIPS GP-relative relocations always resolve to a definition
73 // in a regular input file, ignoring the one-definition rule. So we,
74 // for example, should not attempt to create a dynamic relocation even
75 // if the target symbol is preemptible. There are two two MIPS GP-relative
76 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
77 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000078 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000079 // relocation types occupy eight bit. In case of N64 ABI we extract first
80 // relocation from 3-in-1 packet because only the first relocation can
81 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000082 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000083 return false;
84 return Body.isPreemptible();
85}
86
Peter Smithfde62132016-09-23 13:54:48 +000087// This function is similar to the `handleTlsRelocation`. ARM and MIPS do not
88// support any relaxations for TLS relocations so by factoring out ARM and MIPS
89// handling in to the separate function we can simplify the code and do not
90// pollute `handleTlsRelocation` by ARM and MIPS `ifs` statements.
91// FIXME: The ARM implementation always adds the module index dynamic
92// relocation even for non-preemptible symbols in applications. For static
93// linking support we must either resolve the module index relocation at static
94// link time, or hard code the module index (1) for the application in the GOT.
Simon Atanasyan002e2442016-06-23 15:26:31 +000095template <class ELFT>
Peter Smithfde62132016-09-23 13:54:48 +000096static unsigned handleNoRelaxTlsRelocation(uint32_t Type, SymbolBody &Body,
97 InputSectionBase<ELFT> &C,
98 typename ELFT::uint Offset,
99 typename ELFT::uint Addend,
100 RelExpr Expr) {
101 if (Expr == R_MIPS_TLSLD || Expr == R_TLSLD_PC) {
102 if (Out<ELFT>::Got->addTlsIndex() &&
103 (Config->Pic || Config->EMachine == EM_ARM))
Simon Atanasyan002e2442016-06-23 15:26:31 +0000104 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
105 Out<ELFT>::Got->getTlsIndexOff(), false,
106 nullptr, 0});
Rafael Espindola664c6522016-09-07 20:37:34 +0000107 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000108 return 1;
109 }
Peter Smithfde62132016-09-23 13:54:48 +0000110 typedef typename ELFT::uint uintX_t;
Simon Atanasyan002e2442016-06-23 15:26:31 +0000111 if (Target->isTlsGlobalDynamicRel(Type)) {
Peter Smithfde62132016-09-23 13:54:48 +0000112 if (Out<ELFT>::Got->addDynTlsEntry(Body) &&
113 (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
Simon Atanasyan002e2442016-06-23 15:26:31 +0000114 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
115 Out<ELFT>::RelaDyn->addReloc(
116 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Peter Smithfde62132016-09-23 13:54:48 +0000117 if (Body.isPreemptible())
118 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
119 Off + (uintX_t)sizeof(uintX_t), false,
120 &Body, 0});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000121 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000122 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000123 return 1;
124 }
125 return 0;
126}
127
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000128// Returns the number of relocations processed.
129template <class ELFT>
130static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
131 InputSectionBase<ELFT> &C,
132 typename ELFT::uint Offset,
133 typename ELFT::uint Addend, RelExpr Expr) {
134 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
135 return 0;
136
137 if (!Body.isTls())
138 return 0;
139
140 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000141
Peter Smithfde62132016-09-23 13:54:48 +0000142 if (Config->EMachine == EM_MIPS || Config->EMachine == EM_ARM)
143 return handleNoRelaxTlsRelocation<ELFT>(Type, Body, C, Offset, Addend,
144 Expr);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000145
Peter Smithd6486032016-10-20 09:59:26 +0000146 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC_CALL) &&
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000147 Config->Shared) {
148 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
149 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
150 Out<ELFT>::RelaDyn->addReloc(
151 {Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
152 }
Peter Smithd6486032016-10-20 09:59:26 +0000153 if (Expr != R_TLSDESC_CALL)
Rafael Espindola664c6522016-09-07 20:37:34 +0000154 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000155 return 1;
156 }
157
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000158 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
159 // Local-Dynamic relocs can be relaxed to Local-Exec.
160 if (!Config->Shared) {
161 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000162 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000163 return 2;
164 }
165 if (Out<ELFT>::Got->addTlsIndex())
166 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
167 Out<ELFT>::Got->getTlsIndexOff(), false,
168 nullptr, 0});
Rafael Espindola664c6522016-09-07 20:37:34 +0000169 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000170 return 1;
171 }
172
173 // Local-Dynamic relocs can be relaxed to Local-Exec.
174 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
175 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000176 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000177 return 1;
178 }
179
Peter Smithd6486032016-10-20 09:59:26 +0000180 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_TLSDESC_CALL ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000181 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000182 if (Config->Shared) {
183 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
184 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
185 Out<ELFT>::RelaDyn->addReloc(
186 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000187
188 // If the symbol is preemptible we need the dynamic linker to write
189 // the offset too.
Simon Atanasyan9b861182016-06-10 12:26:39 +0000190 if (isPreemptible(Body, Type))
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000191 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
192 Off + (uintX_t)sizeof(uintX_t), false,
193 &Body, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000194 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000195 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000196 return 1;
197 }
198
199 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
200 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000201 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000202 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000203 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rafael Espindola664c6522016-09-07 20:37:34 +0000204 Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000205 if (!Body.isInGot()) {
206 Out<ELFT>::Got->addEntry(Body);
207 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
208 Body.getGotOffset<ELFT>(), false, &Body,
209 0});
210 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000211 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000212 }
213 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000214 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
Rafael Espindola69f54022016-06-04 23:22:34 +0000215 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000216 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000217 }
218
219 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
220 // defined.
221 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000222 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000223 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000224 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000225 return 1;
226 }
227 return 0;
228}
229
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000230template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
231 return read32<E>(Loc) & 0xffff;
232}
233
234template <class RelTy>
235static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
236 switch (Rel->getType(Config->Mips64EL)) {
237 case R_MIPS_HI16:
238 return R_MIPS_LO16;
239 case R_MIPS_GOT16:
240 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
241 case R_MIPS_PCHI16:
242 return R_MIPS_PCLO16;
243 case R_MICROMIPS_HI16:
244 return R_MICROMIPS_LO16;
245 default:
246 return R_MIPS_NONE;
247 }
248}
249
250template <class ELFT, class RelTy>
251static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
252 SymbolBody &Sym, const RelTy *Rel,
253 const RelTy *End) {
254 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
255 uint32_t Type = getMipsPairType(Rel, Sym);
256
257 // Some MIPS relocations use addend calculated from addend of the relocation
258 // itself and addend of paired relocation. ABI requires to compute such
259 // combined addend in case of REL relocation record format only.
260 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
261 if (RelTy::IsRela || Type == R_MIPS_NONE)
262 return 0;
263
264 for (const RelTy *RI = Rel; RI != End; ++RI) {
265 if (RI->getType(Config->Mips64EL) != Type)
266 continue;
267 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
268 continue;
269 const endianness E = ELFT::TargetEndianness;
270 return ((read32<E>(BufLoc) & 0xffff) << 16) +
271 readSignedLo16<E>(Buf + RI->r_offset);
272 }
Rui Ueyamad31e13f2016-09-29 21:00:23 +0000273 warn("can't find matching " + getRelName(Type) + " relocation for " +
George Rimara4c7e742016-10-20 08:36:42 +0000274 getRelName(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000275 return 0;
276}
277
278// True if non-preemptable symbol always has the same value regardless of where
279// the DSO is loaded.
280template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
281 if (Body.isUndefined())
282 return !Body.isLocal() && Body.symbol()->isWeak();
283 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
284 return DR->Section == nullptr; // Absolute symbol.
285 return false;
286}
287
288static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000289 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
Peter Smithfb05cd92016-07-08 16:10:27 +0000290 Expr == R_PLT_PAGE_PC || Expr == R_THUNK_PLT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000291}
292
293// True if this expression is of the form Sym - X, where X is a position in the
294// file (PC, or GOT for example).
295static bool isRelExpr(RelExpr Expr) {
Rafael Espindola719f55d2016-09-06 13:57:15 +0000296 return Expr == R_PC || Expr == R_GOTREL || Expr == R_GOTREL_FROM_END ||
297 Expr == R_PAGE_PC || Expr == R_RELAX_GOT_PC || Expr == R_THUNK_PC ||
298 Expr == R_THUNK_PLT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000299}
300
301template <class ELFT>
302static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
303 const SymbolBody &Body) {
304 // These expressions always compute a constant
305 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
Simon Atanasyan002e2442016-06-23 15:26:31 +0000306 E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF || E == R_MIPS_TLSGD ||
Peter Smithd6486032016-10-20 09:59:26 +0000307 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC ||
308 E == R_TLSGD_PC || E == R_TLSGD || E == R_PPC_PLT_OPD ||
309 E == R_TLSDESC_CALL || E == R_TLSDESC_PAGE || E == R_HINT ||
310 E == R_THUNK_PC || E == R_THUNK_PLT_PC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000311 return true;
312
313 // These never do, except if the entire file is position dependent or if
314 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000315 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000316 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
317
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000318 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000319 return false;
320
321 if (!Config->Pic)
322 return true;
323
324 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
325 bool RelE = isRelExpr(E);
326 if (AbsVal && !RelE)
327 return true;
328 if (!AbsVal && RelE)
329 return true;
330
331 // Relative relocation to an absolute value. This is normally unrepresentable,
332 // but if the relocation refers to a weak undefined symbol, we allow it to
333 // resolve to the image base. This is a little strange, but it allows us to
334 // link function calls to such symbols. Normally such a call will be guarded
335 // with a comparison, which will load a zero from the GOT.
336 if (AbsVal && RelE) {
337 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
338 return true;
George Rimare6389d12016-06-08 12:22:26 +0000339 error("relocation " + getRelName(Type) +
340 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000341 return true;
342 }
343
344 return Target->usesOnlyLowPageBits(Type);
345}
346
347static RelExpr toPlt(RelExpr Expr) {
348 if (Expr == R_PPC_OPD)
349 return R_PPC_PLT_OPD;
350 if (Expr == R_PC)
351 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000352 if (Expr == R_PAGE_PC)
353 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000354 if (Expr == R_ABS)
355 return R_PLT;
356 return Expr;
357}
358
359static RelExpr fromPlt(RelExpr Expr) {
360 // We decided not to use a plt. Optimize a reference to the plt to a
361 // reference to the symbol itself.
362 if (Expr == R_PLT_PC)
363 return R_PC;
364 if (Expr == R_PPC_PLT_OPD)
365 return R_PPC_OPD;
366 if (Expr == R_PLT)
367 return R_ABS;
368 return Expr;
369}
370
371template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
372 typedef typename ELFT::uint uintX_t;
373
Rui Ueyama434b5612016-07-17 03:11:46 +0000374 uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000375 uintX_t SymValue = SS->Sym.st_value;
376 int TrailingZeros =
377 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
378 return 1 << TrailingZeros;
379}
380
381// Reserve space in .bss for copy relocation.
382template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
383 typedef typename ELFT::uint uintX_t;
384 typedef typename ELFT::Sym Elf_Sym;
385
386 // Copy relocation against zero-sized symbol doesn't make sense.
387 uintX_t SymSize = SS->template getSize<ELFT>();
388 if (SymSize == 0)
Petr Hosek4071b1b2016-08-18 21:55:23 +0000389 fatal("cannot create a copy relocation for symbol " + SS->getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000390
Rui Ueyama424b4082016-06-17 01:18:46 +0000391 uintX_t Alignment = getAlignment(SS);
392 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000393 Out<ELFT>::Bss->setSize(Off + SymSize);
Rui Ueyama424b4082016-06-17 01:18:46 +0000394 Out<ELFT>::Bss->updateAlignment(Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000395 uintX_t Shndx = SS->Sym.st_shndx;
396 uintX_t Value = SS->Sym.st_value;
397 // Look through the DSO's dynamic symbol table for aliases and create a
398 // dynamic symbol for each one. This causes the copy relocation to correctly
399 // interpose any aliases.
Rui Ueyama434b5612016-07-17 03:11:46 +0000400 for (const Elf_Sym &S : SS->file()->getElfSymbols(true)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000401 if (S.st_shndx != Shndx || S.st_value != Value)
402 continue;
403 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
Rui Ueyama434b5612016-07-17 03:11:46 +0000404 Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000405 if (!Alias)
406 continue;
407 Alias->OffsetInBss = Off;
408 Alias->NeedsCopyOrPltAddr = true;
409 Alias->symbol()->IsUsedInRegularObj = true;
410 }
411 Out<ELFT>::RelaDyn->addReloc(
412 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
413}
414
415template <class ELFT>
Petr Hosek5b4f6c62016-08-22 19:01:53 +0000416static StringRef getSymbolName(const elf::ObjectFile<ELFT> &File,
417 SymbolBody &Body) {
418 if (Body.isLocal() && Body.getNameOffset())
419 return File.getStringTable().data() + Body.getNameOffset();
420 if (!Body.isLocal())
421 return Body.getName();
422 return "";
Petr Hosek4071b1b2016-08-18 21:55:23 +0000423}
424
425template <class ELFT>
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000426static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000427 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000428 const uint8_t *Data) {
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000429 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000430 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000431 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000432 } else if (!Preemptible) {
433 if (needsPlt(Expr))
434 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000435 if (Expr == R_GOT_PC)
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000436 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000437 }
Peter Smithfb05cd92016-07-08 16:10:27 +0000438 Expr = Target->getThunkExpr(Expr, Type, File, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000439
440 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
441 return Expr;
442
443 // This relocation would require the dynamic linker to write a value to read
444 // only memory. We can hack around it if we are producing an executable and
445 // the refered symbol can be preemepted to refer to the executable.
446 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
Petr Hosek5b4f6c62016-08-22 19:01:53 +0000447 StringRef Name = getSymbolName(File, Body);
George Rimara4c7e742016-10-20 08:36:42 +0000448 error("can't create dynamic relocation " + getRelName(Type) + " against " +
449 (Name.empty() ? "readonly segment" : "symbol " + Name));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000450 return Expr;
451 }
452 if (Body.getVisibility() != STV_DEFAULT) {
Petr Hosek4071b1b2016-08-18 21:55:23 +0000453 error("cannot preempt symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000454 return Expr;
455 }
456 if (Body.isObject()) {
457 // Produce a copy relocation.
458 auto *B = cast<SharedSymbol<ELFT>>(&Body);
459 if (!B->needsCopy())
460 addCopyRelSymbol(B);
461 return Expr;
462 }
463 if (Body.isFunc()) {
464 // This handles a non PIC program call to function in a shared library. In
465 // an ideal world, we could just report an error saying the relocation can
466 // overflow at runtime. In the real world with glibc, crt1.o has a
467 // R_X86_64_PC32 pointing to libc.so.
468 //
469 // The general idea on how to handle such cases is to create a PLT entry and
470 // use that as the function value.
471 //
472 // For the static linking part, we just return a plt expr and everything
473 // else will use the the PLT entry as the address.
474 //
475 // The remaining problem is making sure pointer equality still works. We
476 // need the help of the dynamic linker for that. We let it know that we have
477 // a direct reference to a so symbol by creating an undefined symbol with a
478 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
479 // the value of the symbol we created. This is true even for got entries, so
480 // pointer equality is maintained. To avoid an infinite loop, the only entry
481 // that points to the real function is a dedicated got entry used by the
482 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
483 // R_386_JMP_SLOT, etc).
484 Body.NeedsCopyOrPltAddr = true;
485 return toPlt(Expr);
486 }
Petr Hosek4071b1b2016-08-18 21:55:23 +0000487 error("symbol " + Body.getName() + " is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000488
489 return Expr;
490}
491
492template <class ELFT, class RelTy>
493static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
494 const uint8_t *SectionData,
495 const RelTy *End, const RelTy &RI,
496 RelExpr Expr, SymbolBody &Body) {
497 typedef typename ELFT::uint uintX_t;
498
499 uint32_t Type = RI.getType(Config->Mips64EL);
500 uintX_t Addend = getAddend<ELFT>(RI);
501 const uint8_t *BufLoc = SectionData + RI.r_offset;
502 if (!RelTy::IsRela)
503 Addend += Target->getImplicitAddend(BufLoc, Type);
504 if (Config->EMachine == EM_MIPS) {
505 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
506 if (Type == R_MIPS_LO16 && Expr == R_PC)
507 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
508 // symbol. In that case we should use the following formula for
509 // calculation "AHL + GP - P + 4". Let's add 4 right here.
510 // For details see p. 4-19 at
511 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
512 Addend += 4;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000513 if (Expr == R_GOTREL) {
514 Addend -= MipsGPOffset;
515 if (Body.isLocal())
516 Addend += File.getMipsGp0();
517 }
518 }
519 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
520 Addend += getPPC64TocBase();
521 return Addend;
522}
523
Eugene Leviant89837592016-10-06 09:45:04 +0000524static void reportUndefined(SymbolBody &Sym) {
525 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
526 return;
527
528 if (Config->Shared && Sym.symbol()->Visibility == STV_DEFAULT &&
529 Config->UnresolvedSymbols != UnresolvedPolicy::NoUndef)
530 return;
531
532 std::string Msg = "undefined symbol: ";
533 Msg += Config->Demangle ? demangle(Sym.getName()) : Sym.getName().str();
534
535 if (Sym.File)
536 Msg += " in " + getFilename(Sym.File);
537 if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn)
538 warn(Msg);
539 else
540 error(Msg);
541}
542
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000543// The reason we have to do this early scan is as follows
544// * To mmap the output file, we need to know the size
545// * For that, we need to know how many dynamic relocs we will have.
546// It might be possible to avoid this by outputting the file with write:
547// * Write the allocated output sections, computing addresses.
548// * Apply relocations, recording which ones require a dynamic reloc.
549// * Write the dynamic relocations.
550// * Write the rest of the file.
551// This would have some drawbacks. For example, we would only know if .rela.dyn
552// is needed after applying relocations. If it is, it will go after rw and rx
553// sections. Given that it is ro, we will need an extra PT_LOAD. This
554// complicates things for the dynamic linker and means we would have to reserve
555// space for the extra PT_LOAD even if we end up not using it.
556template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000557static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000558 typedef typename ELFT::uint uintX_t;
559
George Rimardb0168d2016-06-09 15:17:29 +0000560 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000561
562 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
563 Out<ELFT>::RelaDyn->addReloc(Reloc);
564 };
565
566 const elf::ObjectFile<ELFT> &File = *C.getFile();
Rafael Espindolac7e1e032016-09-12 13:13:53 +0000567 ArrayRef<uint8_t> SectionData = C.Data;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000568 const uint8_t *Buf = SectionData.begin();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000569
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000570 ArrayRef<EhSectionPiece> Pieces;
571 if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
572 Pieces = Eh->Pieces;
573
574 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
575 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000576
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000577 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
578 const RelTy &RI = *I;
579 SymbolBody &Body = File.getRelocTargetSym(RI);
580 uint32_t Type = RI.getType(Config->Mips64EL);
581
George Rimara4c7e742016-10-20 08:36:42 +0000582 // We only report undefined symbols if they are referenced somewhere in the
583 // code.
Eugene Leviant89837592016-10-06 09:45:04 +0000584 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
585 reportUndefined(Body);
586
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000587 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000588 bool Preemptible = isPreemptible(Body, Type);
589 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
590 if (HasError)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000591 continue;
592
Rui Ueyama809d8e22016-06-23 04:33:42 +0000593 // Skip a relocation that points to a dead piece
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000594 // in a eh_frame section.
595 while (PieceI != PieceE &&
596 (PieceI->InputOff + PieceI->size() <= RI.r_offset))
597 ++PieceI;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000598
599 // Compute the offset of this section in the output section. We do it here
600 // to try to compute it only once.
601 uintX_t Offset;
602 if (PieceI != PieceE) {
603 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
George Rimare37dde82016-07-21 15:35:06 +0000604 if (PieceI->OutputOff == (size_t)-1)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000605 continue;
606 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000607 } else {
George Rimar3e6833b2016-08-19 15:46:28 +0000608 Offset = RI.r_offset;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000609 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000610
611 // This relocation does not require got entry, but it is relative to got and
612 // needs it to be created. Here we request for that.
Rafael Espindola79202c32016-08-31 23:24:11 +0000613 if (Expr == R_GOTONLY_PC || Expr == R_GOTONLY_PC_FROM_END ||
614 Expr == R_GOTREL || Expr == R_GOTREL_FROM_END || Expr == R_PPC_TOC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000615 Out<ELFT>::Got->HasGotOffRel = true;
616
617 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
618
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000619 if (unsigned Processed =
620 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000621 I += (Processed - 1);
622 continue;
623 }
624
Peter Smithd6486032016-10-20 09:59:26 +0000625 // Ignore "hint" and TLS Descriptor call relocation because they are
626 // only markers for relaxation.
627 if (Expr == R_HINT || Expr == R_TLSDESC_CALL)
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000628 continue;
629
Peter Smithfb05cd92016-07-08 16:10:27 +0000630 if (needsPlt(Expr) || Expr == R_THUNK_ABS || Expr == R_THUNK_PC ||
631 Expr == R_THUNK_PLT_PC || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000632 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000633 // If the relocation points to something in the file, we can process it.
634 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
635
636 // If the output being produced is position independent, the final value
637 // is still not known. In that case we still need some help from the
638 // dynamic linker. We can however do better than just copying the incoming
639 // relocation. We can process some of it and and just ask the dynamic
640 // linker to add the load address.
641 if (!Constant)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000642 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000643
644 // If the produced value is a constant, we just remember to write it
645 // when outputting this section. We also have to do it if the format
646 // uses Elf_Rel, since in that case the written value is the addend.
647 if (Constant || !RelTy::IsRela)
Rafael Espindola664c6522016-09-07 20:37:34 +0000648 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000649 } else {
650 // We don't know anything about the finaly symbol. Just ask the dynamic
651 // linker to handle the relocation for us.
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000652 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000653 // MIPS ABI turns using of GOT and dynamic relocations inside out.
654 // While regular ABI uses dynamic relocations to fill up GOT entries
655 // MIPS ABI requires dynamic linker to fills up GOT entries using
656 // specially sorted dynamic symbol table. This affects even dynamic
657 // relocations against symbols which do not require GOT entries
658 // creation explicitly, i.e. do not have any GOT-relocations. So if
659 // a preemptible symbol has a dynamic relocation we anyway have
660 // to create a GOT entry for it.
661 // If a non-preemptible symbol has a dynamic relocation against it,
662 // dynamic linker takes it st_value, adds offset and writes down
663 // result of the dynamic relocation. In case of preemptible symbol
664 // dynamic linker performs symbol resolution, writes the symbol value
665 // to the GOT entry and reads the GOT entry when it needs to perform
666 // a dynamic relocation.
667 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000668 if (Config->EMachine == EM_MIPS)
669 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000670 continue;
671 }
672
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000673 // At this point we are done with the relocated position. Some relocations
674 // also require us to create a got or plt entry.
675
676 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
677 if (needsPlt(Expr)) {
678 if (Body.isInPlt())
679 continue;
680 Out<ELFT>::Plt->addEntry(Body);
681
682 uint32_t Rel;
683 if (Body.isGnuIFunc() && !Preemptible)
684 Rel = Target->IRelativeRel;
685 else
686 Rel = Target->PltRel;
687
688 Out<ELFT>::GotPlt->addEntry(Body);
689 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
690 Body.getGotPltOffset<ELFT>(), !Preemptible,
691 &Body, 0});
692 continue;
693 }
694
695 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000696 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanaf52f6a2016-09-08 09:07:12 +0000697 // MIPS ABI has special rules to process GOT entries and doesn't
698 // require relocation entries for them. A special case is TLS
699 // relocations. In that case dynamic loader applies dynamic
700 // relocations to initialize TLS GOT entries.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000701 // See "Global Offset Table" in Chapter 5 in the following document
702 // for detailed description:
703 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan41325112016-06-19 21:39:37 +0000704 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000705 if (Body.isTls() && Body.isPreemptible())
Simon Atanasyan002e2442016-06-23 15:26:31 +0000706 AddDyn({Target->TlsGotRel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000707 false, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000708 continue;
709 }
710
711 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000712 continue;
713
Simon Atanasyan41325112016-06-19 21:39:37 +0000714 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000715 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
716 uint32_t DynType;
717 if (Body.isTls())
718 DynType = Target->TlsGotRel;
719 else if (Preemptible)
720 DynType = Target->GotRel;
721 else
722 DynType = Target->RelativeRel;
723 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
724 !Preemptible, &Body, 0});
725 }
726 continue;
727 }
728 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000729}
730
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000731template <class ELFT>
732void scanRelocations(InputSectionBase<ELFT> &S,
733 const typename ELFT::Shdr &RelSec) {
734 ELFFile<ELFT> &EObj = S.getFile()->getObj();
735 if (RelSec.sh_type == SHT_RELA)
736 scanRelocs(S, EObj.relas(&RelSec));
737 else
738 scanRelocs(S, EObj.rels(&RelSec));
739}
740
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000741template <class ELFT, class RelTy>
742static void createThunks(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
743 const elf::ObjectFile<ELFT> &File = *C.getFile();
744 for (const RelTy &Rel : Rels) {
745 SymbolBody &Body = File.getRelocTargetSym(Rel);
746 uint32_t Type = Rel.getType(Config->Mips64EL);
747 RelExpr Expr = Target->getRelExpr(Type, Body);
748 if (!isPreemptible(Body, Type) && needsPlt(Expr))
749 Expr = fromPlt(Expr);
750 Expr = Target->getThunkExpr(Expr, Type, File, Body);
751 // Some targets might require creation of thunks for relocations.
752 // Now we support only MIPS which requires LA25 thunk to call PIC
753 // code from non-PIC one, and ARM which requires interworking.
754 if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) {
755 auto *Sec = cast<InputSection<ELFT>>(&C);
756 addThunk<ELFT>(Type, Body, *Sec);
757 }
758 }
759}
760
761template <class ELFT>
762void createThunks(InputSectionBase<ELFT> &S,
763 const typename ELFT::Shdr &RelSec) {
764 ELFFile<ELFT> &EObj = S.getFile()->getObj();
765 if (RelSec.sh_type == SHT_RELA)
766 createThunks(S, EObj.relas(&RelSec));
767 else
768 createThunks(S, EObj.rels(&RelSec));
769}
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000770
771template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
772 const ELF32LE::Shdr &);
773template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
774 const ELF32BE::Shdr &);
775template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
776 const ELF64LE::Shdr &);
777template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
778 const ELF64BE::Shdr &);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000779
780template void createThunks<ELF32LE>(InputSectionBase<ELF32LE> &,
781 const ELF32LE::Shdr &);
782template void createThunks<ELF32BE>(InputSectionBase<ELF32BE> &,
783 const ELF32BE::Shdr &);
784template void createThunks<ELF64LE>(InputSectionBase<ELF64LE> &,
785 const ELF64LE::Shdr &);
786template void createThunks<ELF64BE>(InputSectionBase<ELF64BE> &,
787 const ELF64BE::Shdr &);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000788}
789}