blob: 82724bb55a4624cac930021bdecc24c1dbf55ca8 [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"
Peter Smith3a52eb02017-02-01 10:26:03 +000046#include "Memory.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000047#include "OutputSections.h"
Eugene Leviant41ca3272016-11-10 09:48:29 +000048#include "Strings.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000049#include "SymbolTable.h"
Eugene Leviant41ca3272016-11-10 09:48:29 +000050#include "SyntheticSections.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000051#include "Target.h"
Peter Smithfb05cd92016-07-08 16:10:27 +000052#include "Thunks.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000053
54#include "llvm/Support/Endian.h"
55#include "llvm/Support/raw_ostream.h"
Peter Smith3a52eb02017-02-01 10:26:03 +000056#include <algorithm>
Rui Ueyama0fcdc732016-05-24 20:24:43 +000057
58using namespace llvm;
59using namespace llvm::ELF;
60using namespace llvm::object;
61using namespace llvm::support::endian;
62
63namespace lld {
64namespace elf {
65
66static bool refersToGotEntry(RelExpr Expr) {
Sean Silva2eed7592016-12-01 05:43:48 +000067 return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
68 R_MIPS_GOT_OFF32, R_MIPS_TLSGD, R_MIPS_TLSLD,
69 R_GOT_PAGE_PC, R_GOT_PC, R_GOT_FROM_END, R_TLSGD,
70 R_TLSGD_PC, R_TLSDESC, R_TLSDESC_PAGE>(Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +000071}
72
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000073static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
74 // In case of MIPS GP-relative relocations always resolve to a definition
75 // in a regular input file, ignoring the one-definition rule. So we,
76 // for example, should not attempt to create a dynamic relocation even
77 // if the target symbol is preemptible. There are two two MIPS GP-relative
78 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
79 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000080 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000081 // relocation types occupy eight bit. In case of N64 ABI we extract first
82 // relocation from 3-in-1 packet because only the first relocation can
83 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000084 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000085 return false;
86 return Body.isPreemptible();
87}
88
Peter Smithfde62132016-09-23 13:54:48 +000089// This function is similar to the `handleTlsRelocation`. ARM and MIPS do not
90// support any relaxations for TLS relocations so by factoring out ARM and MIPS
91// handling in to the separate function we can simplify the code and do not
92// pollute `handleTlsRelocation` by ARM and MIPS `ifs` statements.
Simon Atanasyan725dc142016-11-16 21:01:02 +000093template <class ELFT, class GOT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +000094static unsigned
95handleNoRelaxTlsRelocation(GOT *Got, uint32_t Type, SymbolBody &Body,
96 InputSectionBase &C, typename ELFT::uint Offset,
97 int64_t Addend, RelExpr Expr) {
Peter Smithde3e7382016-11-29 16:23:50 +000098 typedef typename ELFT::uint uintX_t;
99 auto addModuleReloc = [](SymbolBody &Body, GOT *Got, uintX_t Off, bool LD) {
100 // The Dynamic TLS Module Index Relocation can be statically resolved to 1
101 // if we know that we are linking an executable. For ARM we resolve the
102 // relocation when writing the Got. MIPS has a custom Got implementation
103 // that writes the Module index in directly.
Rui Ueyama104e2352017-02-14 05:45:47 +0000104 if (!Body.isPreemptible() && !Config->pic() && Config->EMachine == EM_ARM)
Peter Smithde3e7382016-11-29 16:23:50 +0000105 Got->Relocations.push_back(
106 {R_ABS, Target->TlsModuleIndexRel, Off, 0, &Body});
107 else {
108 SymbolBody *Dest = LD ? nullptr : &Body;
109 In<ELFT>::RelaDyn->addReloc(
110 {Target->TlsModuleIndexRel, Got, Off, false, Dest, 0});
111 }
112 };
Rui Ueyamacd19b032017-02-16 06:24:16 +0000113 if (isRelExprOneOf<R_MIPS_TLSLD, R_TLSLD_PC>(Expr)) {
Rui Ueyama104e2352017-02-14 05:45:47 +0000114 if (Got->addTlsIndex() && (Config->pic() || Config->EMachine == EM_ARM))
Peter Smithde3e7382016-11-29 16:23:50 +0000115 addModuleReloc(Body, Got, Got->getTlsIndexOff(), true);
Rafael Espindola664c6522016-09-07 20:37:34 +0000116 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000117 return 1;
118 }
119 if (Target->isTlsGlobalDynamicRel(Type)) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000120 if (Got->addDynTlsEntry(Body) &&
Peter Smithfde62132016-09-23 13:54:48 +0000121 (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000122 uintX_t Off = Got->getGlobalDynOffset(Body);
Peter Smithde3e7382016-11-29 16:23:50 +0000123 addModuleReloc(Body, Got, Off, false);
Peter Smithfde62132016-09-23 13:54:48 +0000124 if (Body.isPreemptible())
Simon Atanasyan725dc142016-11-16 21:01:02 +0000125 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Got,
Eugene Levianta96d9022016-11-16 10:02:27 +0000126 Off + (uintX_t)sizeof(uintX_t), false,
127 &Body, 0});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000128 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000129 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000130 return 1;
131 }
132 return 0;
133}
134
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000135// Returns the number of relocations processed.
136template <class ELFT>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000137static unsigned
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000138handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C,
Rafael Espindola7386cea2017-02-16 00:12:34 +0000139 typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000140 if (!(C.Flags & SHF_ALLOC))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000141 return 0;
142
143 if (!Body.isTls())
144 return 0;
145
146 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000147
Simon Atanasyan725dc142016-11-16 21:01:02 +0000148 if (Config->EMachine == EM_ARM)
149 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::Got, Type, Body, C,
150 Offset, Addend, Expr);
151 if (Config->EMachine == EM_MIPS)
152 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::MipsGot, Type, Body, C,
153 Offset, Addend, Expr);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000154
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000155 bool IsPreemptible = isPreemptible(Body, Type);
Rui Ueyamacd19b032017-02-16 06:24:16 +0000156 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000157 Config->Shared) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000158 if (In<ELFT>::Got->addDynTlsEntry(Body)) {
159 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
Adhemerval Zanella86513f02016-12-19 11:58:01 +0000160 In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off,
Rafael Espindola29982b02016-12-19 16:50:20 +0000161 !IsPreemptible, &Body, 0});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000162 }
Peter Smithd6486032016-10-20 09:59:26 +0000163 if (Expr != R_TLSDESC_CALL)
Rafael Espindola664c6522016-09-07 20:37:34 +0000164 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000165 return 1;
166 }
167
Rui Ueyamacd19b032017-02-16 06:24:16 +0000168 if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000169 // Local-Dynamic relocs can be relaxed to Local-Exec.
170 if (!Config->Shared) {
171 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000172 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000173 return 2;
174 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000175 if (In<ELFT>::Got->addTlsIndex())
Eugene Levianta96d9022016-11-16 10:02:27 +0000176 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
177 In<ELFT>::Got->getTlsIndexOff(), false,
178 nullptr, 0});
Rafael Espindola664c6522016-09-07 20:37:34 +0000179 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000180 return 1;
181 }
182
183 // Local-Dynamic relocs can be relaxed to Local-Exec.
184 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
185 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000186 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000187 return 1;
188 }
189
Rui Ueyamacd19b032017-02-16 06:24:16 +0000190 if (isRelExprOneOf<R_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL>(Expr) ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000191 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000192 if (Config->Shared) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000193 if (In<ELFT>::Got->addDynTlsEntry(Body)) {
194 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
Eugene Levianta96d9022016-11-16 10:02:27 +0000195 In<ELFT>::RelaDyn->addReloc(
Eugene Leviantad4439e2016-11-11 11:33:32 +0000196 {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000197
198 // If the symbol is preemptible we need the dynamic linker to write
199 // the offset too.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000200 uintX_t OffsetOff = Off + (uintX_t)sizeof(uintX_t);
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000201 if (IsPreemptible)
Eugene Levianta96d9022016-11-16 10:02:27 +0000202 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000203 OffsetOff, false, &Body, 0});
204 else
205 In<ELFT>::Got->Relocations.push_back(
206 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000207 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000208 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000209 return 1;
210 }
211
212 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
213 // depending on the symbol being locally defined or not.
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000214 if (IsPreemptible) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000215 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000216 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rafael Espindola664c6522016-09-07 20:37:34 +0000217 Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000218 if (!Body.isInGot()) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000219 In<ELFT>::Got->addEntry(Body);
Eugene Levianta96d9022016-11-16 10:02:27 +0000220 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got,
221 Body.getGotOffset<ELFT>(), false, &Body,
222 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000223 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000224 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000225 }
226 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000227 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
Rafael Espindola69f54022016-06-04 23:22:34 +0000228 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000229 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000230 }
231
232 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
233 // defined.
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000234 if (Target->isTlsInitialExecRel(Type) && !Config->Shared && !IsPreemptible) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000235 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000236 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000237 return 1;
238 }
239 return 0;
240}
241
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000242template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
243 return read32<E>(Loc) & 0xffff;
244}
245
246template <class RelTy>
247static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000248 switch (Rel->getType(Config->isMips64EL())) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000249 case R_MIPS_HI16:
250 return R_MIPS_LO16;
251 case R_MIPS_GOT16:
252 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
253 case R_MIPS_PCHI16:
254 return R_MIPS_PCLO16;
255 case R_MICROMIPS_HI16:
256 return R_MICROMIPS_LO16;
257 default:
258 return R_MIPS_NONE;
259 }
260}
261
262template <class ELFT, class RelTy>
263static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
264 SymbolBody &Sym, const RelTy *Rel,
265 const RelTy *End) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000266 uint32_t SymIndex = Rel->getSymbol(Config->isMips64EL());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000267 uint32_t Type = getMipsPairType(Rel, Sym);
268
269 // Some MIPS relocations use addend calculated from addend of the relocation
270 // itself and addend of paired relocation. ABI requires to compute such
271 // combined addend in case of REL relocation record format only.
272 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
273 if (RelTy::IsRela || Type == R_MIPS_NONE)
274 return 0;
275
276 for (const RelTy *RI = Rel; RI != End; ++RI) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000277 if (RI->getType(Config->isMips64EL()) != Type)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000278 continue;
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000279 if (RI->getSymbol(Config->isMips64EL()) != SymIndex)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000280 continue;
281 const endianness E = ELFT::TargetEndianness;
282 return ((read32<E>(BufLoc) & 0xffff) << 16) +
283 readSignedLo16<E>(Buf + RI->r_offset);
284 }
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000285 warn("can't find matching " + toString(Type) + " relocation for " +
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000286 toString(Rel->getType(Config->isMips64EL())));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000287 return 0;
288}
289
290// True if non-preemptable symbol always has the same value regardless of where
291// the DSO is loaded.
292template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
293 if (Body.isUndefined())
294 return !Body.isLocal() && Body.symbol()->isWeak();
Rui Ueyama80474a22017-02-28 19:29:55 +0000295 if (const auto *DR = dyn_cast<DefinedRegular>(&Body))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000296 return DR->Section == nullptr; // Absolute symbol.
297 return false;
298}
299
Rafael Espindolad598c812016-10-27 17:28:56 +0000300template <class ELFT> static bool isAbsoluteValue(const SymbolBody &Body) {
301 return isAbsolute<ELFT>(Body) || Body.isTls();
302}
303
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000304static bool needsPlt(RelExpr Expr) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000305 return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000306}
307
308// True if this expression is of the form Sym - X, where X is a position in the
309// file (PC, or GOT for example).
310static bool isRelExpr(RelExpr Expr) {
Sean Silva2eed7592016-12-01 05:43:48 +0000311 return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
Peter Smith3a52eb02017-02-01 10:26:03 +0000312 R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000313}
314
315template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000316static bool
317isStaticLinkTimeConstant(RelExpr E, uint32_t Type, const SymbolBody &Body,
318 InputSectionBase &S, typename ELFT::uint RelOff) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000319 // These expressions always compute a constant
Sean Silva2eed7592016-12-01 05:43:48 +0000320 if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
321 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_TLSGD,
322 R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC, R_TLSGD_PC, R_TLSGD,
Peter Smith3a52eb02017-02-01 10:26:03 +0000323 R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT>(E))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000324 return true;
325
326 // These never do, except if the entire file is position dependent or if
327 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000328 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama104e2352017-02-14 05:45:47 +0000329 return Target->usesOnlyLowPageBits(Type) || !Config->pic();
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000330
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000331 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000332 return false;
333
Rui Ueyama104e2352017-02-14 05:45:47 +0000334 if (!Config->pic())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000335 return true;
336
Rafael Espindolad598c812016-10-27 17:28:56 +0000337 bool AbsVal = isAbsoluteValue<ELFT>(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000338 bool RelE = isRelExpr(E);
339 if (AbsVal && !RelE)
340 return true;
341 if (!AbsVal && RelE)
342 return true;
343
344 // Relative relocation to an absolute value. This is normally unrepresentable,
345 // but if the relocation refers to a weak undefined symbol, we allow it to
346 // resolve to the image base. This is a little strange, but it allows us to
347 // link function calls to such symbols. Normally such a call will be guarded
348 // with a comparison, which will load a zero from the GOT.
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000349 // Another special case is MIPS _gp_disp symbol which represents offset
350 // between start of a function and '_gp' value and defined as absolute just
351 // to simplify the code.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000352 if (AbsVal && RelE) {
353 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
354 return true;
Rui Ueyama80474a22017-02-28 19:29:55 +0000355 if (&Body == ElfSym::MipsGpDisp)
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000356 return true;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000357 error(S.getLocation<ELFT>(RelOff) + ": relocation " + toString(Type) +
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000358 " cannot refer to absolute symbol '" + toString(Body) +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000359 "' defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000360 return true;
361 }
362
363 return Target->usesOnlyLowPageBits(Type);
364}
365
366static RelExpr toPlt(RelExpr Expr) {
367 if (Expr == R_PPC_OPD)
368 return R_PPC_PLT_OPD;
369 if (Expr == R_PC)
370 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000371 if (Expr == R_PAGE_PC)
372 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000373 if (Expr == R_ABS)
374 return R_PLT;
375 return Expr;
376}
377
378static RelExpr fromPlt(RelExpr Expr) {
379 // We decided not to use a plt. Optimize a reference to the plt to a
380 // reference to the symbol itself.
381 if (Expr == R_PLT_PC)
382 return R_PC;
383 if (Expr == R_PPC_PLT_OPD)
384 return R_PPC_OPD;
385 if (Expr == R_PLT)
386 return R_ABS;
387 return Expr;
388}
389
Rui Ueyama4076fa12017-02-26 23:35:34 +0000390template <class ELFT> static bool isReadOnly(SharedSymbol *SS) {
Peter Collingbournefeb66292017-01-10 01:21:50 +0000391 typedef typename ELFT::Phdr Elf_Phdr;
Rui Ueyama4076fa12017-02-26 23:35:34 +0000392 uint64_t Value = SS->getValue<ELFT>();
Peter Collingbournefeb66292017-01-10 01:21:50 +0000393
394 // Determine if the symbol is read-only by scanning the DSO's program headers.
Rui Ueyama4076fa12017-02-26 23:35:34 +0000395 auto *File = cast<SharedFile<ELFT>>(SS->File);
396 for (const Elf_Phdr &Phdr : check(File->getObj().program_headers()))
Peter Collingbournefeb66292017-01-10 01:21:50 +0000397 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
398 !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
399 Value < Phdr.p_vaddr + Phdr.p_memsz)
400 return true;
401 return false;
402}
403
Rui Ueyama85c22012017-02-17 03:34:17 +0000404// Returns symbols at the same offset as a given symbol, including SS itself.
Rui Ueyama750c11c2017-02-16 04:39:45 +0000405//
406// If two or more symbols are at the same offset, and at least one of
407// them are copied by a copy relocation, all of them need to be copied.
408// Otherwise, they would refer different places at runtime.
409template <class ELFT>
Rui Ueyama4076fa12017-02-26 23:35:34 +0000410static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol *SS) {
Rui Ueyama750c11c2017-02-16 04:39:45 +0000411 typedef typename ELFT::Sym Elf_Sym;
412
Rui Ueyama4076fa12017-02-26 23:35:34 +0000413 auto *File = cast<SharedFile<ELFT>>(SS->File);
414 uint64_t Shndx = SS->getShndx<ELFT>();
415 uint64_t Value = SS->getValue<ELFT>();
416
417 std::vector<SharedSymbol *> Ret;
418 for (const Elf_Sym &S : File->getGlobalSymbols()) {
419 if (S.st_shndx != Shndx || S.st_value != Value)
Rui Ueyama750c11c2017-02-16 04:39:45 +0000420 continue;
Rui Ueyama4076fa12017-02-26 23:35:34 +0000421 StringRef Name = check(S.getName(File->getStringTable()));
Rui Ueyama750c11c2017-02-16 04:39:45 +0000422 SymbolBody *Sym = Symtab<ELFT>::X->find(Name);
Rui Ueyama4076fa12017-02-26 23:35:34 +0000423 if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
Rui Ueyama750c11c2017-02-16 04:39:45 +0000424 Ret.push_back(Alias);
425 }
426 return Ret;
427}
428
Peter Collingbournefeb66292017-01-10 01:21:50 +0000429// Reserve space in .bss or .bss.rel.ro for copy relocation.
Rui Ueyamaa8091582017-02-19 22:48:33 +0000430//
431// The copy relocation is pretty much a hack. If you use a copy relocation
432// in your program, not only the symbol name but the symbol's size, RW/RO
433// bit and alignment become part of the ABI. In addition to that, if the
434// symbol has aliases, the aliases become part of the ABI. That's subtle,
435// but if you violate that implicit ABI, that can cause very counter-
436// intuitive consequences.
437//
438// So, what is the copy relocation? It's for linking non-position
439// independent code to DSOs. In an ideal world, all references to data
440// exported by DSOs should go indirectly through GOT. But if object files
441// are compiled as non-PIC, all data references are direct. There is no
442// way for the linker to transform the code to use GOT, as machine
443// instructions are already set in stone in object files. This is where
444// the copy relocation takes a role.
445//
446// A copy relocation instructs the dynamic linker to copy data from a DSO
447// to a specified address (which is usually in .bss) at load-time. If the
448// static linker (that's us) finds a direct data reference to a DSO
449// symbol, it creates a copy relocation, so that the symbol can be
450// resolved as if it were in .bss rather than in a DSO.
451//
452// As you can see in this function, we create a copy relocation for the
453// dynamic linker, and the relocation contains not only symbol name but
454// various other informtion about the symbol. So, such attributes become a
455// part of the ABI.
Rui Ueyama3fbf02d2017-02-20 02:22:56 +0000456//
457// Note for application developers: I can give you a piece of advice if
458// you are writing a shared library. You probably should export only
459// functions from your library. You shouldn't export variables.
460//
461// As an example what can happen when you export variables without knowing
462// the semantics of copy relocations, assume that you have an exported
463// variable of type T. It is an ABI-breaking change to add new members at
464// end of T even though doing that doesn't change the layout of the
465// existing members. That's because the space for the new members are not
466// reserved in .bss unless you recompile the main program. That means they
467// are likely to overlap with other data that happens to be laid out next
468// to the variable in .bss. This kind of issue is sometimes very hard to
469// debug. What's a solution? Instead of exporting a varaible V from a DSO,
470// define an accessor getV().
Rui Ueyama4076fa12017-02-26 23:35:34 +0000471template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000472 typedef typename ELFT::uint uintX_t;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000473
474 // Copy relocation against zero-sized symbol doesn't make sense.
475 uintX_t SymSize = SS->template getSize<ELFT>();
476 if (SymSize == 0)
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000477 fatal("cannot create a copy relocation for symbol " + toString(*SS));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000478
Peter Collingbournefeb66292017-01-10 01:21:50 +0000479 // See if this symbol is in a read-only segment. If so, preserve the symbol's
480 // memory protection by reserving space in the .bss.rel.ro section.
Rui Ueyama4076fa12017-02-26 23:35:34 +0000481 bool IsReadOnly = isReadOnly<ELFT>(SS);
George Rimarc215a2a2017-03-06 14:37:45 +0000482 BssRelSection<ELFT> *RelSec = IsReadOnly ? In<ELFT>::BssRelRo : In<ELFT>::Bss;
Rui Ueyama967fc1c2017-03-06 15:16:18 +0000483 uintX_t Off = RelSec->addCopyRelocation(SS->getAlignment<ELFT>(), SymSize);
Peter Smithebfe9942017-02-09 10:27:57 +0000484
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000485 // Look through the DSO's dynamic symbol table for aliases and create a
486 // dynamic symbol for each one. This causes the copy relocation to correctly
487 // interpose any aliases.
Rui Ueyama4076fa12017-02-26 23:35:34 +0000488 for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) {
Rui Ueyama3fbf02d2017-02-20 02:22:56 +0000489 Sym->symbol()->IsUsedInRegularObj = true;
George Rimarc215a2a2017-03-06 14:37:45 +0000490 replaceBody<DefinedRegular>(Sym->symbol(), Sym->getName(),
491 /*IsLocal=*/false, Sym->StOther, Sym->Type, Off,
492 Sym->getSize<ELFT>(), RelSec, nullptr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000493 }
Rui Ueyama750c11c2017-02-16 04:39:45 +0000494
George Rimarc215a2a2017-03-06 14:37:45 +0000495 In<ELFT>::RelaDyn->addReloc({Target->CopyRel, RelSec, Off, false, SS, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000496}
497
498template <class ELFT>
499static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000500 bool IsWrite, RelExpr Expr, uint32_t Type,
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000501 const uint8_t *Data, InputSectionBase &S,
George Rimar463984d2016-11-15 08:07:14 +0000502 typename ELFT::uint RelOff) {
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000503 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000504 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000505 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000506 } else if (!Preemptible) {
507 if (needsPlt(Expr))
508 Expr = fromPlt(Expr);
Rafael Espindolad598c812016-10-27 17:28:56 +0000509 if (Expr == R_GOT_PC && !isAbsoluteValue<ELFT>(Body))
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000510 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000511 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000512
George Rimar463984d2016-11-15 08:07:14 +0000513 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000514 return Expr;
515
516 // This relocation would require the dynamic linker to write a value to read
517 // only memory. We can hack around it if we are producing an executable and
518 // the refered symbol can be preemepted to refer to the executable.
Rui Ueyama104e2352017-02-14 05:45:47 +0000519 if (Config->Shared || (Config->pic() && !isRelExpr(Expr))) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000520 error(S.getLocation<ELFT>(RelOff) + ": can't create dynamic relocation " +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000521 toString(Type) + " against " +
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000522 (Body.getName().empty() ? "local symbol in readonly segment"
523 : "symbol '" + toString(Body) + "'") +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000524 " defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000525 return Expr;
526 }
527 if (Body.getVisibility() != STV_DEFAULT) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000528 error(S.getLocation<ELFT>(RelOff) + ": cannot preempt symbol '" +
529 toString(Body) + "' defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000530 return Expr;
531 }
532 if (Body.isObject()) {
533 // Produce a copy relocation.
Rui Ueyama4076fa12017-02-26 23:35:34 +0000534 auto *B = cast<SharedSymbol>(&Body);
George Rimarc215a2a2017-03-06 14:37:45 +0000535 if (Config->ZNocopyreloc)
536 error(S.getLocation<ELFT>(RelOff) + ": unresolvable relocation " +
537 toString(Type) + " against symbol '" + toString(*B) +
538 "'; recompile with -fPIC or remove '-z nocopyreloc'");
Rui Ueyamaf9e80342017-02-21 21:41:50 +0000539
George Rimarc215a2a2017-03-06 14:37:45 +0000540 addCopyRelSymbol<ELFT>(B);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000541 return Expr;
542 }
543 if (Body.isFunc()) {
544 // This handles a non PIC program call to function in a shared library. In
545 // an ideal world, we could just report an error saying the relocation can
546 // overflow at runtime. In the real world with glibc, crt1.o has a
547 // R_X86_64_PC32 pointing to libc.so.
548 //
549 // The general idea on how to handle such cases is to create a PLT entry and
550 // use that as the function value.
551 //
552 // For the static linking part, we just return a plt expr and everything
553 // else will use the the PLT entry as the address.
554 //
555 // The remaining problem is making sure pointer equality still works. We
556 // need the help of the dynamic linker for that. We let it know that we have
557 // a direct reference to a so symbol by creating an undefined symbol with a
558 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
559 // the value of the symbol we created. This is true even for got entries, so
560 // pointer equality is maintained. To avoid an infinite loop, the only entry
561 // that points to the real function is a dedicated got entry used by the
562 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
563 // R_386_JMP_SLOT, etc).
Rui Ueyama924b3612017-02-16 06:12:22 +0000564 Body.NeedsPltAddr = true;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000565 return toPlt(Expr);
566 }
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000567 error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) +
George Rimar76f429b2016-11-16 17:24:06 +0000568 " is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000569
570 return Expr;
571}
572
573template <class ELFT, class RelTy>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000574static int64_t computeAddend(const elf::ObjectFile<ELFT> &File,
575 const uint8_t *SectionData, const RelTy *End,
576 const RelTy &RI, RelExpr Expr, SymbolBody &Body) {
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000577 uint32_t Type = RI.getType(Config->isMips64EL());
Rafael Espindola7386cea2017-02-16 00:12:34 +0000578 int64_t Addend = getAddend<ELFT>(RI);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000579 const uint8_t *BufLoc = SectionData + RI.r_offset;
580 if (!RelTy::IsRela)
581 Addend += Target->getImplicitAddend(BufLoc, Type);
582 if (Config->EMachine == EM_MIPS) {
583 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
584 if (Type == R_MIPS_LO16 && Expr == R_PC)
585 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
586 // symbol. In that case we should use the following formula for
587 // calculation "AHL + GP - P + 4". Let's add 4 right here.
588 // For details see p. 4-19 at
589 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
590 Addend += 4;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000591 if (Expr == R_MIPS_GOTREL && Body.isLocal())
592 Addend += File.MipsGp0;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000593 }
Rui Ueyama104e2352017-02-14 05:45:47 +0000594 if (Config->pic() && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000595 Addend += getPPC64TocBase();
596 return Addend;
597}
598
Eugene Leviantb380b242016-10-26 11:07:09 +0000599template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000600static void reportUndefined(SymbolBody &Sym, InputSectionBase &S,
Eugene Leviantb380b242016-10-26 11:07:09 +0000601 typename ELFT::uint Offset) {
Rafael Espindola403b0932017-01-27 15:52:08 +0000602 bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
603 Sym.getVisibility() == STV_DEFAULT;
604 if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll ||
605 (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal))
Eugene Leviant89837592016-10-06 09:45:04 +0000606 return;
607
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000608 std::string Msg = S.getLocation<ELFT>(Offset) + ": undefined symbol '" +
609 toString(Sym) + "'";
Eugene Leviant89837592016-10-06 09:45:04 +0000610
Rafael Espindola403b0932017-01-27 15:52:08 +0000611 if (Config->UnresolvedSymbols == UnresolvedPolicy::WarnAll ||
612 (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal))
Eugene Leviant89837592016-10-06 09:45:04 +0000613 warn(Msg);
614 else
615 error(Msg);
616}
617
Simon Atanasyan9e0297b2016-11-05 22:58:01 +0000618template <class RelTy>
619static std::pair<uint32_t, uint32_t>
620mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
621 // MIPS N32 ABI treats series of successive relocations with the same offset
622 // as a single relocation. The similar approach used by N64 ABI, but this ABI
623 // packs all relocations into the single relocation record. Here we emulate
624 // this for the N32 ABI. Iterate over relocation with the same offset and put
625 // theirs types into the single bit-set.
626 uint32_t Processed = 0;
627 for (; I != E && Offset == I->r_offset; ++I) {
628 ++Processed;
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000629 Type |= I->getType(Config->isMips64EL()) << (8 * Processed);
Simon Atanasyan9e0297b2016-11-05 22:58:01 +0000630 }
631 return std::make_pair(Type, Processed);
632}
633
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000634// The reason we have to do this early scan is as follows
635// * To mmap the output file, we need to know the size
636// * For that, we need to know how many dynamic relocs we will have.
637// It might be possible to avoid this by outputting the file with write:
638// * Write the allocated output sections, computing addresses.
639// * Apply relocations, recording which ones require a dynamic reloc.
640// * Write the dynamic relocations.
641// * Write the rest of the file.
642// This would have some drawbacks. For example, we would only know if .rela.dyn
643// is needed after applying relocations. If it is, it will go after rw and rx
644// sections. Given that it is ro, we will need an extra PT_LOAD. This
645// complicates things for the dynamic linker and means we would have to reserve
646// space for the extra PT_LOAD even if we end up not using it.
647template <class ELFT, class RelTy>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000648static void scanRelocs(InputSectionBase &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000649 typedef typename ELFT::uint uintX_t;
650
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000651 bool IsWrite = C.Flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000652
653 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +0000654 In<ELFT>::RelaDyn->addReloc(Reloc);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000655 };
656
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000657 const elf::ObjectFile<ELFT> *File = C.getFile<ELFT>();
Rafael Espindolac7e1e032016-09-12 13:13:53 +0000658 ArrayRef<uint8_t> SectionData = C.Data;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000659 const uint8_t *Buf = SectionData.begin();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000660
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000661 ArrayRef<EhSectionPiece> Pieces;
Rafael Espindola5c02b742017-03-06 21:17:18 +0000662 if (auto *Eh = dyn_cast<EhInputSection>(&C))
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000663 Pieces = Eh->Pieces;
664
665 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
666 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000667
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000668 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
669 const RelTy &RI = *I;
Vitaly Buka029d7302016-11-15 07:32:51 +0000670 SymbolBody &Body = File->getRelocTargetSym(RI);
Rui Ueyamadf8eb172017-03-07 00:43:33 +0000671 uint32_t Type = RI.getType(Config->isMips64EL());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000672
Simon Atanasyan9e0297b2016-11-05 22:58:01 +0000673 if (Config->MipsN32Abi) {
674 uint32_t Processed;
675 std::tie(Type, Processed) =
676 mergeMipsN32RelTypes(Type, RI.r_offset, I + 1, E);
677 I += Processed;
678 }
679
George Rimara4c7e742016-10-20 08:36:42 +0000680 // We only report undefined symbols if they are referenced somewhere in the
681 // code.
Eugene Leviant89837592016-10-06 09:45:04 +0000682 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000683 reportUndefined<ELFT>(Body, C, RI.r_offset);
Eugene Leviant89837592016-10-06 09:45:04 +0000684
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000685 RelExpr Expr = Target->getRelExpr(Type, Body);
Petr Hosekb27bb592017-02-23 06:22:28 +0000686
687 // Ignore "hint" relocations because they are only markers for relaxation.
688 if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
689 continue;
690
Rafael Espindola678844e2016-06-17 15:42:36 +0000691 bool Preemptible = isPreemptible(Body, Type);
George Rimar463984d2016-11-15 08:07:14 +0000692 Expr = adjustExpr(*File, Body, IsWrite, Expr, Type, Buf + RI.r_offset, C,
693 RI.r_offset);
Rui Ueyamaf373dd72016-11-24 01:43:21 +0000694 if (ErrorCount)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000695 continue;
696
Rui Ueyama809d8e22016-06-23 04:33:42 +0000697 // Skip a relocation that points to a dead piece
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000698 // in a eh_frame section.
699 while (PieceI != PieceE &&
700 (PieceI->InputOff + PieceI->size() <= RI.r_offset))
701 ++PieceI;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000702
703 // Compute the offset of this section in the output section. We do it here
704 // to try to compute it only once.
705 uintX_t Offset;
706 if (PieceI != PieceE) {
707 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
Rafael Espindola113860b2016-10-20 10:55:58 +0000708 if (PieceI->OutputOff == -1)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000709 continue;
710 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000711 } else {
George Rimar3e6833b2016-08-19 15:46:28 +0000712 Offset = RI.r_offset;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000713 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000714
715 // This relocation does not require got entry, but it is relative to got and
716 // needs it to be created. Here we request for that.
Rui Ueyamacd19b032017-02-16 06:24:16 +0000717 if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
718 R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
Eugene Leviantad4439e2016-11-11 11:33:32 +0000719 In<ELFT>::Got->HasGotOffRel = true;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000720
Rafael Espindola7386cea2017-02-16 00:12:34 +0000721 int64_t Addend = computeAddend(*File, Buf, E, RI, Expr, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000722
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000723 if (unsigned Processed =
724 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000725 I += (Processed - 1);
726 continue;
727 }
728
Petr Hosekb27bb592017-02-23 06:22:28 +0000729 if (Expr == R_TLSDESC_CALL)
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000730 continue;
731
Sean Silva2eed7592016-12-01 05:43:48 +0000732 if (needsPlt(Expr) ||
Sean Silva2eed7592016-12-01 05:43:48 +0000733 refersToGotEntry(Expr) || !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000734 // If the relocation points to something in the file, we can process it.
George Rimar463984d2016-11-15 08:07:14 +0000735 bool Constant =
736 isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, C, RI.r_offset);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000737
738 // If the output being produced is position independent, the final value
739 // is still not known. In that case we still need some help from the
740 // dynamic linker. We can however do better than just copying the incoming
741 // relocation. We can process some of it and and just ask the dynamic
742 // linker to add the load address.
743 if (!Constant)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000744 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000745
746 // If the produced value is a constant, we just remember to write it
747 // when outputting this section. We also have to do it if the format
748 // uses Elf_Rel, since in that case the written value is the addend.
749 if (Constant || !RelTy::IsRela)
Rafael Espindola664c6522016-09-07 20:37:34 +0000750 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000751 } else {
752 // We don't know anything about the finaly symbol. Just ask the dynamic
753 // linker to handle the relocation for us.
Eugene Leviantab024a32016-11-25 08:56:36 +0000754 if (!Target->isPicRel(Type))
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000755 error(C.getLocation<ELFT>(Offset) + ": relocation " + toString(Type) +
Eugene Leviantab024a32016-11-25 08:56:36 +0000756 " cannot be used against shared object; recompile with -fPIC.");
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000757 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
Eugene Leviantab024a32016-11-25 08:56:36 +0000758
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000759 // MIPS ABI turns using of GOT and dynamic relocations inside out.
760 // While regular ABI uses dynamic relocations to fill up GOT entries
761 // MIPS ABI requires dynamic linker to fills up GOT entries using
762 // specially sorted dynamic symbol table. This affects even dynamic
763 // relocations against symbols which do not require GOT entries
764 // creation explicitly, i.e. do not have any GOT-relocations. So if
765 // a preemptible symbol has a dynamic relocation we anyway have
766 // to create a GOT entry for it.
767 // If a non-preemptible symbol has a dynamic relocation against it,
768 // dynamic linker takes it st_value, adds offset and writes down
769 // result of the dynamic relocation. In case of preemptible symbol
770 // dynamic linker performs symbol resolution, writes the symbol value
771 // to the GOT entry and reads the GOT entry when it needs to perform
772 // a dynamic relocation.
773 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000774 if (Config->EMachine == EM_MIPS)
Simon Atanasyan725dc142016-11-16 21:01:02 +0000775 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000776 continue;
777 }
778
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000779 // At this point we are done with the relocated position. Some relocations
780 // also require us to create a got or plt entry.
781
782 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
783 if (needsPlt(Expr)) {
784 if (Body.isInPlt())
785 continue;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000786
Peter Smithbaffdb82016-12-08 12:58:55 +0000787 if (Body.isGnuIFunc() && !Preemptible) {
788 In<ELFT>::Iplt->addEntry(Body);
789 In<ELFT>::IgotPlt->addEntry(Body);
790 In<ELFT>::RelaIplt->addReloc({Target->IRelativeRel, In<ELFT>::IgotPlt,
791 Body.getGotPltOffset<ELFT>(),
792 !Preemptible, &Body, 0});
793 } else {
794 In<ELFT>::Plt->addEntry(Body);
795 In<ELFT>::GotPlt->addEntry(Body);
796 In<ELFT>::RelaPlt->addReloc({Target->PltRel, In<ELFT>::GotPlt,
797 Body.getGotPltOffset<ELFT>(), !Preemptible,
798 &Body, 0});
799 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000800 continue;
801 }
802
803 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000804 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanaf52f6a2016-09-08 09:07:12 +0000805 // MIPS ABI has special rules to process GOT entries and doesn't
806 // require relocation entries for them. A special case is TLS
807 // relocations. In that case dynamic loader applies dynamic
808 // relocations to initialize TLS GOT entries.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000809 // See "Global Offset Table" in Chapter 5 in the following document
810 // for detailed description:
811 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan725dc142016-11-16 21:01:02 +0000812 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000813 if (Body.isTls() && Body.isPreemptible())
Simon Atanasyan725dc142016-11-16 21:01:02 +0000814 AddDyn({Target->TlsGotRel, In<ELFT>::MipsGot,
815 Body.getGotOffset<ELFT>(), false, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000816 continue;
817 }
818
819 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000820 continue;
821
Eugene Leviantad4439e2016-11-11 11:33:32 +0000822 In<ELFT>::Got->addEntry(Body);
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000823 uintX_t Off = Body.getGotOffset<ELFT>();
824 uint32_t DynType;
Peter Smithde3e7382016-11-29 16:23:50 +0000825 RelExpr GotRE = R_ABS;
826 if (Body.isTls()) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000827 DynType = Target->TlsGotRel;
Peter Smithde3e7382016-11-29 16:23:50 +0000828 GotRE = R_TLS;
Rui Ueyama104e2352017-02-14 05:45:47 +0000829 } else if (!Preemptible && Config->pic() && !isAbsolute<ELFT>(Body))
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000830 DynType = Target->RelativeRel;
831 else
832 DynType = Target->GotRel;
833
Rafael Espindolaf4ff80c2016-12-02 01:57:24 +0000834 // FIXME: this logic is almost duplicated above.
Rui Ueyama104e2352017-02-14 05:45:47 +0000835 bool Constant =
836 !Preemptible && !(Config->pic() && !isAbsolute<ELFT>(Body));
Rafael Espindolaf4ff80c2016-12-02 01:57:24 +0000837 if (!Constant)
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000838 AddDyn({DynType, In<ELFT>::Got, Off, !Preemptible, &Body, 0});
Rafael Espindolae004d4b2016-12-06 12:19:24 +0000839 if (Constant || (!RelTy::IsRela && !Preemptible))
Peter Smithde3e7382016-11-29 16:23:50 +0000840 In<ELFT>::Got->Relocations.push_back({GotRE, DynType, Off, 0, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000841 continue;
842 }
843 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000844}
845
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000846template <class ELFT> void scanRelocations(InputSectionBase &S) {
Rafael Espindola9f0c4bb2016-11-10 14:53:24 +0000847 if (S.AreRelocsRela)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000848 scanRelocs<ELFT>(S, S.relas<ELFT>());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000849 else
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000850 scanRelocs<ELFT>(S, S.rels<ELFT>());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000851}
852
Peter Smith3a52eb02017-02-01 10:26:03 +0000853// Insert the Thunks for OutputSection OS into their designated place
854// in the Sections vector, and recalculate the InputSection output section
855// offsets.
856// This may invalidate any output section offsets stored outside of InputSection
857template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000858static void mergeThunks(OutputSection *OS,
Peter Smith3a52eb02017-02-01 10:26:03 +0000859 std::vector<ThunkSection<ELFT> *> &Thunks) {
860 // Order Thunks in ascending OutSecOff
861 auto ThunkCmp = [](const ThunkSection<ELFT> *A, const ThunkSection<ELFT> *B) {
862 return A->OutSecOff < B->OutSecOff;
863 };
864 std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
865
866 // Merge sorted vectors of Thunks and InputSections by OutSecOff
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000867 std::vector<InputSection *> Tmp;
Peter Smith3a52eb02017-02-01 10:26:03 +0000868 Tmp.reserve(OS->Sections.size() + Thunks.size());
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000869 auto MergeCmp = [](const InputSection *A, const InputSection *B) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000870 // std::merge requires a strict weak ordering.
871 if (A->OutSecOff < B->OutSecOff)
872 return true;
873 if (A->OutSecOff == B->OutSecOff)
874 // Check if Thunk is immediately before any specific Target InputSection
875 // for example Mips LA25 Thunks.
876 if (auto *TA = dyn_cast<ThunkSection<ELFT>>(A))
877 if (TA && TA->getTargetInputSection() == B)
878 return true;
879 return false;
880 };
881 std::merge(OS->Sections.begin(), OS->Sections.end(), Thunks.begin(),
882 Thunks.end(), std::back_inserter(Tmp), MergeCmp);
883 OS->Sections = std::move(Tmp);
Rafael Espindola24e6f362017-02-24 15:07:30 +0000884 OS->assignOffsets<ELFT>();
Peter Smith3a52eb02017-02-01 10:26:03 +0000885}
886
887// Process all relocations from the InputSections that have been assigned
888// to OutputSections and redirect through Thunks if needed.
889//
890// createThunks must be called after scanRelocs has created the Relocations for
891// each InputSection. It must be called before the static symbol table is
892// finalized. If any Thunks are added to an OutputSection the output section
893// offsets of the InputSections will change.
894//
895// FIXME: All Thunks are assumed to be in range of the relocation. Range
896// extension Thunks are not yet supported.
Peter Smithee6d7182017-01-18 09:57:14 +0000897template <class ELFT>
Peter Smith1ec42d92017-03-08 14:06:24 +0000898bool createThunks(ArrayRef<OutputSection *> OutputSections) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000899 // Track Symbols that already have a Thunk
900 DenseMap<SymbolBody *, Thunk<ELFT> *> ThunkedSymbols;
901 // Track InputSections that have a ThunkSection placed in front
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000902 DenseMap<InputSection *, ThunkSection<ELFT> *> ThunkedSections;
Peter Smith3a52eb02017-02-01 10:26:03 +0000903 // Track the ThunksSections that need to be inserted into an OutputSection
Rafael Espindola24e6f362017-02-24 15:07:30 +0000904 std::map<OutputSection *, std::vector<ThunkSection<ELFT> *>> ThunkSections;
Peter Smith3a52eb02017-02-01 10:26:03 +0000905
906 // Find or create a Thunk for Body for relocation Type
907 auto GetThunk = [&](SymbolBody &Body, uint32_t Type) {
908 auto res = ThunkedSymbols.insert({&Body, nullptr});
909 if (res.second == true)
910 res.first->second = addThunk<ELFT>(Type, Body);
911 return std::make_pair(res.first->second, res.second);
912 };
913
914 // Find or create a ThunkSection to be placed immediately before IS
Rafael Espindola24e6f362017-02-24 15:07:30 +0000915 auto GetISThunkSec = [&](InputSection *IS, OutputSection *OS) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000916 ThunkSection<ELFT> *TS = ThunkedSections.lookup(IS);
917 if (TS)
918 return TS;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000919 auto *TOS = cast<OutputSection>(IS->OutSec);
Peter Smith3a52eb02017-02-01 10:26:03 +0000920 TS = make<ThunkSection<ELFT>>(TOS, IS->OutSecOff);
Peter Smith24fb2502017-03-07 09:45:04 +0000921 ThunkSections[TOS].push_back(TS);
Peter Smith3a52eb02017-02-01 10:26:03 +0000922 ThunkedSections[IS] = TS;
923 return TS;
924 };
925 // Find or create a ThunkSection to be placed as last executable section in
926 // OS.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000927 auto GetOSThunkSec = [&](ThunkSection<ELFT> *&TS, OutputSection *OS) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000928 if (TS == nullptr) {
929 uint32_t Off = 0;
930 for (auto *IS : OS->Sections) {
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000931 Off = IS->OutSecOff + IS->getSize();
Peter Smith3a52eb02017-02-01 10:26:03 +0000932 if ((IS->Flags & SHF_EXECINSTR) == 0)
933 break;
934 }
935 TS = make<ThunkSection<ELFT>>(OS, Off);
936 ThunkSections[OS].push_back(TS);
937 }
938 return TS;
939 };
940 // Create all the Thunks and insert them into synthetic ThunkSections. The
941 // ThunkSections are later inserted back into the OutputSection.
942
943 // We separate the creation of ThunkSections from the insertion of the
944 // ThunkSections back into the OutputSection as ThunkSections are not always
945 // inserted into the same OutputSection as the caller.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000946 for (OutputSection *Base : OutputSections) {
947 auto *OS = dyn_cast<OutputSection>(Base);
Peter Smith94b999b2017-01-20 15:25:45 +0000948 if (OS == nullptr)
949 continue;
Peter Smith3a52eb02017-02-01 10:26:03 +0000950
951 ThunkSection<ELFT> *OSTS = nullptr;
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000952 for (InputSection *IS : OS->Sections) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000953 for (Relocation &Rel : IS->Relocations) {
954 SymbolBody &Body = *Rel.Sym;
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000955 if (Target->needsThunk(Rel.Expr, Rel.Type, IS->template getFile<ELFT>(),
956 Body)) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000957 Thunk<ELFT> *T;
958 bool IsNew;
959 std::tie(T, IsNew) = GetThunk(Body, Rel.Type);
960 if (IsNew) {
961 // Find or create a ThunkSection for the new Thunk
962 ThunkSection<ELFT> *TS;
963 if (auto *TIS = T->getTargetInputSection())
964 TS = GetISThunkSec(TIS, OS);
965 else
966 TS = GetOSThunkSec(OSTS, OS);
967 TS->addThunk(T);
968 }
969 // Redirect relocation to Thunk, we never go via the PLT to a Thunk
970 Rel.Sym = T->ThunkSym;
971 Rel.Expr = fromPlt(Rel.Expr);
972 }
Peter Smithee6d7182017-01-18 09:57:14 +0000973 }
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000974 }
975 }
Peter Smith3a52eb02017-02-01 10:26:03 +0000976
977 // Merge all created synthetic ThunkSections back into OutputSection
978 for (auto &KV : ThunkSections)
979 mergeThunks<ELFT>(KV.first, KV.second);
Peter Smith1ec42d92017-03-08 14:06:24 +0000980 return !ThunkSections.empty();
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000981}
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000982
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000983template void scanRelocations<ELF32LE>(InputSectionBase &);
984template void scanRelocations<ELF32BE>(InputSectionBase &);
985template void scanRelocations<ELF64LE>(InputSectionBase &);
986template void scanRelocations<ELF64BE>(InputSectionBase &);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000987
Peter Smith1ec42d92017-03-08 14:06:24 +0000988template bool createThunks<ELF32LE>(ArrayRef<OutputSection *>);
989template bool createThunks<ELF32BE>(ArrayRef<OutputSection *>);
990template bool createThunks<ELF64LE>(ArrayRef<OutputSection *>);
991template bool createThunks<ELF64BE>(ArrayRef<OutputSection *>);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000992}
993}