blob: 3e59a0e2cf4ff3d69a2cca7f714adb8071f5cfa9 [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//
10// This file contains platform-independent functions to processe relocations.
11// 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.
75 // To get MIPS relocation type we apply 0xf mask. In case of O32 ABI all
76 // 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.
79 if (Config->EMachine == EM_MIPS && (Type & 0xf) == R_MIPS_GPREL16)
80 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});
139 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
140 Off + (uintX_t)sizeof(uintX_t), false,
141 &Body, 0});
142 }
143 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
144 return 1;
145 }
146
147 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
148 // depending on the symbol being locally defined or not.
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000149 if (isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000150 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000151 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
152 Offset, Addend, &Body});
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000153 if (!Body.isInGot()) {
154 Out<ELFT>::Got->addEntry(Body);
155 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
156 Body.getGotOffset<ELFT>(), false, &Body,
157 0});
158 }
Rafael Espindolae1979ae2016-06-04 23:33:31 +0000159 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000160 }
161 C.Relocations.push_back(
Rafael Espindola69f54022016-06-04 23:22:34 +0000162 {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
163 Offset, Addend, &Body});
Rafael Espindolaf807d472016-06-04 23:04:39 +0000164 return Target->TlsGdRelaxSkip;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000165 }
166
167 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
168 // defined.
169 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000170 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000171 C.Relocations.push_back(
172 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
173 return 1;
174 }
175 return 0;
176}
177
178// Some targets might require creation of thunks for relocations. Now we
179// support only MIPS which requires LA25 thunk to call PIC code from non-PIC
180// one. Scan relocations to find each one requires thunk.
181template <class ELFT, class RelTy>
182static void scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
183 ArrayRef<RelTy> Rels) {
184 for (const RelTy &RI : Rels) {
185 uint32_t Type = RI.getType(Config->Mips64EL);
186 SymbolBody &Body = File.getRelocTargetSym(RI);
187 if (Body.hasThunk() || !Target->needsThunk(Type, File, Body))
188 continue;
189 auto *D = cast<DefinedRegular<ELFT>>(&Body);
190 auto *S = cast<InputSection<ELFT>>(D->Section);
191 S->addThunk(Body);
192 }
193}
194
195template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
196 return read32<E>(Loc) & 0xffff;
197}
198
199template <class RelTy>
200static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
201 switch (Rel->getType(Config->Mips64EL)) {
202 case R_MIPS_HI16:
203 return R_MIPS_LO16;
204 case R_MIPS_GOT16:
205 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
206 case R_MIPS_PCHI16:
207 return R_MIPS_PCLO16;
208 case R_MICROMIPS_HI16:
209 return R_MICROMIPS_LO16;
210 default:
211 return R_MIPS_NONE;
212 }
213}
214
215template <class ELFT, class RelTy>
216static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
217 SymbolBody &Sym, const RelTy *Rel,
218 const RelTy *End) {
219 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
220 uint32_t Type = getMipsPairType(Rel, Sym);
221
222 // Some MIPS relocations use addend calculated from addend of the relocation
223 // itself and addend of paired relocation. ABI requires to compute such
224 // combined addend in case of REL relocation record format only.
225 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
226 if (RelTy::IsRela || Type == R_MIPS_NONE)
227 return 0;
228
229 for (const RelTy *RI = Rel; RI != End; ++RI) {
230 if (RI->getType(Config->Mips64EL) != Type)
231 continue;
232 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
233 continue;
234 const endianness E = ELFT::TargetEndianness;
235 return ((read32<E>(BufLoc) & 0xffff) << 16) +
236 readSignedLo16<E>(Buf + RI->r_offset);
237 }
238 unsigned OldType = Rel->getType(Config->Mips64EL);
239 StringRef OldName = getELFRelocationTypeName(Config->EMachine, OldType);
240 StringRef NewName = getELFRelocationTypeName(Config->EMachine, Type);
241 warning("can't find matching " + NewName + " relocation for " + OldName);
242 return 0;
243}
244
245// True if non-preemptable symbol always has the same value regardless of where
246// the DSO is loaded.
247template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
248 if (Body.isUndefined())
249 return !Body.isLocal() && Body.symbol()->isWeak();
250 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
251 return DR->Section == nullptr; // Absolute symbol.
252 return false;
253}
254
255static bool needsPlt(RelExpr Expr) {
Rafael Espindola12dc4462016-06-04 19:11:14 +0000256 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
257 Expr == R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000258}
259
260// True if this expression is of the form Sym - X, where X is a position in the
261// file (PC, or GOT for example).
262static bool isRelExpr(RelExpr Expr) {
George Rimar5c33b912016-05-25 14:31:37 +0000263 return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Rafael Espindolaa8433c12016-06-01 06:15:22 +0000264 Expr == R_RELAX_GOT_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000265}
266
267template <class ELFT>
268static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
269 const SymbolBody &Body) {
270 // These expressions always compute a constant
271 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
272 E == R_MIPS_GOT_LOCAL || E == R_MIPS_GOT_LOCAL_PAGE ||
273 E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000274 E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE || E == R_HINT)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000275 return true;
276
277 // These never do, except if the entire file is position dependent or if
278 // only the low bits are used.
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000279 if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000280 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
281
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000282 if (isPreemptible(Body, Type))
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000283 return false;
284
285 if (!Config->Pic)
286 return true;
287
288 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
289 bool RelE = isRelExpr(E);
290 if (AbsVal && !RelE)
291 return true;
292 if (!AbsVal && RelE)
293 return true;
294
295 // Relative relocation to an absolute value. This is normally unrepresentable,
296 // but if the relocation refers to a weak undefined symbol, we allow it to
297 // resolve to the image base. This is a little strange, but it allows us to
298 // link function calls to such symbols. Normally such a call will be guarded
299 // with a comparison, which will load a zero from the GOT.
300 if (AbsVal && RelE) {
301 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
302 return true;
303 StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
304 error("relocation " + S + " cannot refer to absolute symbol " +
305 Body.getName());
306 return true;
307 }
308
309 return Target->usesOnlyLowPageBits(Type);
310}
311
312static RelExpr toPlt(RelExpr Expr) {
313 if (Expr == R_PPC_OPD)
314 return R_PPC_PLT_OPD;
315 if (Expr == R_PC)
316 return R_PLT_PC;
Rafael Espindola12dc4462016-06-04 19:11:14 +0000317 if (Expr == R_PAGE_PC)
318 return R_PLT_PAGE_PC;
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000319 if (Expr == R_ABS)
320 return R_PLT;
321 return Expr;
322}
323
324static RelExpr fromPlt(RelExpr Expr) {
325 // We decided not to use a plt. Optimize a reference to the plt to a
326 // reference to the symbol itself.
327 if (Expr == R_PLT_PC)
328 return R_PC;
329 if (Expr == R_PPC_PLT_OPD)
330 return R_PPC_OPD;
331 if (Expr == R_PLT)
332 return R_ABS;
333 return Expr;
334}
335
336template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
337 typedef typename ELFT::uint uintX_t;
338
339 uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
340 uintX_t SymValue = SS->Sym.st_value;
341 int TrailingZeros =
342 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
343 return 1 << TrailingZeros;
344}
345
346// Reserve space in .bss for copy relocation.
347template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
348 typedef typename ELFT::uint uintX_t;
349 typedef typename ELFT::Sym Elf_Sym;
350
351 // Copy relocation against zero-sized symbol doesn't make sense.
352 uintX_t SymSize = SS->template getSize<ELFT>();
353 if (SymSize == 0)
354 fatal("cannot create a copy relocation for " + SS->getName());
355
356 uintX_t Align = getAlignment(SS);
357 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Align);
358 Out<ELFT>::Bss->setSize(Off + SymSize);
359 Out<ELFT>::Bss->updateAlign(Align);
360 uintX_t Shndx = SS->Sym.st_shndx;
361 uintX_t Value = SS->Sym.st_value;
362 // Look through the DSO's dynamic symbol table for aliases and create a
363 // dynamic symbol for each one. This causes the copy relocation to correctly
364 // interpose any aliases.
365 for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
366 if (S.st_shndx != Shndx || S.st_value != Value)
367 continue;
368 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
369 Symtab<ELFT>::X->find(check(S.getName(SS->File->getStringTable()))));
370 if (!Alias)
371 continue;
372 Alias->OffsetInBss = Off;
373 Alias->NeedsCopyOrPltAddr = true;
374 Alias->symbol()->IsUsedInRegularObj = true;
375 }
376 Out<ELFT>::RelaDyn->addReloc(
377 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
378}
379
380template <class ELFT>
381static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
George Rimar5c33b912016-05-25 14:31:37 +0000382 bool IsWrite, RelExpr Expr, uint32_t Type,
383 const uint8_t *Data, typename ELFT::uint Offset) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000384 if (Target->needsThunk(Type, File, Body))
385 return R_THUNK;
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000386 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000387 if (Body.isGnuIFunc()) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000388 Expr = toPlt(Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000389 } else if (!Preemptible) {
390 if (needsPlt(Expr))
391 Expr = fromPlt(Expr);
George Rimarf10c8292016-06-01 16:45:30 +0000392 if (Expr == R_GOT_PC)
Rafael Espindola5c66b822016-06-04 22:58:54 +0000393 Expr = Target->adjustRelaxExpr(Type, Data + Offset, Expr);
George Rimar5c33b912016-05-25 14:31:37 +0000394 }
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000395
396 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
397 return Expr;
398
399 // This relocation would require the dynamic linker to write a value to read
400 // only memory. We can hack around it if we are producing an executable and
401 // the refered symbol can be preemepted to refer to the executable.
402 if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
403 StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
404 error("relocation " + S + " cannot be used when making a shared "
405 "object; recompile with -fPIC.");
406 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
499 uintX_t Flags = C.getSectionHdr()->sh_flags;
500 bool IsWrite = Flags & SHF_WRITE;
501
502 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
503 Out<ELFT>::RelaDyn->addReloc(Reloc);
504 };
505
506 const elf::ObjectFile<ELFT> &File = *C.getFile();
507 ArrayRef<uint8_t> SectionData = C.getSectionData();
508 const uint8_t *Buf = SectionData.begin();
509 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
510 const RelTy &RI = *I;
511 SymbolBody &Body = File.getRelocTargetSym(RI);
512 uint32_t Type = RI.getType(Config->Mips64EL);
513
514 RelExpr Expr = Target->getRelExpr(Type, Body);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000515 uintX_t Offset = C.getOffset(RI.r_offset);
516 if (Offset == (uintX_t)-1)
517 continue;
518
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000519 bool Preemptible = isPreemptible(Body, Type);
George Rimar5c33b912016-05-25 14:31:37 +0000520 Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf, Offset);
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000521 if (HasError)
522 continue;
523
524 // This relocation does not require got entry, but it is relative to got and
525 // needs it to be created. Here we request for that.
526 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
527 Out<ELFT>::Got->HasGotOffRel = true;
528
529 uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
530
531 if (unsigned Processed =
532 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
533 I += (Processed - 1);
534 continue;
535 }
536
Rafael Espindolae37d13b2016-06-02 19:49:53 +0000537 // Ignore "hint" relocation because it is for optional code optimization.
538 if (Expr == R_HINT)
539 continue;
540
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000541 if (needsPlt(Expr) || Expr == R_THUNK || refersToGotEntry(Expr) ||
Simon Atanasyan9a9a3162016-05-28 04:49:57 +0000542 !isPreemptible(Body, Type)) {
Rui Ueyama0fcdc732016-05-24 20:24:43 +0000543 // If the relocation points to something in the file, we can process it.
544 bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
545
546 // If the output being produced is position independent, the final value
547 // is still not known. In that case we still need some help from the
548 // dynamic linker. We can however do better than just copying the incoming
549 // relocation. We can process some of it and and just ask the dynamic
550 // linker to add the load address.
551 if (!Constant)
552 AddDyn({Target->RelativeRel, C.OutSec, Offset, true, &Body, Addend});
553
554 // If the produced value is a constant, we just remember to write it
555 // when outputting this section. We also have to do it if the format
556 // uses Elf_Rel, since in that case the written value is the addend.
557 if (Constant || !RelTy::IsRela)
558 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
559 } else {
560 // We don't know anything about the finaly symbol. Just ask the dynamic
561 // linker to handle the relocation for us.
562 AddDyn({Target->getDynRel(Type), C.OutSec, Offset, false, &Body, Addend});
563 // MIPS ABI turns using of GOT and dynamic relocations inside out.
564 // While regular ABI uses dynamic relocations to fill up GOT entries
565 // MIPS ABI requires dynamic linker to fills up GOT entries using
566 // specially sorted dynamic symbol table. This affects even dynamic
567 // relocations against symbols which do not require GOT entries
568 // creation explicitly, i.e. do not have any GOT-relocations. So if
569 // a preemptible symbol has a dynamic relocation we anyway have
570 // to create a GOT entry for it.
571 // If a non-preemptible symbol has a dynamic relocation against it,
572 // dynamic linker takes it st_value, adds offset and writes down
573 // result of the dynamic relocation. In case of preemptible symbol
574 // dynamic linker performs symbol resolution, writes the symbol value
575 // to the GOT entry and reads the GOT entry when it needs to perform
576 // a dynamic relocation.
577 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
578 if (Config->EMachine == EM_MIPS && !Body.isInGot())
579 Out<ELFT>::Got->addEntry(Body);
580 continue;
581 }
582
583 if (Expr == R_THUNK)
584 continue;
585
586 // At this point we are done with the relocated position. Some relocations
587 // also require us to create a got or plt entry.
588
589 // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
590 if (needsPlt(Expr)) {
591 if (Body.isInPlt())
592 continue;
593 Out<ELFT>::Plt->addEntry(Body);
594
595 uint32_t Rel;
596 if (Body.isGnuIFunc() && !Preemptible)
597 Rel = Target->IRelativeRel;
598 else
599 Rel = Target->PltRel;
600
601 Out<ELFT>::GotPlt->addEntry(Body);
602 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
603 Body.getGotPltOffset<ELFT>(), !Preemptible,
604 &Body, 0});
605 continue;
606 }
607
608 if (refersToGotEntry(Expr)) {
609 if (Body.isInGot())
610 continue;
611 Out<ELFT>::Got->addEntry(Body);
612
613 if (Config->EMachine == EM_MIPS)
614 // MIPS ABI has special rules to process GOT entries
615 // and doesn't require relocation entries for them.
616 // See "Global Offset Table" in Chapter 5 in the following document
617 // for detailed description:
618 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
619 continue;
620
621 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
622 uint32_t DynType;
623 if (Body.isTls())
624 DynType = Target->TlsGotRel;
625 else if (Preemptible)
626 DynType = Target->GotRel;
627 else
628 DynType = Target->RelativeRel;
629 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
630 !Preemptible, &Body, 0});
631 }
632 continue;
633 }
634 }
635
636 // Scan relocations for necessary thunks.
637 if (Config->EMachine == EM_MIPS)
638 scanRelocsForThunks<ELFT>(File, Rels);
639}
640
641template <class ELFT> void scanRelocations(InputSection<ELFT> &C) {
642 typedef typename ELFT::Shdr Elf_Shdr;
643
644 // Scan all relocations. Each relocation goes through a series
645 // of tests to determine if it needs special treatment, such as
646 // creating GOT, PLT, copy relocations, etc.
647 // Note that relocations for non-alloc sections are directly
648 // processed by InputSection::relocateNative.
649 if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
650 for (const Elf_Shdr *RelSec : C.RelocSections)
651 scanRelocations(C, *RelSec);
652}
653
654template <class ELFT>
655void scanRelocations(InputSectionBase<ELFT> &S,
656 const typename ELFT::Shdr &RelSec) {
657 ELFFile<ELFT> &EObj = S.getFile()->getObj();
658 if (RelSec.sh_type == SHT_RELA)
659 scanRelocs(S, EObj.relas(&RelSec));
660 else
661 scanRelocs(S, EObj.rels(&RelSec));
662}
663
664template void scanRelocations<ELF32LE>(InputSection<ELF32LE> &);
665template void scanRelocations<ELF32BE>(InputSection<ELF32BE> &);
666template void scanRelocations<ELF64LE>(InputSection<ELF64LE> &);
667template void scanRelocations<ELF64BE>(InputSection<ELF64BE> &);
668
669template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
670 const ELF32LE::Shdr &);
671template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
672 const ELF32BE::Shdr &);
673template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
674 const ELF64LE::Shdr &);
675template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
676 const ELF64BE::Shdr &);
677}
678}