xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision f5ca27cc)
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 DefinedRegular *ElfSym::Bss;
32 DefinedRegular *ElfSym::Etext1;
33 DefinedRegular *ElfSym::Etext2;
34 DefinedRegular *ElfSym::Edata1;
35 DefinedRegular *ElfSym::Edata2;
36 DefinedRegular *ElfSym::End1;
37 DefinedRegular *ElfSym::End2;
38 DefinedRegular *ElfSym::GlobalOffsetTable;
39 DefinedRegular *ElfSym::MipsGp;
40 DefinedRegular *ElfSym::MipsGpDisp;
41 DefinedRegular *ElfSym::MipsLocalGp;
42 
43 static uint64_t getSymVA(const SymbolBody &Body, int64_t &Addend) {
44   switch (Body.kind()) {
45   case SymbolBody::DefinedRegularKind: {
46     auto &D = cast<DefinedRegular>(Body);
47     SectionBase *IS = D.Section;
48     if (auto *ISB = dyn_cast_or_null<InputSectionBase>(IS))
49       IS = ISB->Repl;
50 
51     // According to the ELF spec reference to a local symbol from outside
52     // the group are not allowed. Unfortunately .eh_frame breaks that rule
53     // and must be treated specially. For now we just replace the symbol with
54     // 0.
55     if (IS == &InputSection::Discarded)
56       return 0;
57 
58     // This is an absolute symbol.
59     if (!IS)
60       return D.Value;
61 
62     uint64_t Offset = D.Value;
63 
64     // An object in an SHF_MERGE section might be referenced via a
65     // section symbol (as a hack for reducing the number of local
66     // symbols).
67     // Depending on the addend, the reference via a section symbol
68     // refers to a different object in the merge section.
69     // Since the objects in the merge section are not necessarily
70     // contiguous in the output, the addend can thus affect the final
71     // VA in a non-linear way.
72     // To make this work, we incorporate the addend into the section
73     // offset (and zero out the addend for later processing) so that
74     // we find the right object in the section.
75     if (D.isSection()) {
76       Offset += Addend;
77       Addend = 0;
78     }
79 
80     const OutputSection *OutSec = IS->getOutputSection();
81 
82     // In the typical case, this is actually very simple and boils
83     // down to adding together 3 numbers:
84     // 1. The address of the output section.
85     // 2. The offset of the input section within the output section.
86     // 3. The offset within the input section (this addition happens
87     //    inside InputSection::getOffset).
88     //
89     // If you understand the data structures involved with this next
90     // line (and how they get built), then you have a pretty good
91     // understanding of the linker.
92     uint64_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset(Offset);
93 
94     if (D.isTls() && !Config->Relocatable) {
95       if (!Out::TlsPhdr)
96         fatal(toString(D.getFile()) +
97               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
98       return VA - Out::TlsPhdr->p_vaddr;
99     }
100     return VA;
101   }
102   case SymbolBody::DefinedCommonKind:
103     llvm_unreachable("common are converted to bss");
104   case SymbolBody::SharedKind: {
105     auto &SS = cast<SharedSymbol>(Body);
106     if (SS.CopyRelSec)
107       return SS.CopyRelSec->getParent()->Addr + SS.CopyRelSec->OutSecOff;
108     if (SS.NeedsPltAddr)
109       return Body.getPltVA();
110     return 0;
111   }
112   case SymbolBody::UndefinedKind:
113     return 0;
114   case SymbolBody::LazyArchiveKind:
115   case SymbolBody::LazyObjectKind:
116     assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
117     return 0;
118   }
119   llvm_unreachable("invalid symbol kind");
120 }
121 
122 SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
123                        uint8_t Type)
124     : SymbolKind(K), IsLocal(IsLocal), NeedsPltAddr(false),
125       IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
126       IsInIgot(false), IsPreemptible(false), Type(Type), StOther(StOther),
127       Name(Name) {}
128 
129 // Returns true if this is a weak undefined symbol.
130 bool SymbolBody::isUndefWeak() const {
131   // A note on isLazy() in the following expression: If you add a weak
132   // undefined symbol and then a lazy symbol to the symbol table, the
133   // combined result is a lazy weak symbol. isLazy is for that situation.
134   //
135   // Weak undefined symbols shouldn't fetch archive members (for
136   // compatibility with other linkers), but we still want to memorize
137   // that there are lazy symbols, because strong undefined symbols
138   // could be added later which triggers archive member fetching.
139   // Thus, the weak lazy symbol is a valid concept in lld.
140   return !isLocal() && symbol()->isWeak() && (isUndefined() || isLazy());
141 }
142 
143 InputFile *SymbolBody::getFile() const {
144   if (isLocal()) {
145     const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
146     // Local absolute symbols actually have a file, but that is not currently
147     // used. We could support that by having a mostly redundant InputFile in
148     // SymbolBody, or having a special absolute section if needed.
149     return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
150   }
151   return symbol()->File;
152 }
153 
154 // Overwrites all attributes with Other's so that this symbol becomes
155 // an alias to Other. This is useful for handling some options such as
156 // --wrap.
157 void SymbolBody::copyFrom(SymbolBody *Other) {
158   memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
159          sizeof(Symbol::Body));
160 }
161 
162 uint64_t SymbolBody::getVA(int64_t Addend) const {
163   uint64_t OutVA = getSymVA(*this, Addend);
164   return OutVA + Addend;
165 }
166 
167 uint64_t SymbolBody::getGotVA() const {
168   return InX::Got->getVA() + getGotOffset();
169 }
170 
171 uint64_t SymbolBody::getGotOffset() const {
172   return GotIndex * Target->GotEntrySize;
173 }
174 
175 uint64_t SymbolBody::getGotPltVA() const {
176   if (this->IsInIgot)
177     return InX::IgotPlt->getVA() + getGotPltOffset();
178   return InX::GotPlt->getVA() + getGotPltOffset();
179 }
180 
181 uint64_t SymbolBody::getGotPltOffset() const {
182   return GotPltIndex * Target->GotPltEntrySize;
183 }
184 
185 uint64_t SymbolBody::getPltVA() const {
186   if (this->IsInIplt)
187     return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
188   return InX::Plt->getVA() + Target->PltHeaderSize +
189          PltIndex * Target->PltEntrySize;
190 }
191 
192 template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
193   if (const auto *C = dyn_cast<DefinedCommon>(this))
194     return C->Size;
195   if (const auto *DR = dyn_cast<DefinedRegular>(this))
196     return DR->Size;
197   if (const auto *S = dyn_cast<SharedSymbol>(this))
198     return S->getSize<ELFT>();
199   return 0;
200 }
201 
202 OutputSection *SymbolBody::getOutputSection() const {
203   if (auto *S = dyn_cast<DefinedRegular>(this)) {
204     if (S->Section)
205       return S->Section->getOutputSection();
206     return nullptr;
207   }
208 
209   if (auto *S = dyn_cast<SharedSymbol>(this)) {
210     if (S->CopyRelSec)
211       return S->CopyRelSec->getParent();
212     return nullptr;
213   }
214 
215   if (auto *S = dyn_cast<DefinedCommon>(this)) {
216     if (Config->DefineCommon)
217       return S->Section->getParent();
218     return nullptr;
219   }
220 
221   return nullptr;
222 }
223 
224 // If a symbol name contains '@', the characters after that is
225 // a symbol version name. This function parses that.
226 void SymbolBody::parseSymbolVersion() {
227   StringRef S = getName();
228   size_t Pos = S.find('@');
229   if (Pos == 0 || Pos == StringRef::npos)
230     return;
231   StringRef Verstr = S.substr(Pos + 1);
232   if (Verstr.empty())
233     return;
234 
235   // Truncate the symbol name so that it doesn't include the version string.
236   Name = {S.data(), Pos};
237 
238   // If this is not in this DSO, it is not a definition.
239   if (!isInCurrentDSO())
240     return;
241 
242   // '@@' in a symbol name means the default version.
243   // It is usually the most recent one.
244   bool IsDefault = (Verstr[0] == '@');
245   if (IsDefault)
246     Verstr = Verstr.substr(1);
247 
248   for (VersionDefinition &Ver : Config->VersionDefinitions) {
249     if (Ver.Name != Verstr)
250       continue;
251 
252     if (IsDefault)
253       symbol()->VersionId = Ver.Id;
254     else
255       symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
256     return;
257   }
258 
259   // It is an error if the specified version is not defined.
260   // Usually version script is not provided when linking executable,
261   // but we may still want to override a versioned symbol from DSO,
262   // so we do not report error in this case.
263   if (Config->Shared)
264     error(toString(getFile()) + ": symbol " + S + " has undefined version " +
265           Verstr);
266 }
267 
268 Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
269                  uint8_t Type)
270     : SymbolBody(K, Name, IsLocal, StOther, Type) {}
271 
272 template <class ELFT> bool DefinedRegular::isMipsPIC() const {
273   typedef typename ELFT::Ehdr Elf_Ehdr;
274   if (!Section || !isFunc())
275     return false;
276 
277   auto *Sec = cast<InputSectionBase>(Section);
278   const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
279   return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
280          (Hdr->e_flags & EF_MIPS_PIC);
281 }
282 
283 Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
284                      uint8_t Type)
285     : SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
286 
287 DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
288                              uint8_t StOther, uint8_t Type)
289     : Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
290               Type),
291       Alignment(Alignment), Size(Size) {}
292 
293 // If a shared symbol is referred via a copy relocation, its alignment
294 // becomes part of the ABI. This function returns a symbol alignment.
295 // Because symbols don't have alignment attributes, we need to infer that.
296 template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
297   SharedFile<ELFT> *File = getFile<ELFT>();
298   uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
299   uint64_t SymValue = getSym<ELFT>().st_value;
300   uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
301   return std::min(SecAlign, SymAlign);
302 }
303 
304 InputFile *Lazy::fetch() {
305   if (auto *S = dyn_cast<LazyArchive>(this))
306     return S->fetch();
307   return cast<LazyObject>(this)->fetch();
308 }
309 
310 LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
311     : Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
312 
313 LazyObject::LazyObject(StringRef Name, uint8_t Type)
314     : Lazy(LazyObjectKind, Name, Type) {}
315 
316 ArchiveFile *LazyArchive::getFile() {
317   return cast<ArchiveFile>(SymbolBody::getFile());
318 }
319 
320 InputFile *LazyArchive::fetch() {
321   std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
322 
323   // getMember returns an empty buffer if the member was already
324   // read from the library.
325   if (MBInfo.first.getBuffer().empty())
326     return nullptr;
327   return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
328 }
329 
330 LazyObjFile *LazyObject::getFile() {
331   return cast<LazyObjFile>(SymbolBody::getFile());
332 }
333 
334 InputFile *LazyObject::fetch() { return getFile()->fetch(); }
335 
336 uint8_t Symbol::computeBinding() const {
337   if (Config->Relocatable)
338     return Binding;
339   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
340     return STB_LOCAL;
341   if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
342     return STB_LOCAL;
343   if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
344     return STB_GLOBAL;
345   return Binding;
346 }
347 
348 bool Symbol::includeInDynsym() const {
349   if (!Config->HasDynSymTab)
350     return false;
351   if (computeBinding() == STB_LOCAL)
352     return false;
353   if (!body()->isInCurrentDSO())
354     return true;
355   return ExportDynamic;
356 }
357 
358 // Print out a log message for --trace-symbol.
359 void elf::printTraceSymbol(Symbol *Sym) {
360   SymbolBody *B = Sym->body();
361   std::string S;
362   if (B->isUndefined())
363     S = ": reference to ";
364   else if (B->isCommon())
365     S = ": common definition of ";
366   else
367     S = ": definition of ";
368 
369   message(toString(Sym->File) + S + B->getName());
370 }
371 
372 // Returns a symbol for an error message.
373 std::string lld::toString(const SymbolBody &B) {
374   if (Config->Demangle)
375     if (Optional<std::string> S = demangle(B.getName()))
376       return *S;
377   return B.getName();
378 }
379 
380 template uint32_t SymbolBody::template getSize<ELF32LE>() const;
381 template uint32_t SymbolBody::template getSize<ELF32BE>() const;
382 template uint64_t SymbolBody::template getSize<ELF64LE>() const;
383 template uint64_t SymbolBody::template getSize<ELF64BE>() const;
384 
385 template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
386 template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
387 template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
388 template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
389 
390 template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
391 template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
392 template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
393 template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
394