blob: 63ed23ea8db01a3c693cda92e113298fb28fd103 [file] [log] [blame]
Rui Ueyama0fcdc732016-05-24 20:24:43 +00001//===- Relocations.cpp ----------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
George Rimar95912d02016-06-08 12:29:29 +000010// This file contains platform-independent functions to process relocations.
Rui Ueyama0fcdc732016-05-24 20:24:43 +000011// I'll describe the overview of this file here.
12//
13// Simple relocations are easy to handle for the linker. For example,
14// for R_X86_64_PC64 relocs, the linker just has to fix up locations
15// with the relative offsets to the target symbols. It would just be
16// reading records from relocation sections and applying them to output.
17//
18// But not all relocations are that easy to handle. For example, for
19// R_386_GOTOFF relocs, the linker has to create new GOT entries for
20// symbols if they don't exist, and fix up locations with GOT entry
21// offsets from the beginning of GOT section. So there is more than
22// fixing addresses in relocation processing.
23//
24// ELF defines a large number of complex relocations.
25//
26// The functions in this file analyze relocations and do whatever needs
27// to be done. It includes, but not limited to, the following.
28//
29// - create GOT/PLT entries
30// - create new relocations in .dynsym to let the dynamic linker resolve
31// them at runtime (since ELF supports dynamic linking, not all
32// relocations can be resolved at link-time)
33// - create COPY relocs and reserve space in .bss
34// - replace expensive relocs (in terms of runtime cost) with cheap ones
35// - error out infeasible combinations such as PIC and non-relative relocs
36//
37// Note that the functions in this file don't actually apply relocations
38// because it doesn't know about the output file nor the output file buffer.
39// It instead stores Relocation objects to InputSection's Relocations
40// vector to let it apply later in InputSection::writeTo.
41//
42//===----------------------------------------------------------------------===//
43
44#include "Relocations.h"
45#include "Config.h"
46#include "OutputSections.h"
47#include "SymbolTable.h"
48#include "Target.h"
49
50#include "llvm/Support/Endian.h"
51#include "llvm/Support/raw_ostream.h"
52
53using namespace llvm;
54using namespace llvm::ELF;
55using namespace llvm::object;
56using namespace llvm::support::endian;
57
58namespace lld {
59namespace elf {
60
61static bool refersToGotEntry(RelExpr Expr) {
62 return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL ||
63 Expr == R_MIPS_GOT_LOCAL_PAGE || Expr == R_GOT_PAGE_PC ||
64 Expr == R_GOT_PC || Expr == R_GOT_FROM_END || Expr == R_TLSGD ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +000065 Expr == R_TLSGD_PC || Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +000066}
67
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000068static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
69 // In case of MIPS GP-relative relocations always resolve to a definition
70 // in a regular input file, ignoring the one-definition rule. So we,
71 // for example, should not attempt to create a dynamic relocation even
72 // if the target symbol is preemptible. There are two two MIPS GP-relative
73 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
74 // can be against a preemptible symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000075 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000076 // relocation types occupy eight bit. In case of N64 ABI we extract first
77 // relocation from 3-in-1 packet because only the first relocation can
78 // be against a real symbol.
Simon Atanasyana26a1572016-06-10 12:26:09 +000079 if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
Simon Atanasyan9a9a3162016-05-28 04:49:57 +000080 return false;
81 return Body.isPreemptible();
82}
83
Rui Ueyama0fcdc732016-05-24 20:24:43 +000084// Returns the number of relocations processed.
85template <class ELFT>
86static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
87 InputSectionBase<ELFT> &C,
88 typename ELFT::uint Offset,
89 typename ELFT::uint Addend, RelExpr Expr) {
90 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
91 return 0;
92
93 if (!Body.isTls())
94 return 0;
95
96 typedef typename ELFT::uint uintX_t;
Rafael Espindolae37d13b2016-06-02 19:49:53 +000097
98 if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
99 Config->Shared) {
100 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
101 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
102 Out<ELFT>::RelaDyn->addReloc(
103 {Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
104 }
105 if (Expr != R_HINT)
106 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
107 return 1;
108 }
109
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000110 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
111 // Local-Dynamic relocs can be relaxed to Local-Exec.
112 if (!Config->Shared) {
113 C.Relocations.push_back(
114 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
115 return 2;
116 }
117 if (Out<ELFT>::Got->addTlsIndex())
118 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
119 Out<ELFT>::Got->getTlsIndexOff(), false,
120 nullptr, 0});
121 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
122 return 1;
123 }
124
125 // Local-Dynamic relocs can be relaxed to Local-Exec.
126 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
127 C.Relocations.push_back(
128 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
129 return 1;
130 }
131
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000132 if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
133 Target->isTlsGlobalDynamicRel(Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000134 if (Config->Shared) {
135 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
136 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
137 Out<ELFT>::RelaDyn->addReloc(
138 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Rafael Espindolaa8777c22016-06-08 21:31:59 +0000139
140 // If the symbol is preemptible we need the dynamic linker to write
141 // the offset too.
142 if (Body.isPreemptible())
143 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
144 Off + (uintX_t)sizeof(uintX_t), false,
145 &Body, 0});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000146 }
147 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
148 return 1;
149 }
150
151 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
152 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000153 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000154 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000155 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
156 Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000157 if (!Body.isInGot()) {
158 Out<ELFT>::Got->addEntry(Body);
159 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
160 Body.getGotOffset<ELFT>(), false, &Body,
161 0});
162 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000163 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000164 }
165 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000166 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
167 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000168 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000169 }
170
171 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
172 // defined.
173 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000174 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000175 C.Relocations.push_back(
176 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
177 return 1;
178 }
179 return 0;
180}
181
182// Some targets might require creation of thunks for relocations. Now we
183// support only MIPS which requires LA25 thunk to call PIC code from non-PIC
184// one. Scan relocations to find each one requires thunk.
185template <class ELFT, class RelTy>
186static void scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
187 ArrayRef<RelTy> Rels) {
188 for (const RelTy &RI : Rels) {
189 uint32_t Type = RI.getType(Config->Mips64EL);
190 SymbolBody &Body = File.getRelocTargetSym(RI);
191 if (Body.hasThunk() || !Target->needsThunk(Type, File, Body))
192 continue;
193 auto *D = cast<DefinedRegular<ELFT>>(&Body);
194 auto *S = cast<InputSection<ELFT>>(D->Section);
195 S->addThunk(Body);
196 }
197}
198
199template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
200 return read32<E>(Loc) & 0xffff;
201}
202
203template <class RelTy>
204static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
205 switch (Rel->getType(Config->Mips64EL)) {
206 case R_MIPS_HI16:
207 return R_MIPS_LO16;
208 case R_MIPS_GOT16:
209 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
210 case R_MIPS_PCHI16:
211 return R_MIPS_PCLO16;
212 case R_MICROMIPS_HI16:
213 return R_MICROMIPS_LO16;
214 default:
215 return R_MIPS_NONE;
216 }
217}
218
219template <class ELFT, class RelTy>
220static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
221 SymbolBody &Sym, const RelTy *Rel,
222 const RelTy *End) {
223 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
224 uint32_t Type = getMipsPairType(Rel, Sym);
225
226 // Some MIPS relocations use addend calculated from addend of the relocation
227 // itself and addend of paired relocation. ABI requires to compute such
228 // combined addend in case of REL relocation record format only.
229 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
230 if (RelTy::IsRela || Type == R_MIPS_NONE)
231 return 0;
232
233 for (const RelTy *RI = Rel; RI != End; ++RI) {
234 if (RI->getType(Config->Mips64EL) != Type)
235 continue;
236 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
237 continue;
238 const endianness E = ELFT::TargetEndianness;
239 return ((read32<E>(BufLoc) & 0xffff) << 16) +
240 readSignedLo16<E>(Buf + RI->r_offset);
241 }
George Rimare6389d12016-06-08 12:22:26 +0000242 warning("can't find matching " + getRelName(Type) + " relocation for " +
243 getRelName(Rel->getType(Config->Mips64EL)));
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000244 return 0;
245}
246
247// True if non-preemptable symbol always has the same value regardless of where
248// the DSO is loaded.
249template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
250 if (Body.isUndefined())
251 return !Body.isLocal() && Body.symbol()->isWeak();
252 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
253 return DR->Section == nullptr; // Absolute symbol.
254 return false;
255}
256
257static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000258 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
259 Expr == R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000260}
261
262// True if this expression is of the form Sym - X, where X is a position in the
263// file (PC, or GOT for example).
264static bool isRelExpr(RelExpr Expr) {
George Rimar5c33b912016-05-25 14:31:37 +0000265 return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Rafael Espindolaa8433c12016-06-01 06:15:22 +0000266 Expr == R_RELAX_GOT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000267}
268
269template <class ELFT>
270static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
271 const SymbolBody &Body) {
272 // These expressions always compute a constant
273 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
274 E == R_MIPS_GOT_LOCAL || E == R_MIPS_GOT_LOCAL_PAGE ||
275 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000276 E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE || E == R_HINT)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000277 return true;
278
279 // These never do, except if the entire file is position dependent or if
280 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000281 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000282 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
283
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000284 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000285 return false;
286
287 if (!Config->Pic)
288 return true;
289
290 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
291 bool RelE = isRelExpr(E);
292 if (AbsVal && !RelE)
293 return true;
294 if (!AbsVal && RelE)
295 return true;
296
297 // Relative relocation to an absolute value. This is normally unrepresentable,
298 // but if the relocation refers to a weak undefined symbol, we allow it to
299 // resolve to the image base. This is a little strange, but it allows us to
300 // link function calls to such symbols. Normally such a call will be guarded
301 // with a comparison, which will load a zero from the GOT.
302 if (AbsVal && RelE) {
303 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
304 return true;
George Rimare6389d12016-06-08 12:22:26 +0000305 error("relocation " + getRelName(Type) +
306 " cannot refer to absolute symbol " + Body.getName());
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000307 return true;
308 }
309
310 return Target->usesOnlyLowPageBits(Type);
311}
312
313static RelExpr toPlt(RelExpr Expr) {
314 if (Expr == R_PPC_OPD)
315 return R_PPC_PLT_OPD;
316 if (Expr == R_PC)
317 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000318 if (Expr == R_PAGE_PC)
319 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000320 if (Expr == R_ABS)
321 return R_PLT;
322 return Expr;
323}
324
325static RelExpr fromPlt(RelExpr Expr) {
326 // We decided not to use a plt. Optimize a reference to the plt to a
327 // reference to the symbol itself.
328 if (Expr == R_PLT_PC)
329 return R_PC;
330 if (Expr == R_PPC_PLT_OPD)
331 return R_PPC_OPD;
332 if (Expr == R_PLT)
333 return R_ABS;
334 return Expr;
335}
336
337template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
338 typedef typename ELFT::uint uintX_t;
339
340 uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
341 uintX_t SymValue = SS->Sym.st_value;
342 int TrailingZeros =
343 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
344 return 1 << TrailingZeros;
345}
346
347// Reserve space in .bss for copy relocation.
348template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
349 typedef typename ELFT::uint uintX_t;
350 typedef typename ELFT::Sym Elf_Sym;
351
352 // Copy relocation against zero-sized symbol doesn't make sense.
353 uintX_t SymSize = SS->template getSize<ELFT>();
354 if (SymSize == 0)
355 fatal("cannot create a copy relocation for " + SS->getName());
356
357 uintX_t Align = getAlignment(SS);
358 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Align);
359 Out<ELFT>::Bss->setSize(Off + SymSize);
360 Out<ELFT>::Bss->updateAlign(Align);
361 uintX_t Shndx = SS->Sym.st_shndx;
362 uintX_t Value = SS->Sym.st_value;
363 // Look through the DSO's dynamic symbol table for aliases and create a
364 // dynamic symbol for each one. This causes the copy relocation to correctly
365 // interpose any aliases.
366 for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
367 if (S.st_shndx != Shndx || S.st_value != Value)
368 continue;
369 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
370 Symtab<ELFT>::X->find(check(S.getName(SS->File->getStringTable()))));
371 if (!Alias)
372 continue;
373 Alias->OffsetInBss = Off;
374 Alias->NeedsCopyOrPltAddr = true;
375 Alias->symbol()->IsUsedInRegularObj = true;
376 }
377 Out<ELFT>::RelaDyn->addReloc(
378 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
379}
380
381template <class ELFT>
382static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000383 bool IsWrite, RelExpr Expr, uint32_t Type,
384 const uint8_t *Data, typename ELFT::uint Offset) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000385 if (Target->needsThunk(Type, File, Body))
386 return R_THUNK;
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000387 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000388 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000389 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000390 } else if (!Preemptible) {
391 if (needsPlt(Expr))
392 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000393 if (Expr == R_GOT_PC)
Rafael Espindola5c66b822016-06-04 22:58:54 +0000394 Expr = Target->adjustRelaxExpr(Type, Data + Offset, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000395 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000396
397 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
398 return Expr;
399
400 // This relocation would require the dynamic linker to write a value to read
401 // only memory. We can hack around it if we are producing an executable and
402 // the refered symbol can be preemepted to refer to the executable.
403 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
George Rimar3ed2b082016-06-10 08:00:01 +0000404 error("can't create dynamic relocation " + getRelName(Type) +
405 " against readonly segment");
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000406 return Expr;
407 }
408 if (Body.getVisibility() != STV_DEFAULT) {
409 error("Cannot preempt symbol");
410 return Expr;
411 }
412 if (Body.isObject()) {
413 // Produce a copy relocation.
414 auto *B = cast<SharedSymbol<ELFT>>(&Body);
415 if (!B->needsCopy())
416 addCopyRelSymbol(B);
417 return Expr;
418 }
419 if (Body.isFunc()) {
420 // This handles a non PIC program call to function in a shared library. In
421 // an ideal world, we could just report an error saying the relocation can
422 // overflow at runtime. In the real world with glibc, crt1.o has a
423 // R_X86_64_PC32 pointing to libc.so.
424 //
425 // The general idea on how to handle such cases is to create a PLT entry and
426 // use that as the function value.
427 //
428 // For the static linking part, we just return a plt expr and everything
429 // else will use the the PLT entry as the address.
430 //
431 // The remaining problem is making sure pointer equality still works. We
432 // need the help of the dynamic linker for that. We let it know that we have
433 // a direct reference to a so symbol by creating an undefined symbol with a
434 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
435 // the value of the symbol we created. This is true even for got entries, so
436 // pointer equality is maintained. To avoid an infinite loop, the only entry
437 // that points to the real function is a dedicated got entry used by the
438 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
439 // R_386_JMP_SLOT, etc).
440 Body.NeedsCopyOrPltAddr = true;
441 return toPlt(Expr);
442 }
443 error("Symbol is missing type");
444
445 return Expr;
446}
447
448template <class ELFT, class RelTy>
449static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
450 const uint8_t *SectionData,
451 const RelTy *End, const RelTy &RI,
452 RelExpr Expr, SymbolBody &Body) {
453 typedef typename ELFT::uint uintX_t;
454
455 uint32_t Type = RI.getType(Config->Mips64EL);
456 uintX_t Addend = getAddend<ELFT>(RI);
457 const uint8_t *BufLoc = SectionData + RI.r_offset;
458 if (!RelTy::IsRela)
459 Addend += Target->getImplicitAddend(BufLoc, Type);
460 if (Config->EMachine == EM_MIPS) {
461 Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
462 if (Type == R_MIPS_LO16 && Expr == R_PC)
463 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
464 // symbol. In that case we should use the following formula for
465 // calculation "AHL + GP - P + 4". Let's add 4 right here.
466 // For details see p. 4-19 at
467 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
468 Addend += 4;
469 if (Expr == R_GOT_OFF)
470 Addend -= MipsGPOffset;
471 if (Expr == R_GOTREL) {
472 Addend -= MipsGPOffset;
473 if (Body.isLocal())
474 Addend += File.getMipsGp0();
475 }
476 }
477 if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
478 Addend += getPPC64TocBase();
479 return Addend;
480}
481
482// The reason we have to do this early scan is as follows
483// * To mmap the output file, we need to know the size
484// * For that, we need to know how many dynamic relocs we will have.
485// It might be possible to avoid this by outputting the file with write:
486// * Write the allocated output sections, computing addresses.
487// * Apply relocations, recording which ones require a dynamic reloc.
488// * Write the dynamic relocations.
489// * Write the rest of the file.
490// This would have some drawbacks. For example, we would only know if .rela.dyn
491// is needed after applying relocations. If it is, it will go after rw and rx
492// sections. Given that it is ro, we will need an extra PT_LOAD. This
493// complicates things for the dynamic linker and means we would have to reserve
494// space for the extra PT_LOAD even if we end up not using it.
495template <class ELFT, class RelTy>
Rui Ueyama2487f192016-05-25 03:40:02 +0000496static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000497 typedef typename ELFT::uint uintX_t;
498
George Rimardb0168d2016-06-09 15:17:29 +0000499 bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000500
501 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
502 Out<ELFT>::RelaDyn->addReloc(Reloc);
503 };
504
505 const elf::ObjectFile<ELFT> &File = *C.getFile();
506 ArrayRef<uint8_t> SectionData = C.getSectionData();
507 const uint8_t *Buf = SectionData.begin();
508 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
509 const RelTy &RI = *I;
510 SymbolBody &Body = File.getRelocTargetSym(RI);
511 uint32_t Type = RI.getType(Config->Mips64EL);
512
513 RelExpr Expr = Target->getRelExpr(Type, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000514 uintX_t Offset = C.getOffset(RI.r_offset);
515 if (Offset == (uintX_t)-1)
516 continue;
517
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000518 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000519 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf, Offset);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000520 if (HasError)
521 continue;
522
523 // This relocation does not require got entry, but it is relative to got and
524 // needs it to be created. Here we request for that.
525 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
526 Out<ELFT>::Got->HasGotOffRel = true;
527
528 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
529
530 if (unsigned Processed =
531 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
532 I += (Processed - 1);
533 continue;
534 }
535
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000536 // Ignore "hint" relocation because it is for optional code optimization.
537 if (Expr == R_HINT)
538 continue;
539
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000540 if (needsPlt(Expr) || Expr == R_THUNK || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000541 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000542 // If the relocation points to something in the file, we can process it.
543 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
544
545 // If the output being produced is position independent, the final value
546 // is still not known. In that case we still need some help from the
547 // dynamic linker. We can however do better than just copying the incoming
548 // relocation. We can process some of it and and just ask the dynamic
549 // linker to add the load address.
550 if (!Constant)
551 AddDyn({Target->RelativeRel, C.OutSec, Offset, true, &Body, Addend});
552
553 // If the produced value is a constant, we just remember to write it
554 // when outputting this section. We also have to do it if the format
555 // uses Elf_Rel, since in that case the written value is the addend.
556 if (Constant || !RelTy::IsRela)
557 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
558 } else {
559 // We don't know anything about the finaly symbol. Just ask the dynamic
560 // linker to handle the relocation for us.
561 AddDyn({Target->getDynRel(Type), C.OutSec, Offset, false, &Body, Addend});
562 // MIPS ABI turns using of GOT and dynamic relocations inside out.
563 // While regular ABI uses dynamic relocations to fill up GOT entries
564 // MIPS ABI requires dynamic linker to fills up GOT entries using
565 // specially sorted dynamic symbol table. This affects even dynamic
566 // relocations against symbols which do not require GOT entries
567 // creation explicitly, i.e. do not have any GOT-relocations. So if
568 // a preemptible symbol has a dynamic relocation we anyway have
569 // to create a GOT entry for it.
570 // If a non-preemptible symbol has a dynamic relocation against it,
571 // dynamic linker takes it st_value, adds offset and writes down
572 // result of the dynamic relocation. In case of preemptible symbol
573 // dynamic linker performs symbol resolution, writes the symbol value
574 // to the GOT entry and reads the GOT entry when it needs to perform
575 // a dynamic relocation.
576 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
577 if (Config->EMachine == EM_MIPS && !Body.isInGot())
578 Out<ELFT>::Got->addEntry(Body);
579 continue;
580 }
581
582 if (Expr == R_THUNK)
583 continue;
584
585 // At this point we are done with the relocated position. Some relocations
586 // also require us to create a got or plt entry.
587
588 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
589 if (needsPlt(Expr)) {
590 if (Body.isInPlt())
591 continue;
592 Out<ELFT>::Plt->addEntry(Body);
593
594 uint32_t Rel;
595 if (Body.isGnuIFunc() && !Preemptible)
596 Rel = Target->IRelativeRel;
597 else
598 Rel = Target->PltRel;
599
600 Out<ELFT>::GotPlt->addEntry(Body);
601 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
602 Body.getGotPltOffset<ELFT>(), !Preemptible,
603 &Body, 0});
604 continue;
605 }
606
607 if (refersToGotEntry(Expr)) {
608 if (Body.isInGot())
609 continue;
610 Out<ELFT>::Got->addEntry(Body);
611
612 if (Config->EMachine == EM_MIPS)
613 // MIPS ABI has special rules to process GOT entries
614 // and doesn't require relocation entries for them.
615 // See "Global Offset Table" in Chapter 5 in the following document
616 // for detailed description:
617 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
618 continue;
619
620 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
621 uint32_t DynType;
622 if (Body.isTls())
623 DynType = Target->TlsGotRel;
624 else if (Preemptible)
625 DynType = Target->GotRel;
626 else
627 DynType = Target->RelativeRel;
628 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
629 !Preemptible, &Body, 0});
630 }
631 continue;
632 }
633 }
634
635 // Scan relocations for necessary thunks.
636 if (Config->EMachine == EM_MIPS)
637 scanRelocsForThunks<ELFT>(File, Rels);
638}
639
640template <class ELFT> void scanRelocations(InputSection<ELFT> &C) {
641 typedef typename ELFT::Shdr Elf_Shdr;
642
643 // Scan all relocations. Each relocation goes through a series
644 // of tests to determine if it needs special treatment, such as
645 // creating GOT, PLT, copy relocations, etc.
646 // Note that relocations for non-alloc sections are directly
647 // processed by InputSection::relocateNative.
648 if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
649 for (const Elf_Shdr *RelSec : C.RelocSections)
650 scanRelocations(C, *RelSec);
651}
652
653template <class ELFT>
654void scanRelocations(InputSectionBase<ELFT> &S,
655 const typename ELFT::Shdr &RelSec) {
656 ELFFile<ELFT> &EObj = S.getFile()->getObj();
657 if (RelSec.sh_type == SHT_RELA)
658 scanRelocs(S, EObj.relas(&RelSec));
659 else
660 scanRelocs(S, EObj.rels(&RelSec));
661}
662
663template void scanRelocations<ELF32LE>(InputSection<ELF32LE> &);
664template void scanRelocations<ELF32BE>(InputSection<ELF32BE> &);
665template void scanRelocations<ELF64LE>(InputSection<ELF64LE> &);
666template void scanRelocations<ELF64BE>(InputSection<ELF64BE> &);
667
668template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
669 const ELF32LE::Shdr &);
670template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
671 const ELF32BE::Shdr &);
672template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
673 const ELF64LE::Shdr &);
674template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
675 const ELF64BE::Shdr &);
676}
677}