blob: e29df03be9c3ae9bf3f5a2dc7a47b277069255f4 [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
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000146 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
147 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 }
153 if (Expr != R_HINT)
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
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000180 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
181 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 ||
307 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
Peter Smithfb05cd92016-07-08 16:10:27 +0000308 E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE ||
309 E == R_HINT || E == R_THUNK_PC || E == R_THUNK_PLT_PC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000310 return true;
311
312 // These never do, except if the entire file is position dependent or if
313 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000314 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000315 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
316
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000317 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000318 return false;
319
320 if (!Config->Pic)
321 return true;
322
323 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
324 bool RelE = isRelExpr(E);
325 if (AbsVal && !RelE)
326 return true;
327 if (!AbsVal && RelE)
328 return true;
329
330 // Relative relocation to an absolute value. This is normally unrepresentable,
331 // but if the relocation refers to a weak undefined symbol, we allow it to
332 // resolve to the image base. This is a little strange, but it allows us to
333 // link function calls to such symbols. Normally such a call will be guarded
334 // with a comparison, which will load a zero from the GOT.
335 if (AbsVal && RelE) {
336 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
337 return true;
George Rimare6389d12016-06-08 12:22:26 +0000338 error("relocation " + getRelName(Type) +
339 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000340 return true;
341 }
342
343 return Target->usesOnlyLowPageBits(Type);
344}
345
346static RelExpr toPlt(RelExpr Expr) {
347 if (Expr == R_PPC_OPD)
348 return R_PPC_PLT_OPD;
349 if (Expr == R_PC)
350 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000351 if (Expr == R_PAGE_PC)
352 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000353 if (Expr == R_ABS)
354 return R_PLT;
355 return Expr;
356}
357
358static RelExpr fromPlt(RelExpr Expr) {
359 // We decided not to use a plt. Optimize a reference to the plt to a
360 // reference to the symbol itself.
361 if (Expr == R_PLT_PC)
362 return R_PC;
363 if (Expr == R_PPC_PLT_OPD)
364 return R_PPC_OPD;
365 if (Expr == R_PLT)
366 return R_ABS;
367 return Expr;
368}
369
370template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
371 typedef typename ELFT::uint uintX_t;
372
Rui Ueyama434b5612016-07-17 03:11:46 +0000373 uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000374 uintX_t SymValue = SS->Sym.st_value;
375 int TrailingZeros =
376 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
377 return 1 << TrailingZeros;
378}
379
380// Reserve space in .bss for copy relocation.
381template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
382 typedef typename ELFT::uint uintX_t;
383 typedef typename ELFT::Sym Elf_Sym;
384
385 // Copy relocation against zero-sized symbol doesn't make sense.
386 uintX_t SymSize = SS->template getSize<ELFT>();
387 if (SymSize == 0)
Petr Hosek4071b1b2016-08-18 21:55:23 +0000388 fatal("cannot create a copy relocation for symbol " + SS->getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000389
Rui Ueyama424b4082016-06-17 01:18:46 +0000390 uintX_t Alignment = getAlignment(SS);
391 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000392 Out<ELFT>::Bss->setSize(Off + SymSize);
Rui Ueyama424b4082016-06-17 01:18:46 +0000393 Out<ELFT>::Bss->updateAlignment(Alignment);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000394 uintX_t Shndx = SS->Sym.st_shndx;
395 uintX_t Value = SS->Sym.st_value;
396 // Look through the DSO's dynamic symbol table for aliases and create a
397 // dynamic symbol for each one. This causes the copy relocation to correctly
398 // interpose any aliases.
Rui Ueyama434b5612016-07-17 03:11:46 +0000399 for (const Elf_Sym &S : SS->file()->getElfSymbols(true)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000400 if (S.st_shndx != Shndx || S.st_value != Value)
401 continue;
402 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
Rui Ueyama434b5612016-07-17 03:11:46 +0000403 Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000404 if (!Alias)
405 continue;
406 Alias->OffsetInBss = Off;
407 Alias->NeedsCopyOrPltAddr = true;
408 Alias->symbol()->IsUsedInRegularObj = true;
409 }
410 Out<ELFT>::RelaDyn->addReloc(
411 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
412}
413
414template <class ELFT>
Petr Hosek5b4f6c62016-08-22 19:01:53 +0000415static StringRef getSymbolName(const elf::ObjectFile<ELFT> &File,
416 SymbolBody &Body) {
417 if (Body.isLocal() && Body.getNameOffset())
418 return File.getStringTable().data() + Body.getNameOffset();
419 if (!Body.isLocal())
420 return Body.getName();
421 return "";
Petr Hosek4071b1b2016-08-18 21:55:23 +0000422}
423
424template <class ELFT>
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000425static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000426 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000427 const uint8_t *Data) {
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000428 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000429 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000430 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000431 } else if (!Preemptible) {
432 if (needsPlt(Expr))
433 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000434 if (Expr == R_GOT_PC)
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000435 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000436 }
Peter Smithfb05cd92016-07-08 16:10:27 +0000437 Expr = Target->getThunkExpr(Expr, Type, File, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000438
439 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
440 return Expr;
441
442 // This relocation would require the dynamic linker to write a value to read
443 // only memory. We can hack around it if we are producing an executable and
444 // the refered symbol can be preemepted to refer to the executable.
445 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
Petr Hosek5b4f6c62016-08-22 19:01:53 +0000446 StringRef Name = getSymbolName(File, Body);
George Rimara4c7e742016-10-20 08:36:42 +0000447 error("can't create dynamic relocation " + getRelName(Type) + " against " +
448 (Name.empty() ? "readonly segment" : "symbol " + Name));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000449 return Expr;
450 }
451 if (Body.getVisibility() != STV_DEFAULT) {
Petr Hosek4071b1b2016-08-18 21:55:23 +0000452 error("cannot preempt symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000453 return Expr;
454 }
455 if (Body.isObject()) {
456 // Produce a copy relocation.
457 auto *B = cast<SharedSymbol<ELFT>>(&Body);
458 if (!B->needsCopy())
459 addCopyRelSymbol(B);
460 return Expr;
461 }
462 if (Body.isFunc()) {
463 // This handles a non PIC program call to function in a shared library. In
464 // an ideal world, we could just report an error saying the relocation can
465 // overflow at runtime. In the real world with glibc, crt1.o has a
466 // R_X86_64_PC32 pointing to libc.so.
467 //
468 // The general idea on how to handle such cases is to create a PLT entry and
469 // use that as the function value.
470 //
471 // For the static linking part, we just return a plt expr and everything
472 // else will use the the PLT entry as the address.
473 //
474 // The remaining problem is making sure pointer equality still works. We
475 // need the help of the dynamic linker for that. We let it know that we have
476 // a direct reference to a so symbol by creating an undefined symbol with a
477 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
478 // the value of the symbol we created. This is true even for got entries, so
479 // pointer equality is maintained. To avoid an infinite loop, the only entry
480 // that points to the real function is a dedicated got entry used by the
481 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
482 // R_386_JMP_SLOT, etc).
483 Body.NeedsCopyOrPltAddr = true;
484 return toPlt(Expr);
485 }
Petr Hosek4071b1b2016-08-18 21:55:23 +0000486 error("symbol " + Body.getName() + " is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000487
488 return Expr;
489}
490
491template <class ELFT, class RelTy>
492static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
493 const uint8_t *SectionData,
494 const RelTy *End, const RelTy &RI,
495 RelExpr Expr, SymbolBody &Body) {
496 typedef typename ELFT::uint uintX_t;
497
498 uint32_t Type = RI.getType(Config->Mips64EL);
499 uintX_t Addend = getAddend<ELFT>(RI);
500 const uint8_t *BufLoc = SectionData + RI.r_offset;
501 if (!RelTy::IsRela)
502 Addend += Target->getImplicitAddend(BufLoc, Type);
503 if (Config->EMachine == EM_MIPS) {
504 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
505 if (Type == R_MIPS_LO16 && Expr == R_PC)
506 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
507 // symbol. In that case we should use the following formula for
508 // calculation "AHL + GP - P + 4". Let's add 4 right here.
509 // For details see p. 4-19 at
510 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
511 Addend += 4;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000512 if (Expr == R_GOTREL) {
513 Addend -= MipsGPOffset;
514 if (Body.isLocal())
515 Addend += File.getMipsGp0();
516 }
517 }
518 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
519 Addend += getPPC64TocBase();
520 return Addend;
521}
522
Eugene Leviant89837592016-10-06 09:45:04 +0000523static void reportUndefined(SymbolBody &Sym) {
524 if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
525 return;
526
527 if (Config->Shared && Sym.symbol()->Visibility == STV_DEFAULT &&
528 Config->UnresolvedSymbols != UnresolvedPolicy::NoUndef)
529 return;
530
531 std::string Msg = "undefined symbol: ";
532 Msg += Config->Demangle ? demangle(Sym.getName()) : Sym.getName().str();
533
534 if (Sym.File)
535 Msg += " in " + getFilename(Sym.File);
536 if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn)
537 warn(Msg);
538 else
539 error(Msg);
540}
541
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000542// The reason we have to do this early scan is as follows
543// * To mmap the output file, we need to know the size
544// * For that, we need to know how many dynamic relocs we will have.
545// It might be possible to avoid this by outputting the file with write:
546// * Write the allocated output sections, computing addresses.
547// * Apply relocations, recording which ones require a dynamic reloc.
548// * Write the dynamic relocations.
549// * Write the rest of the file.
550// This would have some drawbacks. For example, we would only know if .rela.dyn
551// is needed after applying relocations. If it is, it will go after rw and rx
552// sections. Given that it is ro, we will need an extra PT_LOAD. This
553// complicates things for the dynamic linker and means we would have to reserve
554// space for the extra PT_LOAD even if we end up not using it.
555template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000556static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000557 typedef typename ELFT::uint uintX_t;
558
George Rimardb0168d2016-06-09 15:17:29 +0000559 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000560
561 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
562 Out<ELFT>::RelaDyn->addReloc(Reloc);
563 };
564
565 const elf::ObjectFile<ELFT> &File = *C.getFile();
Rafael Espindolac7e1e032016-09-12 13:13:53 +0000566 ArrayRef<uint8_t> SectionData = C.Data;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000567 const uint8_t *Buf = SectionData.begin();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000568
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000569 ArrayRef<EhSectionPiece> Pieces;
570 if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
571 Pieces = Eh->Pieces;
572
573 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
574 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000575
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000576 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
577 const RelTy &RI = *I;
578 SymbolBody &Body = File.getRelocTargetSym(RI);
579 uint32_t Type = RI.getType(Config->Mips64EL);
580
George Rimara4c7e742016-10-20 08:36:42 +0000581 // We only report undefined symbols if they are referenced somewhere in the
582 // code.
Eugene Leviant89837592016-10-06 09:45:04 +0000583 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
584 reportUndefined(Body);
585
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000586 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000587 bool Preemptible = isPreemptible(Body, Type);
588 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
589 if (HasError)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000590 continue;
591
Rui Ueyama809d8e22016-06-23 04:33:42 +0000592 // Skip a relocation that points to a dead piece
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000593 // in a eh_frame section.
594 while (PieceI != PieceE &&
595 (PieceI->InputOff + PieceI->size() <= RI.r_offset))
596 ++PieceI;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000597
598 // Compute the offset of this section in the output section. We do it here
599 // to try to compute it only once.
600 uintX_t Offset;
601 if (PieceI != PieceE) {
602 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
George Rimare37dde82016-07-21 15:35:06 +0000603 if (PieceI->OutputOff == (size_t)-1)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000604 continue;
605 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000606 } else {
George Rimar3e6833b2016-08-19 15:46:28 +0000607 Offset = RI.r_offset;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000608 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000609
610 // This relocation does not require got entry, but it is relative to got and
611 // needs it to be created. Here we request for that.
Rafael Espindola79202c32016-08-31 23:24:11 +0000612 if (Expr == R_GOTONLY_PC || Expr == R_GOTONLY_PC_FROM_END ||
613 Expr == R_GOTREL || Expr == R_GOTREL_FROM_END || Expr == R_PPC_TOC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000614 Out<ELFT>::Got->HasGotOffRel = true;
615
616 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
617
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000618 if (unsigned Processed =
619 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000620 I += (Processed - 1);
621 continue;
622 }
623
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000624 // Ignore "hint" relocation because it is for optional code optimization.
625 if (Expr == R_HINT)
626 continue;
627
Peter Smithfb05cd92016-07-08 16:10:27 +0000628 if (needsPlt(Expr) || Expr == R_THUNK_ABS || Expr == R_THUNK_PC ||
629 Expr == R_THUNK_PLT_PC || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000630 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000631 // If the relocation points to something in the file, we can process it.
632 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
633
634 // If the output being produced is position independent, the final value
635 // is still not known. In that case we still need some help from the
636 // dynamic linker. We can however do better than just copying the incoming
637 // relocation. We can process some of it and and just ask the dynamic
638 // linker to add the load address.
639 if (!Constant)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000640 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000641
642 // If the produced value is a constant, we just remember to write it
643 // when outputting this section. We also have to do it if the format
644 // uses Elf_Rel, since in that case the written value is the addend.
645 if (Constant || !RelTy::IsRela)
Rafael Espindola664c6522016-09-07 20:37:34 +0000646 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000647 } else {
648 // We don't know anything about the finaly symbol. Just ask the dynamic
649 // linker to handle the relocation for us.
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000650 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000651 // MIPS ABI turns using of GOT and dynamic relocations inside out.
652 // While regular ABI uses dynamic relocations to fill up GOT entries
653 // MIPS ABI requires dynamic linker to fills up GOT entries using
654 // specially sorted dynamic symbol table. This affects even dynamic
655 // relocations against symbols which do not require GOT entries
656 // creation explicitly, i.e. do not have any GOT-relocations. So if
657 // a preemptible symbol has a dynamic relocation we anyway have
658 // to create a GOT entry for it.
659 // If a non-preemptible symbol has a dynamic relocation against it,
660 // dynamic linker takes it st_value, adds offset and writes down
661 // result of the dynamic relocation. In case of preemptible symbol
662 // dynamic linker performs symbol resolution, writes the symbol value
663 // to the GOT entry and reads the GOT entry when it needs to perform
664 // a dynamic relocation.
665 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000666 if (Config->EMachine == EM_MIPS)
667 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000668 continue;
669 }
670
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000671 // At this point we are done with the relocated position. Some relocations
672 // also require us to create a got or plt entry.
673
674 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
675 if (needsPlt(Expr)) {
676 if (Body.isInPlt())
677 continue;
678 Out<ELFT>::Plt->addEntry(Body);
679
680 uint32_t Rel;
681 if (Body.isGnuIFunc() && !Preemptible)
682 Rel = Target->IRelativeRel;
683 else
684 Rel = Target->PltRel;
685
686 Out<ELFT>::GotPlt->addEntry(Body);
687 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
688 Body.getGotPltOffset<ELFT>(), !Preemptible,
689 &Body, 0});
690 continue;
691 }
692
693 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000694 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanaf52f6a2016-09-08 09:07:12 +0000695 // MIPS ABI has special rules to process GOT entries and doesn't
696 // require relocation entries for them. A special case is TLS
697 // relocations. In that case dynamic loader applies dynamic
698 // relocations to initialize TLS GOT entries.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000699 // See "Global Offset Table" in Chapter 5 in the following document
700 // for detailed description:
701 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan41325112016-06-19 21:39:37 +0000702 Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000703 if (Body.isTls() && Body.isPreemptible())
Simon Atanasyan002e2442016-06-23 15:26:31 +0000704 AddDyn({Target->TlsGotRel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000705 false, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000706 continue;
707 }
708
709 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000710 continue;
711
Simon Atanasyan41325112016-06-19 21:39:37 +0000712 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000713 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
714 uint32_t DynType;
715 if (Body.isTls())
716 DynType = Target->TlsGotRel;
717 else if (Preemptible)
718 DynType = Target->GotRel;
719 else
720 DynType = Target->RelativeRel;
721 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
722 !Preemptible, &Body, 0});
723 }
724 continue;
725 }
726 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000727}
728
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000729template <class ELFT>
730void scanRelocations(InputSectionBase<ELFT> &S,
731 const typename ELFT::Shdr &RelSec) {
732 ELFFile<ELFT> &EObj = S.getFile()->getObj();
733 if (RelSec.sh_type == SHT_RELA)
734 scanRelocs(S, EObj.relas(&RelSec));
735 else
736 scanRelocs(S, EObj.rels(&RelSec));
737}
738
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000739template <class ELFT, class RelTy>
740static void createThunks(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
741 const elf::ObjectFile<ELFT> &File = *C.getFile();
742 for (const RelTy &Rel : Rels) {
743 SymbolBody &Body = File.getRelocTargetSym(Rel);
744 uint32_t Type = Rel.getType(Config->Mips64EL);
745 RelExpr Expr = Target->getRelExpr(Type, Body);
746 if (!isPreemptible(Body, Type) && needsPlt(Expr))
747 Expr = fromPlt(Expr);
748 Expr = Target->getThunkExpr(Expr, Type, File, Body);
749 // Some targets might require creation of thunks for relocations.
750 // Now we support only MIPS which requires LA25 thunk to call PIC
751 // code from non-PIC one, and ARM which requires interworking.
752 if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) {
753 auto *Sec = cast<InputSection<ELFT>>(&C);
754 addThunk<ELFT>(Type, Body, *Sec);
755 }
756 }
757}
758
759template <class ELFT>
760void createThunks(InputSectionBase<ELFT> &S,
761 const typename ELFT::Shdr &RelSec) {
762 ELFFile<ELFT> &EObj = S.getFile()->getObj();
763 if (RelSec.sh_type == SHT_RELA)
764 createThunks(S, EObj.relas(&RelSec));
765 else
766 createThunks(S, EObj.rels(&RelSec));
767}
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000768
769template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
770 const ELF32LE::Shdr &);
771template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
772 const ELF32BE::Shdr &);
773template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
774 const ELF64LE::Shdr &);
775template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
776 const ELF64BE::Shdr &);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000777
778template void createThunks<ELF32LE>(InputSectionBase<ELF32LE> &,
779 const ELF32LE::Shdr &);
780template void createThunks<ELF32BE>(InputSectionBase<ELF32BE> &,
781 const ELF32BE::Shdr &);
782template void createThunks<ELF64LE>(InputSectionBase<ELF64LE> &,
783 const ELF64LE::Shdr &);
784template void createThunks<ELF64BE>(InputSectionBase<ELF64BE> &,
785 const ELF64BE::Shdr &);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000786}
787}