xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision 1cb0256a)
1 //===- Symbols.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 #include "Symbols.h"
11 #include "Error.h"
12 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "OutputSections.h"
15 #include "Strings.h"
16 #include "SyntheticSections.h"
17 #include "Target.h"
18 #include "Writer.h"
19 
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Path.h"
22 #include <cstring>
23 
24 using namespace llvm;
25 using namespace llvm::object;
26 using namespace llvm::ELF;
27 
28 using namespace lld;
29 using namespace lld::elf;
30 
31 InputSectionBase *DefinedRegular::NullInputSection;
32 
33 DefinedSynthetic *ElfSym::Etext;
34 DefinedSynthetic *ElfSym::Etext2;
35 DefinedSynthetic *ElfSym::Edata;
36 DefinedSynthetic *ElfSym::Edata2;
37 DefinedSynthetic *ElfSym::End;
38 DefinedSynthetic *ElfSym::End2;
39 DefinedRegular *ElfSym::MipsGpDisp;
40 DefinedRegular *ElfSym::MipsLocalGp;
41 DefinedRegular *ElfSym::MipsGp;
42 
43 template <class ELFT>
44 static typename ELFT::uint getSymVA(const SymbolBody &Body, int64_t &Addend) {
45   typedef typename ELFT::uint uintX_t;
46 
47   switch (Body.kind()) {
48   case SymbolBody::DefinedSyntheticKind: {
49     auto &D = cast<DefinedSynthetic>(Body);
50     const OutputSection *Sec = D.Section;
51     if (!Sec)
52       return D.Value;
53     if (D.Value == uintX_t(-1))
54       return Sec->Addr + Sec->Size;
55     return Sec->Addr + D.Value;
56   }
57   case SymbolBody::DefinedRegularKind: {
58     auto &D = cast<DefinedRegular>(Body);
59     InputSectionBase *IS = D.Section;
60 
61     // According to the ELF spec reference to a local symbol from outside
62     // the group are not allowed. Unfortunately .eh_frame breaks that rule
63     // and must be treated specially. For now we just replace the symbol with
64     // 0.
65     if (IS == &InputSection::Discarded)
66       return 0;
67 
68     // This is an absolute symbol.
69     if (!IS)
70       return D.Value;
71 
72     uintX_t Offset = D.Value;
73 
74     // An object in an SHF_MERGE section might be referenced via a
75     // section symbol (as a hack for reducing the number of local
76     // symbols).
77     // Depending on the addend, the reference via a section symbol
78     // refers to a different object in the merge section.
79     // Since the objects in the merge section are not necessarily
80     // contiguous in the output, the addend can thus affect the final
81     // VA in a non-linear way.
82     // To make this work, we incorporate the addend into the section
83     // offset (and zero out the addend for later processing) so that
84     // we find the right object in the section.
85     if (D.isSection()) {
86       Offset += Addend;
87       Addend = 0;
88     }
89 
90     const OutputSection *OutSec = IS->getOutputSection<ELFT>();
91 
92     // In the typical case, this is actually very simple and boils
93     // down to adding together 3 numbers:
94     // 1. The address of the output section.
95     // 2. The offset of the input section within the output section.
96     // 3. The offset within the input section (this addition happens
97     //    inside InputSection::getOffset).
98     //
99     // If you understand the data structures involved with this next
100     // line (and how they get built), then you have a pretty good
101     // understanding of the linker.
102     uintX_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset<ELFT>(Offset);
103 
104     if (D.isTls() && !Config->Relocatable) {
105       if (!Out::TlsPhdr)
106         fatal(toString(D.File) +
107               " has a STT_TLS symbol but doesn't have a PT_TLS section");
108       return VA - Out::TlsPhdr->p_vaddr;
109     }
110     return VA;
111   }
112   case SymbolBody::DefinedCommonKind:
113     if (!Config->DefineCommon)
114       return 0;
115     return In<ELFT>::Common->OutSec->Addr + In<ELFT>::Common->OutSecOff +
116            cast<DefinedCommon>(Body).Offset;
117   case SymbolBody::SharedKind: {
118     auto &SS = cast<SharedSymbol>(Body);
119     if (SS.NeedsCopy)
120       return SS.Section->OutSec->Addr + SS.Section->OutSecOff;
121     if (SS.NeedsPltAddr)
122       return Body.getPltVA<ELFT>();
123     return 0;
124   }
125   case SymbolBody::UndefinedKind:
126     return 0;
127   case SymbolBody::LazyArchiveKind:
128   case SymbolBody::LazyObjectKind:
129     assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
130     return 0;
131   }
132   llvm_unreachable("invalid symbol kind");
133 }
134 
135 SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
136                        uint8_t Type)
137     : SymbolKind(K), NeedsCopy(false), NeedsPltAddr(false), IsLocal(IsLocal),
138       IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
139       IsInIgot(false), Type(Type), StOther(StOther), Name(Name) {}
140 
141 // Returns true if a symbol can be replaced at load-time by a symbol
142 // with the same name defined in other ELF executable or DSO.
143 bool SymbolBody::isPreemptible() const {
144   if (isLocal())
145     return false;
146 
147   // Shared symbols resolve to the definition in the DSO. The exceptions are
148   // symbols with copy relocations (which resolve to .bss) or preempt plt
149   // entries (which resolve to that plt entry).
150   if (isShared())
151     return !NeedsCopy && !NeedsPltAddr;
152 
153   // That's all that can be preempted in a non-DSO.
154   if (!Config->Shared)
155     return false;
156 
157   // Only symbols that appear in dynsym can be preempted.
158   if (!symbol()->includeInDynsym())
159     return false;
160 
161   // Only default visibility symbols can be preempted.
162   if (symbol()->Visibility != STV_DEFAULT)
163     return false;
164 
165   // -Bsymbolic means that definitions are not preempted.
166   if (Config->Bsymbolic || (Config->BsymbolicFunctions && isFunc()))
167     return !isDefined();
168   return true;
169 }
170 
171 template <class ELFT>
172 typename ELFT::uint SymbolBody::getVA(int64_t Addend) const {
173   typename ELFT::uint OutVA = getSymVA<ELFT>(*this, Addend);
174   return OutVA + Addend;
175 }
176 
177 template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const {
178   return In<ELFT>::Got->getVA() + getGotOffset<ELFT>();
179 }
180 
181 template <class ELFT> typename ELFT::uint SymbolBody::getGotOffset() const {
182   return GotIndex * Target->GotEntrySize;
183 }
184 
185 template <class ELFT> typename ELFT::uint SymbolBody::getGotPltVA() const {
186   if (this->IsInIgot)
187     return In<ELFT>::IgotPlt->getVA() + getGotPltOffset<ELFT>();
188   return In<ELFT>::GotPlt->getVA() + getGotPltOffset<ELFT>();
189 }
190 
191 template <class ELFT> typename ELFT::uint SymbolBody::getGotPltOffset() const {
192   return GotPltIndex * Target->GotPltEntrySize;
193 }
194 
195 template <class ELFT> typename ELFT::uint SymbolBody::getPltVA() const {
196   if (this->IsInIplt)
197     return In<ELFT>::Iplt->getVA() + PltIndex * Target->PltEntrySize;
198   return In<ELFT>::Plt->getVA() + Target->PltHeaderSize +
199          PltIndex * Target->PltEntrySize;
200 }
201 
202 template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
203   if (const auto *C = dyn_cast<DefinedCommon>(this))
204     return C->Size;
205   if (const auto *DR = dyn_cast<DefinedRegular>(this))
206     return DR->Size;
207   if (const auto *S = dyn_cast<SharedSymbol>(this))
208     return S->getSize<ELFT>();
209   return 0;
210 }
211 
212 template <class ELFT>
213 const OutputSection *SymbolBody::getOutputSection() const {
214   if (auto *S = dyn_cast<DefinedRegular>(this)) {
215     if (S->Section)
216       return S->Section->template getOutputSection<ELFT>();
217     return nullptr;
218   }
219 
220   if (auto *S = dyn_cast<SharedSymbol>(this)) {
221     if (S->NeedsCopy)
222       return S->Section->OutSec;
223     return nullptr;
224   }
225 
226   if (isa<DefinedCommon>(this)) {
227     if (Config->DefineCommon)
228       return In<ELFT>::Common->OutSec;
229     return nullptr;
230   }
231 
232   if (auto *S = dyn_cast<DefinedSynthetic>(this))
233     return S->Section;
234   return nullptr;
235 }
236 
237 // If a symbol name contains '@', the characters after that is
238 // a symbol version name. This function parses that.
239 void SymbolBody::parseSymbolVersion() {
240   StringRef S = getName();
241   size_t Pos = S.find('@');
242   if (Pos == 0 || Pos == StringRef::npos)
243     return;
244   StringRef Verstr = S.substr(Pos + 1);
245   if (Verstr.empty())
246     return;
247 
248   // Truncate the symbol name so that it doesn't include the version string.
249   Name = {S.data(), Pos};
250 
251   // If this is not in this DSO, it is not a definition.
252   if (!isInCurrentDSO())
253     return;
254 
255   // '@@' in a symbol name means the default version.
256   // It is usually the most recent one.
257   bool IsDefault = (Verstr[0] == '@');
258   if (IsDefault)
259     Verstr = Verstr.substr(1);
260 
261   for (VersionDefinition &Ver : Config->VersionDefinitions) {
262     if (Ver.Name != Verstr)
263       continue;
264 
265     if (IsDefault)
266       symbol()->VersionId = Ver.Id;
267     else
268       symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
269     return;
270   }
271 
272   // It is an error if the specified version is not defined.
273   error(toString(File) + ": symbol " + S + " has undefined version " + Verstr);
274 }
275 
276 Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
277                  uint8_t Type)
278     : SymbolBody(K, Name, IsLocal, StOther, Type) {}
279 
280 template <class ELFT> bool DefinedRegular::isMipsPIC() const {
281   if (!Section || !isFunc())
282     return false;
283   return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
284          (Section->getFile<ELFT>()->getObj().getHeader()->e_flags &
285           EF_MIPS_PIC);
286 }
287 
288 Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
289                      uint8_t Type, InputFile *File)
290     : SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {
291   this->File = File;
292 }
293 
294 DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint64_t Alignment,
295                              uint8_t StOther, uint8_t Type, InputFile *File)
296     : Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
297               Type),
298       Alignment(Alignment), Size(Size) {
299   this->File = File;
300 }
301 
302 // If a shared symbol is referred via a copy relocation, its alignment
303 // becomes part of the ABI. This function returns a symbol alignment.
304 // Because symbols don't have alignment attributes, we need to infer that.
305 template <class ELFT> uint64_t SharedSymbol::getAlignment() const {
306   auto *File = cast<SharedFile<ELFT>>(this->File);
307   uint64_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
308   uint64_t SymValue = getSym<ELFT>().st_value;
309   uint64_t SymAlign = uint64_t(1) << countTrailingZeros(SymValue);
310   return std::min(SecAlign, SymAlign);
311 }
312 
313 InputFile *Lazy::fetch() {
314   if (auto *S = dyn_cast<LazyArchive>(this))
315     return S->fetch();
316   return cast<LazyObject>(this)->fetch();
317 }
318 
319 LazyArchive::LazyArchive(ArchiveFile &File,
320                          const llvm::object::Archive::Symbol S, uint8_t Type)
321     : Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {
322   this->File = &File;
323 }
324 
325 LazyObject::LazyObject(StringRef Name, LazyObjectFile &File, uint8_t Type)
326     : Lazy(LazyObjectKind, Name, Type) {
327   this->File = &File;
328 }
329 
330 InputFile *LazyArchive::fetch() {
331   std::pair<MemoryBufferRef, uint64_t> MBInfo = file()->getMember(&Sym);
332 
333   // getMember returns an empty buffer if the member was already
334   // read from the library.
335   if (MBInfo.first.getBuffer().empty())
336     return nullptr;
337   return createObjectFile(MBInfo.first, file()->getName(), MBInfo.second);
338 }
339 
340 InputFile *LazyObject::fetch() {
341   MemoryBufferRef MBRef = file()->getBuffer();
342   if (MBRef.getBuffer().empty())
343     return nullptr;
344   return createObjectFile(MBRef);
345 }
346 
347 uint8_t Symbol::computeBinding() const {
348   if (Config->Relocatable)
349     return Binding;
350   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
351     return STB_LOCAL;
352   const SymbolBody *Body = body();
353   if (VersionId == VER_NDX_LOCAL && Body->isInCurrentDSO())
354     return STB_LOCAL;
355   if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
356     return STB_GLOBAL;
357   return Binding;
358 }
359 
360 bool Symbol::includeInDynsym() const {
361   if (computeBinding() == STB_LOCAL)
362     return false;
363   return ExportDynamic || body()->isShared() ||
364          (body()->isUndefined() && Config->Shared);
365 }
366 
367 // Print out a log message for --trace-symbol.
368 void elf::printTraceSymbol(Symbol *Sym) {
369   SymbolBody *B = Sym->body();
370   std::string S;
371   if (B->isUndefined())
372     S = ": reference to ";
373   else if (B->isCommon())
374     S = ": common definition of ";
375   else
376     S = ": definition of ";
377 
378   message(toString(B->File) + S + B->getName());
379 }
380 
381 // Returns a symbol for an error message.
382 std::string lld::toString(const SymbolBody &B) {
383   if (Config->Demangle)
384     if (Optional<std::string> S = demangle(B.getName()))
385       return *S;
386   return B.getName();
387 }
388 
389 template uint32_t SymbolBody::template getVA<ELF32LE>(int64_t) const;
390 template uint32_t SymbolBody::template getVA<ELF32BE>(int64_t) const;
391 template uint64_t SymbolBody::template getVA<ELF64LE>(int64_t) const;
392 template uint64_t SymbolBody::template getVA<ELF64BE>(int64_t) const;
393 
394 template uint32_t SymbolBody::template getGotVA<ELF32LE>() const;
395 template uint32_t SymbolBody::template getGotVA<ELF32BE>() const;
396 template uint64_t SymbolBody::template getGotVA<ELF64LE>() const;
397 template uint64_t SymbolBody::template getGotVA<ELF64BE>() const;
398 
399 template uint32_t SymbolBody::template getGotOffset<ELF32LE>() const;
400 template uint32_t SymbolBody::template getGotOffset<ELF32BE>() const;
401 template uint64_t SymbolBody::template getGotOffset<ELF64LE>() const;
402 template uint64_t SymbolBody::template getGotOffset<ELF64BE>() const;
403 
404 template uint32_t SymbolBody::template getGotPltVA<ELF32LE>() const;
405 template uint32_t SymbolBody::template getGotPltVA<ELF32BE>() const;
406 template uint64_t SymbolBody::template getGotPltVA<ELF64LE>() const;
407 template uint64_t SymbolBody::template getGotPltVA<ELF64BE>() const;
408 
409 template uint32_t SymbolBody::template getGotPltOffset<ELF32LE>() const;
410 template uint32_t SymbolBody::template getGotPltOffset<ELF32BE>() const;
411 template uint64_t SymbolBody::template getGotPltOffset<ELF64LE>() const;
412 template uint64_t SymbolBody::template getGotPltOffset<ELF64BE>() const;
413 
414 template uint32_t SymbolBody::template getPltVA<ELF32LE>() const;
415 template uint32_t SymbolBody::template getPltVA<ELF32BE>() const;
416 template uint64_t SymbolBody::template getPltVA<ELF64LE>() const;
417 template uint64_t SymbolBody::template getPltVA<ELF64BE>() const;
418 
419 template uint32_t SymbolBody::template getSize<ELF32LE>() const;
420 template uint32_t SymbolBody::template getSize<ELF32BE>() const;
421 template uint64_t SymbolBody::template getSize<ELF64LE>() const;
422 template uint64_t SymbolBody::template getSize<ELF64BE>() const;
423 
424 template const OutputSection *
425     SymbolBody::template getOutputSection<ELF32LE>() const;
426 template const OutputSection *
427     SymbolBody::template getOutputSection<ELF32BE>() const;
428 template const OutputSection *
429     SymbolBody::template getOutputSection<ELF64LE>() const;
430 template const OutputSection *
431     SymbolBody::template getOutputSection<ELF64BE>() const;
432 
433 template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
434 template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
435 template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
436 template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
437 
438 template uint64_t SharedSymbol::template getAlignment<ELF32LE>() const;
439 template uint64_t SharedSymbol::template getAlignment<ELF32BE>() const;
440 template uint64_t SharedSymbol::template getAlignment<ELF64LE>() const;
441 template uint64_t SharedSymbol::template getAlignment<ELF64BE>() const;
442