1 //===- 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 process 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 "Memory.h"
47 #include "OutputSections.h"
48 #include "Strings.h"
49 #include "SymbolTable.h"
50 #include "SyntheticSections.h"
51 #include "Target.h"
52 #include "Thunks.h"
53 
54 #include "llvm/Support/Endian.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 
58 using namespace llvm;
59 using namespace llvm::ELF;
60 using namespace llvm::object;
61 using namespace llvm::support::endian;
62 
63 using namespace lld;
64 using namespace lld::elf;
65 
66 // Construct a message in the following format.
67 //
68 // >>> defined in /home/alice/src/foo.o
69 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
70 // >>>               /home/alice/src/bar.o:(.text+0x1)
71 template <class ELFT>
72 static std::string getLocation(InputSectionBase &S, const SymbolBody &Sym,
73                                uint64_t Off) {
74   std::string Msg =
75       "\n>>> defined in " + toString(Sym.File) + "\n>>> referenced by ";
76   std::string Src = S.getSrcMsg<ELFT>(Off);
77   if (!Src.empty())
78     Msg += Src + "\n>>>               ";
79   return Msg + S.getObjMsg<ELFT>(Off);
80 }
81 
82 static bool refersToGotEntry(RelExpr Expr) {
83   return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
84                         R_MIPS_GOT_OFF32, R_MIPS_TLSGD, R_MIPS_TLSLD,
85                         R_GOT_PAGE_PC, R_GOT_PC, R_GOT_FROM_END, R_TLSGD,
86                         R_TLSGD_PC, R_TLSDESC, R_TLSDESC_PAGE>(Expr);
87 }
88 
89 static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
90   // In case of MIPS GP-relative relocations always resolve to a definition
91   // in a regular input file, ignoring the one-definition rule. So we,
92   // for example, should not attempt to create a dynamic relocation even
93   // if the target symbol is preemptible. There are two two MIPS GP-relative
94   // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
95   // can be against a preemptible symbol.
96   // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
97   // relocation types occupy eight bit. In case of N64 ABI we extract first
98   // relocation from 3-in-1 packet because only the first relocation can
99   // be against a real symbol.
100   if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
101     return false;
102   return Body.isPreemptible();
103 }
104 
105 // This function is similar to the `handleTlsRelocation`. ARM and MIPS do not
106 // support any relaxations for TLS relocations so by factoring out ARM and MIPS
107 // handling in to the separate function we can simplify the code and do not
108 // pollute `handleTlsRelocation` by ARM and MIPS `ifs` statements.
109 template <class ELFT, class GOT>
110 static unsigned handleNoRelaxTlsRelocation(GOT *Got, uint32_t Type,
111                                            SymbolBody &Body,
112                                            InputSectionBase &C, uint64_t Offset,
113                                            int64_t Addend, RelExpr Expr) {
114   auto addModuleReloc = [&](uint64_t Off, bool LD) {
115     // The Dynamic TLS Module Index Relocation can be statically resolved to 1
116     // if we know that we are linking an executable. For ARM we resolve the
117     // relocation when writing the Got. MIPS has a custom Got implementation
118     // that writes the Module index in directly.
119     if (!Body.isPreemptible() && !Config->Pic && Config->EMachine == EM_ARM)
120       Got->Relocations.push_back(
121           {R_ABS, Target->TlsModuleIndexRel, Off, 0, &Body});
122     else {
123       SymbolBody *Dest = LD ? nullptr : &Body;
124       In<ELFT>::RelaDyn->addReloc(
125           {Target->TlsModuleIndexRel, Got, Off, false, Dest, 0});
126     }
127   };
128 
129   if (isRelExprOneOf<R_MIPS_TLSLD, R_TLSLD_PC>(Expr)) {
130     if (Got->addTlsIndex() && (Config->Pic || Config->EMachine == EM_ARM))
131       addModuleReloc(Got->getTlsIndexOff(), true);
132     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
133     return 1;
134   }
135 
136   if (Target->isTlsGlobalDynamicRel(Type)) {
137     if (Got->addDynTlsEntry(Body) &&
138         (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
139       uint64_t Off = Got->getGlobalDynOffset(Body);
140       addModuleReloc(Off, false);
141       if (Body.isPreemptible())
142         In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Got,
143                                      Off + Config->Wordsize, false, &Body, 0});
144     }
145     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
146     return 1;
147   }
148 
149   return 0;
150 }
151 
152 // Returns the number of relocations processed.
153 template <class ELFT>
154 static unsigned
155 handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C,
156                     typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
157   if (!(C.Flags & SHF_ALLOC))
158     return 0;
159 
160   if (!Body.isTls())
161     return 0;
162 
163   if (Config->EMachine == EM_ARM)
164     return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::Got, Type, Body, C,
165                                             Offset, Addend, Expr);
166   if (Config->EMachine == EM_MIPS)
167     return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::MipsGot, Type, Body, C,
168                                             Offset, Addend, Expr);
169 
170   bool IsPreemptible = isPreemptible(Body, Type);
171   if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
172       Config->Shared) {
173     if (In<ELFT>::Got->addDynTlsEntry(Body)) {
174       uint64_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
175       In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off,
176                                    !IsPreemptible, &Body, 0});
177     }
178     if (Expr != R_TLSDESC_CALL)
179       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
180     return 1;
181   }
182 
183   if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
184     // Local-Dynamic relocs can be relaxed to Local-Exec.
185     if (!Config->Shared) {
186       C.Relocations.push_back(
187           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
188       return 2;
189     }
190     if (In<ELFT>::Got->addTlsIndex())
191       In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
192                                    In<ELFT>::Got->getTlsIndexOff(), false,
193                                    nullptr, 0});
194     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
195     return 1;
196   }
197 
198   // Local-Dynamic relocs can be relaxed to Local-Exec.
199   if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
200     C.Relocations.push_back(
201         {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
202     return 1;
203   }
204 
205   if (isRelExprOneOf<R_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL>(Expr) ||
206       Target->isTlsGlobalDynamicRel(Type)) {
207     if (Config->Shared) {
208       if (In<ELFT>::Got->addDynTlsEntry(Body)) {
209         uint64_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
210         In<ELFT>::RelaDyn->addReloc(
211             {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
212 
213         // If the symbol is preemptible we need the dynamic linker to write
214         // the offset too.
215         uint64_t OffsetOff = Off + Config->Wordsize;
216         if (IsPreemptible)
217           In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
218                                        OffsetOff, false, &Body, 0});
219         else
220           In<ELFT>::Got->Relocations.push_back(
221               {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
222       }
223       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
224       return 1;
225     }
226 
227     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
228     // depending on the symbol being locally defined or not.
229     if (IsPreemptible) {
230       C.Relocations.push_back(
231           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
232            Offset, Addend, &Body});
233       if (!Body.isInGot()) {
234         In<ELFT>::Got->addEntry(Body);
235         In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got,
236                                      Body.getGotOffset(), false, &Body, 0});
237       }
238     } else {
239       C.Relocations.push_back(
240           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
241                 Offset, Addend, &Body});
242     }
243     return Target->TlsGdRelaxSkip;
244   }
245 
246   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
247   // defined.
248   if (Target->isTlsInitialExecRel(Type) && !Config->Shared && !IsPreemptible) {
249     C.Relocations.push_back(
250         {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
251     return 1;
252   }
253   return 0;
254 }
255 
256 static uint32_t getMipsPairType(uint32_t Type, const SymbolBody &Sym) {
257   switch (Type) {
258   case R_MIPS_HI16:
259     return R_MIPS_LO16;
260   case R_MIPS_GOT16:
261     return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
262   case R_MIPS_PCHI16:
263     return R_MIPS_PCLO16;
264   case R_MICROMIPS_HI16:
265     return R_MICROMIPS_LO16;
266   default:
267     return R_MIPS_NONE;
268   }
269 }
270 
271 // True if non-preemptable symbol always has the same value regardless of where
272 // the DSO is loaded.
273 static bool isAbsolute(const SymbolBody &Body) {
274   if (Body.isUndefined())
275     return !Body.isLocal() && Body.symbol()->isWeak();
276   if (const auto *DR = dyn_cast<DefinedRegular>(&Body))
277     return DR->Section == nullptr; // Absolute symbol.
278   return false;
279 }
280 
281 static bool isAbsoluteValue(const SymbolBody &Body) {
282   return isAbsolute(Body) || Body.isTls();
283 }
284 
285 static bool needsPlt(RelExpr Expr) {
286   return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
287 }
288 
289 // True if this expression is of the form Sym - X, where X is a position in the
290 // file (PC, or GOT for example).
291 static bool isRelExpr(RelExpr Expr) {
292   return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
293                         R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
294 }
295 
296 // Returns true if a given relocation can be computed at link-time.
297 //
298 // For instance, we know the offset from a relocation to its target at
299 // link-time if the relocation is PC-relative and refers a
300 // non-interposable function in the same executable. This function
301 // will return true for such relocation.
302 //
303 // If this function returns false, that means we need to emit a
304 // dynamic relocation so that the relocation will be fixed at load-time.
305 template <class ELFT>
306 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
307                                      const SymbolBody &Body,
308                                      InputSectionBase &S, uint64_t RelOff) {
309   // These expressions always compute a constant
310   if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
311                      R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
312                      R_MIPS_TLSGD, R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC,
313                      R_TLSGD_PC, R_TLSGD, R_PPC_PLT_OPD, R_TLSDESC_CALL,
314                      R_TLSDESC_PAGE, R_HINT>(E))
315     return true;
316 
317   // These never do, except if the entire file is position dependent or if
318   // only the low bits are used.
319   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
320     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
321 
322   if (isPreemptible(Body, Type))
323     return false;
324   if (!Config->Pic)
325     return true;
326 
327   // For the target and the relocation, we want to know if they are
328   // absolute or relative.
329   bool AbsVal = isAbsoluteValue(Body);
330   bool RelE = isRelExpr(E);
331   if (AbsVal && !RelE)
332     return true;
333   if (!AbsVal && RelE)
334     return true;
335   if (!AbsVal && !RelE)
336     return Target->usesOnlyLowPageBits(Type);
337 
338   // Relative relocation to an absolute value. This is normally unrepresentable,
339   // but if the relocation refers to a weak undefined symbol, we allow it to
340   // resolve to the image base. This is a little strange, but it allows us to
341   // link function calls to such symbols. Normally such a call will be guarded
342   // with a comparison, which will load a zero from the GOT.
343   // Another special case is MIPS _gp_disp symbol which represents offset
344   // between start of a function and '_gp' value and defined as absolute just
345   // to simplify the code.
346   assert(AbsVal && RelE);
347   if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
348     return true;
349 
350   error("relocation " + toString(Type) + " cannot refer to absolute symbol: " +
351         toString(Body) + getLocation<ELFT>(S, Body, RelOff));
352   return true;
353 }
354 
355 static RelExpr toPlt(RelExpr Expr) {
356   if (Expr == R_PPC_OPD)
357     return R_PPC_PLT_OPD;
358   if (Expr == R_PC)
359     return R_PLT_PC;
360   if (Expr == R_PAGE_PC)
361     return R_PLT_PAGE_PC;
362   if (Expr == R_ABS)
363     return R_PLT;
364   return Expr;
365 }
366 
367 static RelExpr fromPlt(RelExpr Expr) {
368   // We decided not to use a plt. Optimize a reference to the plt to a
369   // reference to the symbol itself.
370   if (Expr == R_PLT_PC)
371     return R_PC;
372   if (Expr == R_PPC_PLT_OPD)
373     return R_PPC_OPD;
374   if (Expr == R_PLT)
375     return R_ABS;
376   return Expr;
377 }
378 
379 // Returns true if a given shared symbol is in a read-only segment in a DSO.
380 template <class ELFT> static bool isReadOnly(SharedSymbol *SS) {
381   typedef typename ELFT::Phdr Elf_Phdr;
382   uint64_t Value = SS->getValue<ELFT>();
383 
384   // Determine if the symbol is read-only by scanning the DSO's program headers.
385   auto *File = cast<SharedFile<ELFT>>(SS->File);
386   for (const Elf_Phdr &Phdr : check(File->getObj().program_headers()))
387     if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
388         !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
389         Value < Phdr.p_vaddr + Phdr.p_memsz)
390       return true;
391   return false;
392 }
393 
394 // Returns symbols at the same offset as a given symbol, including SS itself.
395 //
396 // If two or more symbols are at the same offset, and at least one of
397 // them are copied by a copy relocation, all of them need to be copied.
398 // Otherwise, they would refer different places at runtime.
399 template <class ELFT>
400 static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol *SS) {
401   typedef typename ELFT::Sym Elf_Sym;
402 
403   auto *File = cast<SharedFile<ELFT>>(SS->File);
404   uint64_t Shndx = SS->getShndx<ELFT>();
405   uint64_t Value = SS->getValue<ELFT>();
406 
407   std::vector<SharedSymbol *> Ret;
408   for (const Elf_Sym &S : File->getGlobalSymbols()) {
409     if (S.st_shndx != Shndx || S.st_value != Value)
410       continue;
411     StringRef Name = check(S.getName(File->getStringTable()));
412     SymbolBody *Sym = Symtab<ELFT>::X->find(Name);
413     if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
414       Ret.push_back(Alias);
415   }
416   return Ret;
417 }
418 
419 // Reserve space in .bss or .bss.rel.ro for copy relocation.
420 //
421 // The copy relocation is pretty much a hack. If you use a copy relocation
422 // in your program, not only the symbol name but the symbol's size, RW/RO
423 // bit and alignment become part of the ABI. In addition to that, if the
424 // symbol has aliases, the aliases become part of the ABI. That's subtle,
425 // but if you violate that implicit ABI, that can cause very counter-
426 // intuitive consequences.
427 //
428 // So, what is the copy relocation? It's for linking non-position
429 // independent code to DSOs. In an ideal world, all references to data
430 // exported by DSOs should go indirectly through GOT. But if object files
431 // are compiled as non-PIC, all data references are direct. There is no
432 // way for the linker to transform the code to use GOT, as machine
433 // instructions are already set in stone in object files. This is where
434 // the copy relocation takes a role.
435 //
436 // A copy relocation instructs the dynamic linker to copy data from a DSO
437 // to a specified address (which is usually in .bss) at load-time. If the
438 // static linker (that's us) finds a direct data reference to a DSO
439 // symbol, it creates a copy relocation, so that the symbol can be
440 // resolved as if it were in .bss rather than in a DSO.
441 //
442 // As you can see in this function, we create a copy relocation for the
443 // dynamic linker, and the relocation contains not only symbol name but
444 // various other informtion about the symbol. So, such attributes become a
445 // part of the ABI.
446 //
447 // Note for application developers: I can give you a piece of advice if
448 // you are writing a shared library. You probably should export only
449 // functions from your library. You shouldn't export variables.
450 //
451 // As an example what can happen when you export variables without knowing
452 // the semantics of copy relocations, assume that you have an exported
453 // variable of type T. It is an ABI-breaking change to add new members at
454 // end of T even though doing that doesn't change the layout of the
455 // existing members. That's because the space for the new members are not
456 // reserved in .bss unless you recompile the main program. That means they
457 // are likely to overlap with other data that happens to be laid out next
458 // to the variable in .bss. This kind of issue is sometimes very hard to
459 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
460 // define an accessor getV().
461 template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) {
462   // Copy relocation against zero-sized symbol doesn't make sense.
463   uint64_t SymSize = SS->template getSize<ELFT>();
464   if (SymSize == 0)
465     fatal("cannot create a copy relocation for symbol " + toString(*SS));
466 
467   // See if this symbol is in a read-only segment. If so, preserve the symbol's
468   // memory protection by reserving space in the .bss.rel.ro section.
469   bool IsReadOnly = isReadOnly<ELFT>(SS);
470   BssSection *Sec = IsReadOnly ? In<ELFT>::BssRelRo : In<ELFT>::Bss;
471   uint64_t Off = Sec->reserveSpace(SymSize, SS->getAlignment<ELFT>());
472 
473   // Look through the DSO's dynamic symbol table for aliases and create a
474   // dynamic symbol for each one. This causes the copy relocation to correctly
475   // interpose any aliases.
476   for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) {
477     Sym->NeedsCopy = true;
478     Sym->CopyRelSec = Sec;
479     Sym->CopyRelSecOff = Off;
480     Sym->symbol()->IsUsedInRegularObj = true;
481   }
482 
483   In<ELFT>::RelaDyn->addReloc({Target->CopyRel, Sec, Off, false, SS, 0});
484 }
485 
486 template <class ELFT>
487 static RelExpr adjustExpr(SymbolBody &Body, RelExpr Expr, uint32_t Type,
488                           const uint8_t *Data, InputSectionBase &S,
489                           typename ELFT::uint RelOff) {
490   if (Body.isGnuIFunc()) {
491     Expr = toPlt(Expr);
492   } else if (!isPreemptible(Body, Type)) {
493     if (needsPlt(Expr))
494       Expr = fromPlt(Expr);
495     if (Expr == R_GOT_PC && !isAbsoluteValue(Body))
496       Expr = Target->adjustRelaxExpr(Type, Data, Expr);
497   }
498 
499   bool IsWrite = !Config->ZText || (S.Flags & SHF_WRITE);
500   if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
501     return Expr;
502 
503   // This relocation would require the dynamic linker to write a value to read
504   // only memory. We can hack around it if we are producing an executable and
505   // the refered symbol can be preemepted to refer to the executable.
506   if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
507     error("can't create dynamic relocation " + toString(Type) + " against " +
508           (Body.getName().empty() ? "local symbol in readonly segment"
509                                   : "symbol: " + toString(Body)) +
510           getLocation<ELFT>(S, Body, RelOff));
511     return Expr;
512   }
513 
514   if (Body.getVisibility() != STV_DEFAULT) {
515     error("cannot preempt symbol: " + toString(Body) +
516           getLocation<ELFT>(S, Body, RelOff));
517     return Expr;
518   }
519 
520   if (Body.isObject()) {
521     // Produce a copy relocation.
522     auto *B = cast<SharedSymbol>(&Body);
523     if (!B->NeedsCopy) {
524       if (Config->ZNocopyreloc)
525         error("unresolvable relocation " + toString(Type) +
526               " against symbol '" + toString(*B) +
527               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
528               getLocation<ELFT>(S, Body, RelOff));
529 
530       addCopyRelSymbol<ELFT>(B);
531     }
532     return Expr;
533   }
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).
556     Body.NeedsPltAddr = true;
557     return toPlt(Expr);
558   }
559 
560   error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) +
561         " has no type");
562   return Expr;
563 }
564 
565 // Returns an addend of a given relocation. If it is RELA, an addend
566 // is in a relocation itself. If it is REL, we need to read it from an
567 // input section.
568 template <class ELFT, class RelTy>
569 static int64_t computeAddend(const RelTy &Rel, const uint8_t *Buf) {
570   uint32_t Type = Rel.getType(Config->IsMips64EL);
571   int64_t A = RelTy::IsRela
572                   ? getAddend<ELFT>(Rel)
573                   : Target->getImplicitAddend(Buf + Rel.r_offset, Type);
574 
575   if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
576     A += getPPC64TocBase();
577   return A;
578 }
579 
580 // MIPS has an odd notion of "paired" relocations to calculate addends.
581 // For example, if a relocation is of R_MIPS_HI16, there must be a
582 // R_MIPS_LO16 relocation after that, and an addend is calculated using
583 // the two relocations.
584 template <class ELFT, class RelTy>
585 static int64_t computeMipsAddend(const RelTy &Rel, InputSectionBase &Sec,
586                                  RelExpr Expr, SymbolBody &Body,
587                                  const RelTy *End) {
588   if (Expr == R_MIPS_GOTREL && Body.isLocal())
589     return Sec.getFile<ELFT>()->MipsGp0;
590 
591   // The ABI says that the paired relocation is used only for REL.
592   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
593   if (RelTy::IsRela)
594     return 0;
595 
596   uint32_t Type = Rel.getType(Config->IsMips64EL);
597   uint32_t PairTy = getMipsPairType(Type, Body);
598   if (PairTy == R_MIPS_NONE)
599     return 0;
600 
601   const uint8_t *Buf = Sec.Data.data();
602   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
603 
604   // To make things worse, paired relocations might not be contiguous in
605   // the relocation table, so we need to do linear search. *sigh*
606   for (const RelTy *RI = &Rel; RI != End; ++RI) {
607     if (RI->getType(Config->IsMips64EL) != PairTy)
608       continue;
609     if (RI->getSymbol(Config->IsMips64EL) != SymIndex)
610       continue;
611 
612     endianness E = Config->Endianness;
613     int32_t Hi = (read32(Buf + Rel.r_offset, E) & 0xffff) << 16;
614     int32_t Lo = SignExtend32<16>(read32(Buf + RI->r_offset, E));
615     return Hi + Lo;
616   }
617 
618   warn("can't find matching " + toString(PairTy) + " relocation for " +
619        toString(Type));
620   return 0;
621 }
622 
623 template <class ELFT>
624 static void reportUndefined(SymbolBody &Sym, InputSectionBase &S,
625                             uint64_t Offset) {
626   if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll)
627     return;
628 
629   bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
630                        Sym.getVisibility() == STV_DEFAULT;
631   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
632     return;
633 
634   std::string Msg =
635       "undefined symbol: " + toString(Sym) + "\n>>> referenced by ";
636 
637   std::string Src = S.getSrcMsg<ELFT>(Offset);
638   if (!Src.empty())
639     Msg += Src + "\n>>>               ";
640   Msg += S.getObjMsg<ELFT>(Offset);
641 
642   if (Config->UnresolvedSymbols == UnresolvedPolicy::WarnAll ||
643       (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal)) {
644     warn(Msg);
645   } else {
646     error(Msg);
647 
648     if (Config->ArchiveWithoutSymbolsSeen) {
649       message("At least one archive listed no symbols in its index."
650               " This can happen when creating archives with a version"
651               " of ar that does not understand the object files in"
652               " the archive. For example, if you are using LLVM"
653               " bitcode objects (such as created by -flto), you may"
654               " need to use llvm-ar or GNU ar with a plugin.");
655       // Reset to false so that we print the message only once.
656       Config->ArchiveWithoutSymbolsSeen = false;
657     }
658   }
659 }
660 
661 template <class RelTy>
662 static std::pair<uint32_t, uint32_t>
663 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
664   // MIPS N32 ABI treats series of successive relocations with the same offset
665   // as a single relocation. The similar approach used by N64 ABI, but this ABI
666   // packs all relocations into the single relocation record. Here we emulate
667   // this for the N32 ABI. Iterate over relocation with the same offset and put
668   // theirs types into the single bit-set.
669   uint32_t Processed = 0;
670   for (; I != E && Offset == I->r_offset; ++I) {
671     ++Processed;
672     Type |= I->getType(Config->IsMips64EL) << (8 * Processed);
673   }
674   return std::make_pair(Type, Processed);
675 }
676 
677 // .eh_frame sections are mergeable input sections, so their input
678 // offsets are not linearly mapped to output section. For each input
679 // offset, we need to find a section piece containing the offset and
680 // add the piece's base address to the input offset to compute the
681 // output offset. That isn't cheap.
682 //
683 // This class is to speed up the offset computation. When we process
684 // relocations, we access offsets in the monotonically increasing
685 // order. So we can optimize for that access pattern.
686 //
687 // For sections other than .eh_frame, this class doesn't do anything.
688 namespace {
689 class OffsetGetter {
690 public:
691   explicit OffsetGetter(InputSectionBase &Sec) {
692     if (auto *Eh = dyn_cast<EhInputSection>(&Sec)) {
693       P = Eh->Pieces;
694       Size = Eh->Pieces.size();
695     }
696   }
697 
698   // Translates offsets in input sections to offsets in output sections.
699   // Given offset must increase monotonically. We assume that P is
700   // sorted by InputOff.
701   uint64_t get(uint64_t Off) {
702     if (P.empty())
703       return Off;
704 
705     while (I != Size && P[I].InputOff + P[I].size() <= Off)
706       ++I;
707     if (I == Size)
708       return Off;
709 
710     // P must be contiguous, so there must be no holes in between.
711     assert(P[I].InputOff <= Off && "Relocation not in any piece");
712 
713     // Offset -1 means that the piece is dead (i.e. garbage collected).
714     if (P[I].OutputOff == -1)
715       return -1;
716     return P[I].OutputOff + Off - P[I].InputOff;
717   }
718 
719 private:
720   ArrayRef<EhSectionPiece> P;
721   size_t I = 0;
722   size_t Size;
723 };
724 } // namespace
725 
726 template <class ELFT, class GotPltSection>
727 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
728                         RelocationSection<ELFT> *Rel, uint32_t Type,
729                         SymbolBody &Sym, bool UseSymVA) {
730   Plt->addEntry<ELFT>(Sym);
731   GotPlt->addEntry(Sym);
732   Rel->addReloc({Type, GotPlt, Sym.getGotPltOffset(), UseSymVA, &Sym, 0});
733 }
734 
735 template <class ELFT>
736 static void addGotEntry(SymbolBody &Sym, bool Preemptible) {
737   In<ELFT>::Got->addEntry(Sym);
738 
739   uint64_t Off = Sym.getGotOffset();
740   uint32_t DynType;
741   RelExpr Expr = R_ABS;
742 
743   if (Sym.isTls()) {
744     DynType = Target->TlsGotRel;
745     Expr = R_TLS;
746   } else if (!Preemptible && Config->Pic && !isAbsolute(Sym)) {
747     DynType = Target->RelativeRel;
748   } else {
749     DynType = Target->GotRel;
750   }
751 
752   bool Constant = !Preemptible && !(Config->Pic && !isAbsolute(Sym));
753   if (!Constant)
754     In<ELFT>::RelaDyn->addReloc(
755         {DynType, In<ELFT>::Got, Off, !Preemptible, &Sym, 0});
756 
757   if (Constant || (!Config->IsRela && !Preemptible))
758     In<ELFT>::Got->Relocations.push_back({Expr, DynType, Off, 0, &Sym});
759 }
760 
761 // The reason we have to do this early scan is as follows
762 // * To mmap the output file, we need to know the size
763 // * For that, we need to know how many dynamic relocs we will have.
764 // It might be possible to avoid this by outputting the file with write:
765 // * Write the allocated output sections, computing addresses.
766 // * Apply relocations, recording which ones require a dynamic reloc.
767 // * Write the dynamic relocations.
768 // * Write the rest of the file.
769 // This would have some drawbacks. For example, we would only know if .rela.dyn
770 // is needed after applying relocations. If it is, it will go after rw and rx
771 // sections. Given that it is ro, we will need an extra PT_LOAD. This
772 // complicates things for the dynamic linker and means we would have to reserve
773 // space for the extra PT_LOAD even if we end up not using it.
774 template <class ELFT, class RelTy>
775 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
776   OffsetGetter GetOffset(Sec);
777 
778   for (auto I = Rels.begin(), End = Rels.end(); I != End; ++I) {
779     const RelTy &Rel = *I;
780     SymbolBody &Body = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
781     uint32_t Type = Rel.getType(Config->IsMips64EL);
782 
783     if (Config->MipsN32Abi) {
784       uint32_t Processed;
785       std::tie(Type, Processed) =
786           mergeMipsN32RelTypes(Type, Rel.r_offset, I + 1, End);
787       I += Processed;
788     }
789 
790     // Compute the offset of this section in the output section.
791     uint64_t Offset = GetOffset.get(Rel.r_offset);
792     if (Offset == uint64_t(-1))
793       continue;
794 
795     // Report undefined symbols. The fact that we report undefined
796     // symbols here means that we report undefined symbols only when
797     // they have relocations pointing to them. We don't care about
798     // undefined symbols that are in dead-stripped sections.
799     if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
800       reportUndefined<ELFT>(Body, Sec, Rel.r_offset);
801 
802     RelExpr Expr = Target->getRelExpr(Type, Body);
803 
804     // Ignore "hint" relocations because they are only markers for relaxation.
805     if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
806       continue;
807 
808     bool Preemptible = isPreemptible(Body, Type);
809     Expr = adjustExpr<ELFT>(Body, Expr, Type, Sec.Data.data() + Rel.r_offset,
810                             Sec, Rel.r_offset);
811     if (ErrorCount)
812       continue;
813 
814     // This relocation does not require got entry, but it is relative to got and
815     // needs it to be created. Here we request for that.
816     if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
817                        R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
818       In<ELFT>::Got->HasGotOffRel = true;
819 
820     int64_t Addend = computeAddend<ELFT>(Rel, Sec.Data.data());
821     if (Config->EMachine == EM_MIPS)
822       Addend += computeMipsAddend<ELFT>(Rel, Sec, Expr, Body, End);
823 
824     if (unsigned Processed =
825             handleTlsRelocation<ELFT>(Type, Body, Sec, Offset, Addend, Expr)) {
826       I += (Processed - 1);
827       continue;
828     }
829 
830     if (Expr == R_TLSDESC_CALL)
831       continue;
832 
833     if (!needsPlt(Expr) && !refersToGotEntry(Expr) &&
834         isPreemptible(Body, Type)) {
835       // We don't know anything about the finaly symbol. Just ask the dynamic
836       // linker to handle the relocation for us.
837       if (!Target->isPicRel(Type))
838         error("relocation " + toString(Type) +
839               " cannot be used against shared object; recompile with -fPIC" +
840               getLocation<ELFT>(Sec, Body, Offset));
841 
842       In<ELFT>::RelaDyn->addReloc(
843           {Target->getDynRel(Type), &Sec, Offset, false, &Body, Addend});
844 
845       // MIPS ABI turns using of GOT and dynamic relocations inside out.
846       // While regular ABI uses dynamic relocations to fill up GOT entries
847       // MIPS ABI requires dynamic linker to fills up GOT entries using
848       // specially sorted dynamic symbol table. This affects even dynamic
849       // relocations against symbols which do not require GOT entries
850       // creation explicitly, i.e. do not have any GOT-relocations. So if
851       // a preemptible symbol has a dynamic relocation we anyway have
852       // to create a GOT entry for it.
853       // If a non-preemptible symbol has a dynamic relocation against it,
854       // dynamic linker takes it st_value, adds offset and writes down
855       // result of the dynamic relocation. In case of preemptible symbol
856       // dynamic linker performs symbol resolution, writes the symbol value
857       // to the GOT entry and reads the GOT entry when it needs to perform
858       // a dynamic relocation.
859       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
860       if (Config->EMachine == EM_MIPS)
861         In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
862       continue;
863     }
864 
865     // If the relocation points to something in the file, we can process it.
866     bool Constant =
867         isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, Sec, Rel.r_offset);
868 
869     // If the output being produced is position independent, the final value
870     // is still not known. In that case we still need some help from the
871     // dynamic linker. We can however do better than just copying the incoming
872     // relocation. We can process some of it and and just ask the dynamic
873     // linker to add the load address.
874     if (!Constant)
875       In<ELFT>::RelaDyn->addReloc(
876           {Target->RelativeRel, &Sec, Offset, true, &Body, Addend});
877 
878     // If the produced value is a constant, we just remember to write it
879     // when outputting this section. We also have to do it if the format
880     // uses Elf_Rel, since in that case the written value is the addend.
881     if (Constant || !RelTy::IsRela)
882       Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
883 
884     // At this point we are done with the relocated position. Some relocations
885     // also require us to create a got or plt entry.
886 
887     // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
888     if (needsPlt(Expr)) {
889       if (Body.isInPlt())
890         continue;
891 
892       if (Body.isGnuIFunc() && !Preemptible)
893         addPltEntry(InX::Iplt, In<ELFT>::IgotPlt, In<ELFT>::RelaIplt,
894                     Target->IRelativeRel, Body, true);
895       else
896         addPltEntry(InX::Plt, In<ELFT>::GotPlt, In<ELFT>::RelaPlt,
897                     Target->PltRel, Body, !Preemptible);
898       continue;
899     }
900 
901     if (refersToGotEntry(Expr)) {
902       if (Config->EMachine == EM_MIPS) {
903         // MIPS ABI has special rules to process GOT entries and doesn't
904         // require relocation entries for them. A special case is TLS
905         // relocations. In that case dynamic loader applies dynamic
906         // relocations to initialize TLS GOT entries.
907         // See "Global Offset Table" in Chapter 5 in the following document
908         // for detailed description:
909         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
910         In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
911         if (Body.isTls() && Body.isPreemptible())
912           In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::MipsGot,
913                                        Body.getGotOffset(), false, &Body, 0});
914         continue;
915       }
916 
917       if (!Body.isInGot())
918         addGotEntry<ELFT>(Body, Preemptible);
919       continue;
920     }
921   }
922 }
923 
924 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
925   if (S.AreRelocsRela)
926     scanRelocs<ELFT>(S, S.relas<ELFT>());
927   else
928     scanRelocs<ELFT>(S, S.rels<ELFT>());
929 }
930 
931 // Insert the Thunks for OutputSection OS into their designated place
932 // in the Sections vector, and recalculate the InputSection output section
933 // offsets.
934 // This may invalidate any output section offsets stored outside of InputSection
935 static void mergeThunks(OutputSection *OS,
936                         std::vector<ThunkSection *> &Thunks) {
937   // Order Thunks in ascending OutSecOff
938   auto ThunkCmp = [](const ThunkSection *A, const ThunkSection *B) {
939     return A->OutSecOff < B->OutSecOff;
940   };
941   std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
942 
943   // Merge sorted vectors of Thunks and InputSections by OutSecOff
944   std::vector<InputSection *> Tmp;
945   Tmp.reserve(OS->Sections.size() + Thunks.size());
946   auto MergeCmp = [](const InputSection *A, const InputSection *B) {
947     // std::merge requires a strict weak ordering.
948     if (A->OutSecOff < B->OutSecOff)
949       return true;
950     if (A->OutSecOff == B->OutSecOff)
951       // Check if Thunk is immediately before any specific Target InputSection
952       // for example Mips LA25 Thunks.
953       if (auto *TA = dyn_cast<ThunkSection>(A))
954         if (TA && TA->getTargetInputSection() == B)
955           return true;
956     return false;
957   };
958   std::merge(OS->Sections.begin(), OS->Sections.end(), Thunks.begin(),
959              Thunks.end(), std::back_inserter(Tmp), MergeCmp);
960   OS->Sections = std::move(Tmp);
961   OS->assignOffsets();
962 }
963 
964 // Process all relocations from the InputSections that have been assigned
965 // to OutputSections and redirect through Thunks if needed.
966 //
967 // createThunks must be called after scanRelocs has created the Relocations for
968 // each InputSection. It must be called before the static symbol table is
969 // finalized. If any Thunks are added to an OutputSection the output section
970 // offsets of the InputSections will change.
971 //
972 // FIXME: All Thunks are assumed to be in range of the relocation. Range
973 // extension Thunks are not yet supported.
974 template <class ELFT>
975 bool elf::createThunks(ArrayRef<OutputSection *> OutputSections) {
976   // Track Symbols that already have a Thunk
977   DenseMap<SymbolBody *, Thunk *> ThunkedSymbols;
978   // Track InputSections that have a ThunkSection placed in front
979   DenseMap<InputSection *, ThunkSection *> ThunkedSections;
980   // Track the ThunksSections that need to be inserted into an OutputSection
981   std::map<OutputSection *, std::vector<ThunkSection *>> ThunkSections;
982 
983   // Find or create a Thunk for Body for relocation Type
984   auto GetThunk = [&](SymbolBody &Body, uint32_t Type) {
985     auto res = ThunkedSymbols.insert({&Body, nullptr});
986     if (res.second == true)
987       res.first->second = addThunk<ELFT>(Type, Body);
988     return std::make_pair(res.first->second, res.second);
989   };
990 
991   // Find or create a ThunkSection to be placed immediately before IS
992   auto GetISThunkSec = [&](InputSection *IS, OutputSection *OS) {
993     ThunkSection *TS = ThunkedSections.lookup(IS);
994     if (TS)
995       return TS;
996     auto *TOS = cast<OutputSection>(IS->OutSec);
997     TS = make<ThunkSection>(TOS, IS->OutSecOff);
998     ThunkSections[TOS].push_back(TS);
999     ThunkedSections[IS] = TS;
1000     return TS;
1001   };
1002   // Find or create a ThunkSection to be placed as last executable section in
1003   // OS.
1004   auto GetOSThunkSec = [&](ThunkSection *&TS, OutputSection *OS) {
1005     if (TS == nullptr) {
1006       uint32_t Off = 0;
1007       for (auto *IS : OS->Sections) {
1008         Off = IS->OutSecOff + IS->getSize();
1009         if ((IS->Flags & SHF_EXECINSTR) == 0)
1010           break;
1011       }
1012       TS = make<ThunkSection>(OS, Off);
1013       ThunkSections[OS].push_back(TS);
1014     }
1015     return TS;
1016   };
1017   // Create all the Thunks and insert them into synthetic ThunkSections. The
1018   // ThunkSections are later inserted back into the OutputSection.
1019 
1020   // We separate the creation of ThunkSections from the insertion of the
1021   // ThunkSections back into the OutputSection as ThunkSections are not always
1022   // inserted into the same OutputSection as the caller.
1023   for (OutputSection *OS : OutputSections) {
1024     ThunkSection *OSTS = nullptr;
1025     for (InputSection *IS : OS->Sections) {
1026       for (Relocation &Rel : IS->Relocations) {
1027         SymbolBody &Body = *Rel.Sym;
1028         if (Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Body)) {
1029           Thunk *T;
1030           bool IsNew;
1031           std::tie(T, IsNew) = GetThunk(Body, Rel.Type);
1032           if (IsNew) {
1033             // Find or create a ThunkSection for the new Thunk
1034             ThunkSection *TS;
1035             if (auto *TIS = T->getTargetInputSection())
1036               TS = GetISThunkSec(TIS, OS);
1037             else
1038               TS = GetOSThunkSec(OSTS, OS);
1039             TS->addThunk(T);
1040           }
1041           // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1042           Rel.Sym = T->ThunkSym;
1043           Rel.Expr = fromPlt(Rel.Expr);
1044         }
1045       }
1046     }
1047   }
1048 
1049   // Merge all created synthetic ThunkSections back into OutputSection
1050   for (auto &KV : ThunkSections)
1051     mergeThunks(KV.first, KV.second);
1052   return !ThunkSections.empty();
1053 }
1054 
1055 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1056 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1057 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1058 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1059 
1060 template bool elf::createThunks<ELF32LE>(ArrayRef<OutputSection *>);
1061 template bool elf::createThunks<ELF32BE>(ArrayRef<OutputSection *>);
1062 template bool elf::createThunks<ELF64LE>(ArrayRef<OutputSection *>);
1063 template bool elf::createThunks<ELF64BE>(ArrayRef<OutputSection *>);
1064