blob: c700db1f779fd50a37b4fbf01e0decb0b76951ae [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 Espindola7386cea2017-02-16 00:12:34 +000094static unsigned handleNoRelaxTlsRelocation(GOT *Got, uint32_t Type,
95 SymbolBody &Body,
96 InputSectionBase<ELFT> &C,
97 typename ELFT::uint Offset,
98 int64_t Addend, RelExpr Expr) {
Peter Smithde3e7382016-11-29 16:23:50 +000099 typedef typename ELFT::uint uintX_t;
100 auto addModuleReloc = [](SymbolBody &Body, GOT *Got, uintX_t Off, bool LD) {
101 // The Dynamic TLS Module Index Relocation can be statically resolved to 1
102 // if we know that we are linking an executable. For ARM we resolve the
103 // relocation when writing the Got. MIPS has a custom Got implementation
104 // that writes the Module index in directly.
Rui Ueyama104e2352017-02-14 05:45:47 +0000105 if (!Body.isPreemptible() && !Config->pic() && Config->EMachine == EM_ARM)
Peter Smithde3e7382016-11-29 16:23:50 +0000106 Got->Relocations.push_back(
107 {R_ABS, Target->TlsModuleIndexRel, Off, 0, &Body});
108 else {
109 SymbolBody *Dest = LD ? nullptr : &Body;
110 In<ELFT>::RelaDyn->addReloc(
111 {Target->TlsModuleIndexRel, Got, Off, false, Dest, 0});
112 }
113 };
Rui Ueyamacd19b032017-02-16 06:24:16 +0000114 if (isRelExprOneOf<R_MIPS_TLSLD, R_TLSLD_PC>(Expr)) {
Rui Ueyama104e2352017-02-14 05:45:47 +0000115 if (Got->addTlsIndex() && (Config->pic() || Config->EMachine == EM_ARM))
Peter Smithde3e7382016-11-29 16:23:50 +0000116 addModuleReloc(Body, Got, Got->getTlsIndexOff(), true);
Rafael Espindola664c6522016-09-07 20:37:34 +0000117 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000118 return 1;
119 }
120 if (Target->isTlsGlobalDynamicRel(Type)) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000121 if (Got->addDynTlsEntry(Body) &&
Peter Smithfde62132016-09-23 13:54:48 +0000122 (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000123 uintX_t Off = Got->getGlobalDynOffset(Body);
Peter Smithde3e7382016-11-29 16:23:50 +0000124 addModuleReloc(Body, Got, Off, false);
Peter Smithfde62132016-09-23 13:54:48 +0000125 if (Body.isPreemptible())
Simon Atanasyan725dc142016-11-16 21:01:02 +0000126 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Got,
Eugene Levianta96d9022016-11-16 10:02:27 +0000127 Off + (uintX_t)sizeof(uintX_t), false,
128 &Body, 0});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000129 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000130 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Simon Atanasyan002e2442016-06-23 15:26:31 +0000131 return 1;
132 }
133 return 0;
134}
135
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000136// Returns the number of relocations processed.
137template <class ELFT>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000138static unsigned
139handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase<ELFT> &C,
140 typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000141 if (!(C.Flags & SHF_ALLOC))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000142 return 0;
143
144 if (!Body.isTls())
145 return 0;
146
147 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000148
Simon Atanasyan725dc142016-11-16 21:01:02 +0000149 if (Config->EMachine == EM_ARM)
150 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::Got, Type, Body, C,
151 Offset, Addend, Expr);
152 if (Config->EMachine == EM_MIPS)
153 return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::MipsGot, Type, Body, C,
154 Offset, Addend, Expr);
Simon Atanasyan002e2442016-06-23 15:26:31 +0000155
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000156 bool IsPreemptible = isPreemptible(Body, Type);
Rui Ueyamacd19b032017-02-16 06:24:16 +0000157 if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000158 Config->Shared) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000159 if (In<ELFT>::Got->addDynTlsEntry(Body)) {
160 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
Adhemerval Zanella86513f02016-12-19 11:58:01 +0000161 In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off,
Rafael Espindola29982b02016-12-19 16:50:20 +0000162 !IsPreemptible, &Body, 0});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000163 }
Peter Smithd6486032016-10-20 09:59:26 +0000164 if (Expr != R_TLSDESC_CALL)
Rafael Espindola664c6522016-09-07 20:37:34 +0000165 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000166 return 1;
167 }
168
Rui Ueyamacd19b032017-02-16 06:24:16 +0000169 if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000170 // Local-Dynamic relocs can be relaxed to Local-Exec.
171 if (!Config->Shared) {
172 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000173 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000174 return 2;
175 }
Eugene Leviantad4439e2016-11-11 11:33:32 +0000176 if (In<ELFT>::Got->addTlsIndex())
Eugene Levianta96d9022016-11-16 10:02:27 +0000177 In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
178 In<ELFT>::Got->getTlsIndexOff(), false,
179 nullptr, 0});
Rafael Espindola664c6522016-09-07 20:37:34 +0000180 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000181 return 1;
182 }
183
184 // Local-Dynamic relocs can be relaxed to Local-Exec.
185 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
186 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000187 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000188 return 1;
189 }
190
Rui Ueyamacd19b032017-02-16 06:24:16 +0000191 if (isRelExprOneOf<R_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL>(Expr) ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000192 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000193 if (Config->Shared) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000194 if (In<ELFT>::Got->addDynTlsEntry(Body)) {
195 uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
Eugene Levianta96d9022016-11-16 10:02:27 +0000196 In<ELFT>::RelaDyn->addReloc(
Eugene Leviantad4439e2016-11-11 11:33:32 +0000197 {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000198
199 // If the symbol is preemptible we need the dynamic linker to write
200 // the offset too.
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000201 uintX_t OffsetOff = Off + (uintX_t)sizeof(uintX_t);
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000202 if (IsPreemptible)
Eugene Levianta96d9022016-11-16 10:02:27 +0000203 In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000204 OffsetOff, false, &Body, 0});
205 else
206 In<ELFT>::Got->Relocations.push_back(
207 {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000208 }
Rafael Espindola664c6522016-09-07 20:37:34 +0000209 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000210 return 1;
211 }
212
213 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
214 // depending on the symbol being locally defined or not.
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000215 if (IsPreemptible) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000216 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000217 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
Rafael Espindola664c6522016-09-07 20:37:34 +0000218 Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000219 if (!Body.isInGot()) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000220 In<ELFT>::Got->addEntry(Body);
Eugene Levianta96d9022016-11-16 10:02:27 +0000221 In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got,
222 Body.getGotOffset<ELFT>(), false, &Body,
223 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000224 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000225 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000226 }
227 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000228 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
Rafael Espindola69f54022016-06-04 23:22:34 +0000229 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000230 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000231 }
232
233 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
234 // defined.
Rafael Espindola09d5daa2016-12-13 16:59:19 +0000235 if (Target->isTlsInitialExecRel(Type) && !Config->Shared && !IsPreemptible) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000236 C.Relocations.push_back(
Rafael Espindola664c6522016-09-07 20:37:34 +0000237 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000238 return 1;
239 }
240 return 0;
241}
242
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000243template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
244 return read32<E>(Loc) & 0xffff;
245}
246
247template <class RelTy>
248static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
249 switch (Rel->getType(Config->Mips64EL)) {
250 case R_MIPS_HI16:
251 return R_MIPS_LO16;
252 case R_MIPS_GOT16:
253 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
254 case R_MIPS_PCHI16:
255 return R_MIPS_PCLO16;
256 case R_MICROMIPS_HI16:
257 return R_MICROMIPS_LO16;
258 default:
259 return R_MIPS_NONE;
260 }
261}
262
263template <class ELFT, class RelTy>
264static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
265 SymbolBody &Sym, const RelTy *Rel,
266 const RelTy *End) {
267 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
268 uint32_t Type = getMipsPairType(Rel, Sym);
269
270 // Some MIPS relocations use addend calculated from addend of the relocation
271 // itself and addend of paired relocation. ABI requires to compute such
272 // combined addend in case of REL relocation record format only.
273 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
274 if (RelTy::IsRela || Type == R_MIPS_NONE)
275 return 0;
276
277 for (const RelTy *RI = Rel; RI != End; ++RI) {
278 if (RI->getType(Config->Mips64EL) != Type)
279 continue;
280 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
281 continue;
282 const endianness E = ELFT::TargetEndianness;
283 return ((read32<E>(BufLoc) & 0xffff) << 16) +
284 readSignedLo16<E>(Buf + RI->r_offset);
285 }
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000286 warn("can't find matching " + toString(Type) + " relocation for " +
287 toString(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000288 return 0;
289}
290
291// True if non-preemptable symbol always has the same value regardless of where
292// the DSO is loaded.
293template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
294 if (Body.isUndefined())
295 return !Body.isLocal() && Body.symbol()->isWeak();
296 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
297 return DR->Section == nullptr; // Absolute symbol.
298 return false;
299}
300
Rafael Espindolad598c812016-10-27 17:28:56 +0000301template <class ELFT> static bool isAbsoluteValue(const SymbolBody &Body) {
302 return isAbsolute<ELFT>(Body) || Body.isTls();
303}
304
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000305static bool needsPlt(RelExpr Expr) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000306 return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000307}
308
309// True if this expression is of the form Sym - X, where X is a position in the
310// file (PC, or GOT for example).
311static bool isRelExpr(RelExpr Expr) {
Sean Silva2eed7592016-12-01 05:43:48 +0000312 return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
Peter Smith3a52eb02017-02-01 10:26:03 +0000313 R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000314}
315
316template <class ELFT>
317static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
George Rimar463984d2016-11-15 08:07:14 +0000318 const SymbolBody &Body,
319 InputSectionBase<ELFT> &S,
320 typename ELFT::uint RelOff) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000321 // These expressions always compute a constant
Sean Silva2eed7592016-12-01 05:43:48 +0000322 if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
323 R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_TLSGD,
324 R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC, R_TLSGD_PC, R_TLSGD,
Peter Smith3a52eb02017-02-01 10:26:03 +0000325 R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT>(E))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000326 return true;
327
328 // These never do, except if the entire file is position dependent or if
329 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000330 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama104e2352017-02-14 05:45:47 +0000331 return Target->usesOnlyLowPageBits(Type) || !Config->pic();
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000332
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000333 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000334 return false;
335
Rui Ueyama104e2352017-02-14 05:45:47 +0000336 if (!Config->pic())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000337 return true;
338
Rafael Espindolad598c812016-10-27 17:28:56 +0000339 bool AbsVal = isAbsoluteValue<ELFT>(Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000340 bool RelE = isRelExpr(E);
341 if (AbsVal && !RelE)
342 return true;
343 if (!AbsVal && RelE)
344 return true;
345
346 // Relative relocation to an absolute value. This is normally unrepresentable,
347 // but if the relocation refers to a weak undefined symbol, we allow it to
348 // resolve to the image base. This is a little strange, but it allows us to
349 // link function calls to such symbols. Normally such a call will be guarded
350 // with a comparison, which will load a zero from the GOT.
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000351 // Another special case is MIPS _gp_disp symbol which represents offset
352 // between start of a function and '_gp' value and defined as absolute just
353 // to simplify the code.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000354 if (AbsVal && RelE) {
355 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
356 return true;
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000357 if (&Body == ElfSym<ELFT>::MipsGpDisp)
358 return true;
Rui Ueyamada06bfb2016-11-25 18:51:53 +0000359 error(S.getLocation(RelOff) + ": relocation " + toString(Type) +
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000360 " cannot refer to absolute symbol '" + toString(Body) +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000361 "' defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000362 return true;
363 }
364
365 return Target->usesOnlyLowPageBits(Type);
366}
367
368static RelExpr toPlt(RelExpr Expr) {
369 if (Expr == R_PPC_OPD)
370 return R_PPC_PLT_OPD;
371 if (Expr == R_PC)
372 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000373 if (Expr == R_PAGE_PC)
374 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000375 if (Expr == R_ABS)
376 return R_PLT;
377 return Expr;
378}
379
380static RelExpr fromPlt(RelExpr Expr) {
381 // We decided not to use a plt. Optimize a reference to the plt to a
382 // reference to the symbol itself.
383 if (Expr == R_PLT_PC)
384 return R_PC;
385 if (Expr == R_PPC_PLT_OPD)
386 return R_PPC_OPD;
387 if (Expr == R_PLT)
388 return R_ABS;
389 return Expr;
390}
391
392template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
393 typedef typename ELFT::uint uintX_t;
394
Rui Ueyama434b5612016-07-17 03:11:46 +0000395 uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000396 uintX_t SymValue = SS->Sym.st_value;
397 int TrailingZeros =
398 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
399 return 1 << TrailingZeros;
400}
401
Peter Collingbournefeb66292017-01-10 01:21:50 +0000402template <class ELFT> static bool isReadOnly(SharedSymbol<ELFT> *SS) {
403 typedef typename ELFT::uint uintX_t;
404 typedef typename ELFT::Phdr Elf_Phdr;
405
406 // Determine if the symbol is read-only by scanning the DSO's program headers.
407 uintX_t Value = SS->Sym.st_value;
408 for (const Elf_Phdr &Phdr : check(SS->file()->getObj().program_headers()))
409 if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
410 !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
411 Value < Phdr.p_vaddr + Phdr.p_memsz)
412 return true;
413 return false;
414}
415
Rui Ueyama85c22012017-02-17 03:34:17 +0000416// Returns symbols at the same offset as a given symbol, including SS itself.
Rui Ueyama750c11c2017-02-16 04:39:45 +0000417//
418// If two or more symbols are at the same offset, and at least one of
419// them are copied by a copy relocation, all of them need to be copied.
420// Otherwise, they would refer different places at runtime.
421template <class ELFT>
Rui Ueyama85c22012017-02-17 03:34:17 +0000422static std::vector<SharedSymbol<ELFT> *> getSymbolsAt(SharedSymbol<ELFT> *SS) {
Rui Ueyama750c11c2017-02-16 04:39:45 +0000423 typedef typename ELFT::Sym Elf_Sym;
424
425 std::vector<SharedSymbol<ELFT> *> Ret;
426 for (const Elf_Sym &S : SS->file()->getGlobalSymbols()) {
427 if (S.st_shndx != SS->Sym.st_shndx || S.st_value != SS->Sym.st_value)
428 continue;
429 StringRef Name = check(S.getName(SS->file()->getStringTable()));
430 SymbolBody *Sym = Symtab<ELFT>::X->find(Name);
431 if (auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(Sym))
432 Ret.push_back(Alias);
433 }
434 return Ret;
435}
436
Peter Collingbournefeb66292017-01-10 01:21:50 +0000437// Reserve space in .bss or .bss.rel.ro for copy relocation.
Rui Ueyamaa8091582017-02-19 22:48:33 +0000438//
439// The copy relocation is pretty much a hack. If you use a copy relocation
440// in your program, not only the symbol name but the symbol's size, RW/RO
441// bit and alignment become part of the ABI. In addition to that, if the
442// symbol has aliases, the aliases become part of the ABI. That's subtle,
443// but if you violate that implicit ABI, that can cause very counter-
444// intuitive consequences.
445//
446// So, what is the copy relocation? It's for linking non-position
447// independent code to DSOs. In an ideal world, all references to data
448// exported by DSOs should go indirectly through GOT. But if object files
449// are compiled as non-PIC, all data references are direct. There is no
450// way for the linker to transform the code to use GOT, as machine
451// instructions are already set in stone in object files. This is where
452// the copy relocation takes a role.
453//
454// A copy relocation instructs the dynamic linker to copy data from a DSO
455// to a specified address (which is usually in .bss) at load-time. If the
456// static linker (that's us) finds a direct data reference to a DSO
457// symbol, it creates a copy relocation, so that the symbol can be
458// resolved as if it were in .bss rather than in a DSO.
459//
460// As you can see in this function, we create a copy relocation for the
461// dynamic linker, and the relocation contains not only symbol name but
462// various other informtion about the symbol. So, such attributes become a
463// part of the ABI.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000464template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
465 typedef typename ELFT::uint uintX_t;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000466
467 // Copy relocation against zero-sized symbol doesn't make sense.
468 uintX_t SymSize = SS->template getSize<ELFT>();
469 if (SymSize == 0)
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000470 fatal("cannot create a copy relocation for symbol " + toString(*SS));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000471
Peter Collingbournefeb66292017-01-10 01:21:50 +0000472 // See if this symbol is in a read-only segment. If so, preserve the symbol's
473 // memory protection by reserving space in the .bss.rel.ro section.
474 bool IsReadOnly = isReadOnly(SS);
Rui Ueyamada5cc842017-02-16 04:12:19 +0000475 OutputSection<ELFT> *OSec = IsReadOnly ? Out<ELFT>::BssRelRo : Out<ELFT>::Bss;
Peter Collingbournefeb66292017-01-10 01:21:50 +0000476
Rui Ueyamada5cc842017-02-16 04:12:19 +0000477 // Create a SyntheticSection in Out to hold the .bss and the Copy Reloc.
478 auto *ISec =
479 make<CopyRelSection<ELFT>>(IsReadOnly, getAlignment(SS), SymSize);
480 OSec->addSection(ISec);
Peter Smithebfe9942017-02-09 10:27:57 +0000481
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000482 // Look through the DSO's dynamic symbol table for aliases and create a
483 // dynamic symbol for each one. This causes the copy relocation to correctly
484 // interpose any aliases.
Rui Ueyama85c22012017-02-17 03:34:17 +0000485 for (SharedSymbol<ELFT> *Alias : getSymbolsAt(SS)) {
Rui Ueyama924b3612017-02-16 06:12:22 +0000486 Alias->NeedsCopy = true;
Rui Ueyamaf829e8c2017-02-16 06:12:41 +0000487 Alias->Section = ISec;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000488 Alias->symbol()->IsUsedInRegularObj = true;
489 }
Rui Ueyama750c11c2017-02-16 04:39:45 +0000490
Rui Ueyamada5cc842017-02-16 04:12:19 +0000491 In<ELFT>::RelaDyn->addReloc({Target->CopyRel, ISec, 0, false, SS, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000492}
493
494template <class ELFT>
495static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000496 bool IsWrite, RelExpr Expr, uint32_t Type,
George Rimar463984d2016-11-15 08:07:14 +0000497 const uint8_t *Data, InputSectionBase<ELFT> &S,
498 typename ELFT::uint RelOff) {
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000499 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000500 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000501 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000502 } else if (!Preemptible) {
503 if (needsPlt(Expr))
504 Expr = fromPlt(Expr);
Rafael Espindolad598c812016-10-27 17:28:56 +0000505 if (Expr == R_GOT_PC && !isAbsoluteValue<ELFT>(Body))
Rafael Espindolaf2956a32016-06-17 15:01:50 +0000506 Expr = Target->adjustRelaxExpr(Type, Data, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000507 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000508
George Rimar463984d2016-11-15 08:07:14 +0000509 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000510 return Expr;
511
512 // This relocation would require the dynamic linker to write a value to read
513 // only memory. We can hack around it if we are producing an executable and
514 // the refered symbol can be preemepted to refer to the executable.
Rui Ueyama104e2352017-02-14 05:45:47 +0000515 if (Config->Shared || (Config->pic() && !isRelExpr(Expr))) {
Rui Ueyamada06bfb2016-11-25 18:51:53 +0000516 error(S.getLocation(RelOff) + ": can't create dynamic relocation " +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000517 toString(Type) + " against " +
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000518 (Body.getName().empty() ? "local symbol in readonly segment"
519 : "symbol '" + toString(Body) + "'") +
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000520 " defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000521 return Expr;
522 }
523 if (Body.getVisibility() != STV_DEFAULT) {
Rui Ueyamada06bfb2016-11-25 18:51:53 +0000524 error(S.getLocation(RelOff) + ": cannot preempt symbol '" + toString(Body) +
525 "' defined in " + toString(Body.File));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000526 return Expr;
527 }
528 if (Body.isObject()) {
529 // Produce a copy relocation.
530 auto *B = cast<SharedSymbol<ELFT>>(&Body);
Rui Ueyama924b3612017-02-16 06:12:22 +0000531 if (!B->NeedsCopy)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000532 addCopyRelSymbol(B);
533 return Expr;
534 }
535 if (Body.isFunc()) {
536 // This handles a non PIC program call to function in a shared library. In
537 // an ideal world, we could just report an error saying the relocation can
538 // overflow at runtime. In the real world with glibc, crt1.o has a
539 // R_X86_64_PC32 pointing to libc.so.
540 //
541 // The general idea on how to handle such cases is to create a PLT entry and
542 // use that as the function value.
543 //
544 // For the static linking part, we just return a plt expr and everything
545 // else will use the the PLT entry as the address.
546 //
547 // The remaining problem is making sure pointer equality still works. We
548 // need the help of the dynamic linker for that. We let it know that we have
549 // a direct reference to a so symbol by creating an undefined symbol with a
550 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
551 // the value of the symbol we created. This is true even for got entries, so
552 // pointer equality is maintained. To avoid an infinite loop, the only entry
553 // that points to the real function is a dedicated got entry used by the
554 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
555 // R_386_JMP_SLOT, etc).
Rui Ueyama924b3612017-02-16 06:12:22 +0000556 Body.NeedsPltAddr = true;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000557 return toPlt(Expr);
558 }
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000559 error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) +
George Rimar76f429b2016-11-16 17:24:06 +0000560 " is missing type");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000561
562 return Expr;
563}
564
565template <class ELFT, class RelTy>
Rafael Espindola7386cea2017-02-16 00:12:34 +0000566static int64_t computeAddend(const elf::ObjectFile<ELFT> &File,
567 const uint8_t *SectionData, const RelTy *End,
568 const RelTy &RI, RelExpr Expr, SymbolBody &Body) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000569 uint32_t Type = RI.getType(Config->Mips64EL);
Rafael Espindola7386cea2017-02-16 00:12:34 +0000570 int64_t Addend = getAddend<ELFT>(RI);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000571 const uint8_t *BufLoc = SectionData + RI.r_offset;
572 if (!RelTy::IsRela)
573 Addend += Target->getImplicitAddend(BufLoc, Type);
574 if (Config->EMachine == EM_MIPS) {
575 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
576 if (Type == R_MIPS_LO16 && Expr == R_PC)
577 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
578 // symbol. In that case we should use the following formula for
579 // calculation "AHL + GP - P + 4". Let's add 4 right here.
580 // For details see p. 4-19 at
581 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
582 Addend += 4;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000583 if (Expr == R_MIPS_GOTREL && Body.isLocal())
584 Addend += File.MipsGp0;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000585 }
Rui Ueyama104e2352017-02-14 05:45:47 +0000586 if (Config->pic() && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000587 Addend += getPPC64TocBase();
588 return Addend;
589}
590
Eugene Leviantb380b242016-10-26 11:07:09 +0000591template <class ELFT>
592static void reportUndefined(SymbolBody &Sym, InputSectionBase<ELFT> &S,
593 typename ELFT::uint Offset) {
Rafael Espindola403b0932017-01-27 15:52:08 +0000594 bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
595 Sym.getVisibility() == STV_DEFAULT;
596 if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll ||
597 (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal))
Eugene Leviant89837592016-10-06 09:45:04 +0000598 return;
599
Rui Ueyamaa3ac1732016-11-24 20:24:18 +0000600 std::string Msg =
Rui Ueyamada06bfb2016-11-25 18:51:53 +0000601 S.getLocation(Offset) + ": undefined symbol '" + toString(Sym) + "'";
Eugene Leviant89837592016-10-06 09:45:04 +0000602
Rafael Espindola403b0932017-01-27 15:52:08 +0000603 if (Config->UnresolvedSymbols == UnresolvedPolicy::WarnAll ||
604 (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal))
Eugene Leviant89837592016-10-06 09:45:04 +0000605 warn(Msg);
606 else
607 error(Msg);
608}
609
Simon Atanasyan9e0297b2016-11-05 22:58:01 +0000610template <class RelTy>
611static std::pair<uint32_t, uint32_t>
612mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
613 // MIPS N32 ABI treats series of successive relocations with the same offset
614 // as a single relocation. The similar approach used by N64 ABI, but this ABI
615 // packs all relocations into the single relocation record. Here we emulate
616 // this for the N32 ABI. Iterate over relocation with the same offset and put
617 // theirs types into the single bit-set.
618 uint32_t Processed = 0;
619 for (; I != E && Offset == I->r_offset; ++I) {
620 ++Processed;
621 Type |= I->getType(Config->Mips64EL) << (8 * Processed);
622 }
623 return std::make_pair(Type, Processed);
624}
625
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000626// The reason we have to do this early scan is as follows
627// * To mmap the output file, we need to know the size
628// * For that, we need to know how many dynamic relocs we will have.
629// It might be possible to avoid this by outputting the file with write:
630// * Write the allocated output sections, computing addresses.
631// * Apply relocations, recording which ones require a dynamic reloc.
632// * Write the dynamic relocations.
633// * Write the rest of the file.
634// This would have some drawbacks. For example, we would only know if .rela.dyn
635// is needed after applying relocations. If it is, it will go after rw and rx
636// sections. Given that it is ro, we will need an extra PT_LOAD. This
637// complicates things for the dynamic linker and means we would have to reserve
638// space for the extra PT_LOAD even if we end up not using it.
639template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000640static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000641 typedef typename ELFT::uint uintX_t;
642
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000643 bool IsWrite = C.Flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000644
645 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
Eugene Levianta96d9022016-11-16 10:02:27 +0000646 In<ELFT>::RelaDyn->addReloc(Reloc);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000647 };
648
Vitaly Buka029d7302016-11-15 07:32:51 +0000649 const elf::ObjectFile<ELFT> *File = C.getFile();
Rafael Espindolac7e1e032016-09-12 13:13:53 +0000650 ArrayRef<uint8_t> SectionData = C.Data;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000651 const uint8_t *Buf = SectionData.begin();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000652
Rafael Espindola3abe3aa2016-07-21 21:15:32 +0000653 ArrayRef<EhSectionPiece> Pieces;
654 if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
655 Pieces = Eh->Pieces;
656
657 ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
658 ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000659
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000660 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
661 const RelTy &RI = *I;
Vitaly Buka029d7302016-11-15 07:32:51 +0000662 SymbolBody &Body = File->getRelocTargetSym(RI);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000663 uint32_t Type = RI.getType(Config->Mips64EL);
664
Simon Atanasyan9e0297b2016-11-05 22:58:01 +0000665 if (Config->MipsN32Abi) {
666 uint32_t Processed;
667 std::tie(Type, Processed) =
668 mergeMipsN32RelTypes(Type, RI.r_offset, I + 1, E);
669 I += Processed;
670 }
671
George Rimara4c7e742016-10-20 08:36:42 +0000672 // We only report undefined symbols if they are referenced somewhere in the
673 // code.
Eugene Leviant89837592016-10-06 09:45:04 +0000674 if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
Eugene Leviantb380b242016-10-26 11:07:09 +0000675 reportUndefined(Body, C, RI.r_offset);
Eugene Leviant89837592016-10-06 09:45:04 +0000676
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000677 RelExpr Expr = Target->getRelExpr(Type, Body);
Rafael Espindola678844e2016-06-17 15:42:36 +0000678 bool Preemptible = isPreemptible(Body, Type);
George Rimar463984d2016-11-15 08:07:14 +0000679 Expr = adjustExpr(*File, Body, IsWrite, Expr, Type, Buf + RI.r_offset, C,
680 RI.r_offset);
Rui Ueyamaf373dd72016-11-24 01:43:21 +0000681 if (ErrorCount)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000682 continue;
683
Rui Ueyama809d8e22016-06-23 04:33:42 +0000684 // Skip a relocation that points to a dead piece
Rafael Espindola5b7a79f2016-07-20 11:47:50 +0000685 // in a eh_frame section.
686 while (PieceI != PieceE &&
687 (PieceI->InputOff + PieceI->size() <= RI.r_offset))
688 ++PieceI;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000689
690 // Compute the offset of this section in the output section. We do it here
691 // to try to compute it only once.
692 uintX_t Offset;
693 if (PieceI != PieceE) {
694 assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
Rafael Espindola113860b2016-10-20 10:55:58 +0000695 if (PieceI->OutputOff == -1)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000696 continue;
697 Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000698 } else {
George Rimar3e6833b2016-08-19 15:46:28 +0000699 Offset = RI.r_offset;
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000700 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000701
702 // This relocation does not require got entry, but it is relative to got and
703 // needs it to be created. Here we request for that.
Rui Ueyamacd19b032017-02-16 06:24:16 +0000704 if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
705 R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
Eugene Leviantad4439e2016-11-11 11:33:32 +0000706 In<ELFT>::Got->HasGotOffRel = true;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000707
Rafael Espindola7386cea2017-02-16 00:12:34 +0000708 int64_t Addend = computeAddend(*File, Buf, E, RI, Expr, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000709
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000710 if (unsigned Processed =
711 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000712 I += (Processed - 1);
713 continue;
714 }
715
Peter Smithd6486032016-10-20 09:59:26 +0000716 // Ignore "hint" and TLS Descriptor call relocation because they are
717 // only markers for relaxation.
Sean Silva2eed7592016-12-01 05:43:48 +0000718 if (isRelExprOneOf<R_HINT, R_TLSDESC_CALL>(Expr))
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000719 continue;
720
Sean Silva2eed7592016-12-01 05:43:48 +0000721 if (needsPlt(Expr) ||
Sean Silva2eed7592016-12-01 05:43:48 +0000722 refersToGotEntry(Expr) || !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000723 // If the relocation points to something in the file, we can process it.
George Rimar463984d2016-11-15 08:07:14 +0000724 bool Constant =
725 isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, C, RI.r_offset);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000726
727 // If the output being produced is position independent, the final value
728 // is still not known. In that case we still need some help from the
729 // dynamic linker. We can however do better than just copying the incoming
730 // relocation. We can process some of it and and just ask the dynamic
731 // linker to add the load address.
732 if (!Constant)
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000733 AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000734
735 // If the produced value is a constant, we just remember to write it
736 // when outputting this section. We also have to do it if the format
737 // uses Elf_Rel, since in that case the written value is the addend.
738 if (Constant || !RelTy::IsRela)
Rafael Espindola664c6522016-09-07 20:37:34 +0000739 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000740 } else {
741 // We don't know anything about the finaly symbol. Just ask the dynamic
742 // linker to handle the relocation for us.
Eugene Leviantab024a32016-11-25 08:56:36 +0000743 if (!Target->isPicRel(Type))
Rui Ueyamada06bfb2016-11-25 18:51:53 +0000744 error(C.getLocation(Offset) + ": relocation " + toString(Type) +
Eugene Leviantab024a32016-11-25 08:56:36 +0000745 " cannot be used against shared object; recompile with -fPIC.");
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000746 AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
Eugene Leviantab024a32016-11-25 08:56:36 +0000747
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000748 // MIPS ABI turns using of GOT and dynamic relocations inside out.
749 // While regular ABI uses dynamic relocations to fill up GOT entries
750 // MIPS ABI requires dynamic linker to fills up GOT entries using
751 // specially sorted dynamic symbol table. This affects even dynamic
752 // relocations against symbols which do not require GOT entries
753 // creation explicitly, i.e. do not have any GOT-relocations. So if
754 // a preemptible symbol has a dynamic relocation we anyway have
755 // to create a GOT entry for it.
756 // If a non-preemptible symbol has a dynamic relocation against it,
757 // dynamic linker takes it st_value, adds offset and writes down
758 // result of the dynamic relocation. In case of preemptible symbol
759 // dynamic linker performs symbol resolution, writes the symbol value
760 // to the GOT entry and reads the GOT entry when it needs to perform
761 // a dynamic relocation.
762 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
Simon Atanasyan41325112016-06-19 21:39:37 +0000763 if (Config->EMachine == EM_MIPS)
Simon Atanasyan725dc142016-11-16 21:01:02 +0000764 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000765 continue;
766 }
767
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000768 // At this point we are done with the relocated position. Some relocations
769 // also require us to create a got or plt entry.
770
771 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
772 if (needsPlt(Expr)) {
773 if (Body.isInPlt())
774 continue;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000775
Peter Smithbaffdb82016-12-08 12:58:55 +0000776 if (Body.isGnuIFunc() && !Preemptible) {
777 In<ELFT>::Iplt->addEntry(Body);
778 In<ELFT>::IgotPlt->addEntry(Body);
779 In<ELFT>::RelaIplt->addReloc({Target->IRelativeRel, In<ELFT>::IgotPlt,
780 Body.getGotPltOffset<ELFT>(),
781 !Preemptible, &Body, 0});
782 } else {
783 In<ELFT>::Plt->addEntry(Body);
784 In<ELFT>::GotPlt->addEntry(Body);
785 In<ELFT>::RelaPlt->addReloc({Target->PltRel, In<ELFT>::GotPlt,
786 Body.getGotPltOffset<ELFT>(), !Preemptible,
787 &Body, 0});
788 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000789 continue;
790 }
791
792 if (refersToGotEntry(Expr)) {
Simon Atanasyan41325112016-06-19 21:39:37 +0000793 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanaf52f6a2016-09-08 09:07:12 +0000794 // MIPS ABI has special rules to process GOT entries and doesn't
795 // require relocation entries for them. A special case is TLS
796 // relocations. In that case dynamic loader applies dynamic
797 // relocations to initialize TLS GOT entries.
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000798 // See "Global Offset Table" in Chapter 5 in the following document
799 // for detailed description:
800 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyan725dc142016-11-16 21:01:02 +0000801 In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
Simon Atanasyan919a58c2016-09-08 09:07:19 +0000802 if (Body.isTls() && Body.isPreemptible())
Simon Atanasyan725dc142016-11-16 21:01:02 +0000803 AddDyn({Target->TlsGotRel, In<ELFT>::MipsGot,
804 Body.getGotOffset<ELFT>(), false, &Body, 0});
Simon Atanasyan41325112016-06-19 21:39:37 +0000805 continue;
806 }
807
808 if (Body.isInGot())
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000809 continue;
810
Eugene Leviantad4439e2016-11-11 11:33:32 +0000811 In<ELFT>::Got->addEntry(Body);
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000812 uintX_t Off = Body.getGotOffset<ELFT>();
813 uint32_t DynType;
Peter Smithde3e7382016-11-29 16:23:50 +0000814 RelExpr GotRE = R_ABS;
815 if (Body.isTls()) {
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000816 DynType = Target->TlsGotRel;
Peter Smithde3e7382016-11-29 16:23:50 +0000817 GotRE = R_TLS;
Rui Ueyama104e2352017-02-14 05:45:47 +0000818 } else if (!Preemptible && Config->pic() && !isAbsolute<ELFT>(Body))
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000819 DynType = Target->RelativeRel;
820 else
821 DynType = Target->GotRel;
822
Rafael Espindolaf4ff80c2016-12-02 01:57:24 +0000823 // FIXME: this logic is almost duplicated above.
Rui Ueyama104e2352017-02-14 05:45:47 +0000824 bool Constant =
825 !Preemptible && !(Config->pic() && !isAbsolute<ELFT>(Body));
Rafael Espindolaf4ff80c2016-12-02 01:57:24 +0000826 if (!Constant)
Rafael Espindolaf1e24532016-11-29 03:45:36 +0000827 AddDyn({DynType, In<ELFT>::Got, Off, !Preemptible, &Body, 0});
Rafael Espindolae004d4b2016-12-06 12:19:24 +0000828 if (Constant || (!RelTy::IsRela && !Preemptible))
Peter Smithde3e7382016-11-29 16:23:50 +0000829 In<ELFT>::Got->Relocations.push_back({GotRE, DynType, Off, 0, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000830 continue;
831 }
832 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000833}
834
Rafael Espindola9f0c4bb2016-11-10 14:53:24 +0000835template <class ELFT> void scanRelocations(InputSectionBase<ELFT> &S) {
836 if (S.AreRelocsRela)
837 scanRelocs(S, S.relas());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000838 else
Rafael Espindola9f0c4bb2016-11-10 14:53:24 +0000839 scanRelocs(S, S.rels());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000840}
841
Peter Smith3a52eb02017-02-01 10:26:03 +0000842// Insert the Thunks for OutputSection OS into their designated place
843// in the Sections vector, and recalculate the InputSection output section
844// offsets.
845// This may invalidate any output section offsets stored outside of InputSection
846template <class ELFT>
847static void mergeThunks(OutputSection<ELFT> *OS,
848 std::vector<ThunkSection<ELFT> *> &Thunks) {
849 // Order Thunks in ascending OutSecOff
850 auto ThunkCmp = [](const ThunkSection<ELFT> *A, const ThunkSection<ELFT> *B) {
851 return A->OutSecOff < B->OutSecOff;
852 };
853 std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
854
855 // Merge sorted vectors of Thunks and InputSections by OutSecOff
856 std::vector<InputSection<ELFT> *> Tmp;
857 Tmp.reserve(OS->Sections.size() + Thunks.size());
858 auto MergeCmp = [](const InputSection<ELFT> *A, const InputSection<ELFT> *B) {
859 // std::merge requires a strict weak ordering.
860 if (A->OutSecOff < B->OutSecOff)
861 return true;
862 if (A->OutSecOff == B->OutSecOff)
863 // Check if Thunk is immediately before any specific Target InputSection
864 // for example Mips LA25 Thunks.
865 if (auto *TA = dyn_cast<ThunkSection<ELFT>>(A))
866 if (TA && TA->getTargetInputSection() == B)
867 return true;
868 return false;
869 };
870 std::merge(OS->Sections.begin(), OS->Sections.end(), Thunks.begin(),
871 Thunks.end(), std::back_inserter(Tmp), MergeCmp);
872 OS->Sections = std::move(Tmp);
873 OS->Size = 0;
874 OS->assignOffsets();
875}
876
877// Process all relocations from the InputSections that have been assigned
878// to OutputSections and redirect through Thunks if needed.
879//
880// createThunks must be called after scanRelocs has created the Relocations for
881// each InputSection. It must be called before the static symbol table is
882// finalized. If any Thunks are added to an OutputSection the output section
883// offsets of the InputSections will change.
884//
885// FIXME: All Thunks are assumed to be in range of the relocation. Range
886// extension Thunks are not yet supported.
Peter Smithee6d7182017-01-18 09:57:14 +0000887template <class ELFT>
888void createThunks(ArrayRef<OutputSectionBase *> OutputSections) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000889 // Track Symbols that already have a Thunk
890 DenseMap<SymbolBody *, Thunk<ELFT> *> ThunkedSymbols;
891 // Track InputSections that have a ThunkSection placed in front
892 DenseMap<InputSection<ELFT> *, ThunkSection<ELFT> *> ThunkedSections;
893 // Track the ThunksSections that need to be inserted into an OutputSection
894 std::map<OutputSection<ELFT> *, std::vector<ThunkSection<ELFT> *>>
895 ThunkSections;
896
897 // Find or create a Thunk for Body for relocation Type
898 auto GetThunk = [&](SymbolBody &Body, uint32_t Type) {
899 auto res = ThunkedSymbols.insert({&Body, nullptr});
900 if (res.second == true)
901 res.first->second = addThunk<ELFT>(Type, Body);
902 return std::make_pair(res.first->second, res.second);
903 };
904
905 // Find or create a ThunkSection to be placed immediately before IS
906 auto GetISThunkSec = [&](InputSection<ELFT> *IS, OutputSection<ELFT> *OS) {
907 ThunkSection<ELFT> *TS = ThunkedSections.lookup(IS);
908 if (TS)
909 return TS;
910 auto *TOS = cast<OutputSection<ELFT>>(IS->OutSec);
911 TS = make<ThunkSection<ELFT>>(TOS, IS->OutSecOff);
912 ThunkSections[OS].push_back(TS);
913 ThunkedSections[IS] = TS;
914 return TS;
915 };
916 // Find or create a ThunkSection to be placed as last executable section in
917 // OS.
918 auto GetOSThunkSec = [&](ThunkSection<ELFT> *&TS, OutputSection<ELFT> *OS) {
919 if (TS == nullptr) {
920 uint32_t Off = 0;
921 for (auto *IS : OS->Sections) {
922 Off = IS->OutSecOff + IS->getSize();
923 if ((IS->Flags & SHF_EXECINSTR) == 0)
924 break;
925 }
926 TS = make<ThunkSection<ELFT>>(OS, Off);
927 ThunkSections[OS].push_back(TS);
928 }
929 return TS;
930 };
931 // Create all the Thunks and insert them into synthetic ThunkSections. The
932 // ThunkSections are later inserted back into the OutputSection.
933
934 // We separate the creation of ThunkSections from the insertion of the
935 // ThunkSections back into the OutputSection as ThunkSections are not always
936 // inserted into the same OutputSection as the caller.
Peter Smithee6d7182017-01-18 09:57:14 +0000937 for (OutputSectionBase *Base : OutputSections) {
Peter Smith94b999b2017-01-20 15:25:45 +0000938 auto *OS = dyn_cast<OutputSection<ELFT>>(Base);
939 if (OS == nullptr)
940 continue;
Peter Smith3a52eb02017-02-01 10:26:03 +0000941
942 ThunkSection<ELFT> *OSTS = nullptr;
Peter Smith94b999b2017-01-20 15:25:45 +0000943 for (InputSection<ELFT> *IS : OS->Sections) {
Peter Smith3a52eb02017-02-01 10:26:03 +0000944 for (Relocation &Rel : IS->Relocations) {
945 SymbolBody &Body = *Rel.Sym;
946 if (Target->needsThunk(Rel.Expr, Rel.Type, IS->getFile(), Body)) {
947 Thunk<ELFT> *T;
948 bool IsNew;
949 std::tie(T, IsNew) = GetThunk(Body, Rel.Type);
950 if (IsNew) {
951 // Find or create a ThunkSection for the new Thunk
952 ThunkSection<ELFT> *TS;
953 if (auto *TIS = T->getTargetInputSection())
954 TS = GetISThunkSec(TIS, OS);
955 else
956 TS = GetOSThunkSec(OSTS, OS);
957 TS->addThunk(T);
958 }
959 // Redirect relocation to Thunk, we never go via the PLT to a Thunk
960 Rel.Sym = T->ThunkSym;
961 Rel.Expr = fromPlt(Rel.Expr);
962 }
Peter Smithee6d7182017-01-18 09:57:14 +0000963 }
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000964 }
965 }
Peter Smith3a52eb02017-02-01 10:26:03 +0000966
967 // Merge all created synthetic ThunkSections back into OutputSection
968 for (auto &KV : ThunkSections)
969 mergeThunks<ELFT>(KV.first, KV.second);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000970}
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000971
Rafael Espindola9f0c4bb2016-11-10 14:53:24 +0000972template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &);
973template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &);
974template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &);
975template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000976
Peter Smithee6d7182017-01-18 09:57:14 +0000977template void createThunks<ELF32LE>(ArrayRef<OutputSectionBase *>);
978template void createThunks<ELF32BE>(ArrayRef<OutputSectionBase *>);
979template void createThunks<ELF64LE>(ArrayRef<OutputSectionBase *>);
980template void createThunks<ELF64BE>(ArrayRef<OutputSectionBase *>);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000981}
982}