xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision 7fe441b2)
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   // See comment on Lazy in Symbols.h for the details.
132   return !isLocal() && symbol()->isWeak() && (isUndefined() || isLazy());
133 }
134 
135 InputFile *SymbolBody::getFile() const {
136   if (isLocal()) {
137     const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
138     // Local absolute symbols actually have a file, but that is not currently
139     // used. We could support that by having a mostly redundant InputFile in
140     // SymbolBody, or having a special absolute section if needed.
141     return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
142   }
143   return symbol()->File;
144 }
145 
146 // Overwrites all attributes with Other's so that this symbol becomes
147 // an alias to Other. This is useful for handling some options such as
148 // --wrap.
149 void SymbolBody::copyFrom(SymbolBody *Other) {
150   memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
151          sizeof(Symbol::Body));
152 }
153 
154 uint64_t SymbolBody::getVA(int64_t Addend) const {
155   uint64_t OutVA = getSymVA(*this, Addend);
156   return OutVA + Addend;
157 }
158 
159 uint64_t SymbolBody::getGotVA() const {
160   return InX::Got->getVA() + getGotOffset();
161 }
162 
163 uint64_t SymbolBody::getGotOffset() const {
164   return GotIndex * Target->GotEntrySize;
165 }
166 
167 uint64_t SymbolBody::getGotPltVA() const {
168   if (this->IsInIgot)
169     return InX::IgotPlt->getVA() + getGotPltOffset();
170   return InX::GotPlt->getVA() + getGotPltOffset();
171 }
172 
173 uint64_t SymbolBody::getGotPltOffset() const {
174   return GotPltIndex * Target->GotPltEntrySize;
175 }
176 
177 uint64_t SymbolBody::getPltVA() const {
178   if (this->IsInIplt)
179     return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
180   return InX::Plt->getVA() + Target->PltHeaderSize +
181          PltIndex * Target->PltEntrySize;
182 }
183 
184 template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
185   if (const auto *C = dyn_cast<DefinedCommon>(this))
186     return C->Size;
187   if (const auto *DR = dyn_cast<DefinedRegular>(this))
188     return DR->Size;
189   if (const auto *S = dyn_cast<SharedSymbol>(this))
190     return S->getSize<ELFT>();
191   return 0;
192 }
193 
194 OutputSection *SymbolBody::getOutputSection() const {
195   if (auto *S = dyn_cast<DefinedRegular>(this)) {
196     if (S->Section)
197       return S->Section->getOutputSection();
198     return nullptr;
199   }
200 
201   if (auto *S = dyn_cast<SharedSymbol>(this)) {
202     if (S->CopyRelSec)
203       return S->CopyRelSec->getParent();
204     return nullptr;
205   }
206 
207   if (auto *S = dyn_cast<DefinedCommon>(this)) {
208     if (Config->DefineCommon)
209       return S->Section->getParent();
210     return nullptr;
211   }
212 
213   return nullptr;
214 }
215 
216 // If a symbol name contains '@', the characters after that is
217 // a symbol version name. This function parses that.
218 void SymbolBody::parseSymbolVersion() {
219   StringRef S = getName();
220   size_t Pos = S.find('@');
221   if (Pos == 0 || Pos == StringRef::npos)
222     return;
223   StringRef Verstr = S.substr(Pos + 1);
224   if (Verstr.empty())
225     return;
226 
227   // Truncate the symbol name so that it doesn't include the version string.
228   Name = {S.data(), Pos};
229 
230   // If this is not in this DSO, it is not a definition.
231   if (!isInCurrentDSO())
232     return;
233 
234   // '@@' in a symbol name means the default version.
235   // It is usually the most recent one.
236   bool IsDefault = (Verstr[0] == '@');
237   if (IsDefault)
238     Verstr = Verstr.substr(1);
239 
240   for (VersionDefinition &Ver : Config->VersionDefinitions) {
241     if (Ver.Name != Verstr)
242       continue;
243 
244     if (IsDefault)
245       symbol()->VersionId = Ver.Id;
246     else
247       symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
248     return;
249   }
250 
251   // It is an error if the specified version is not defined.
252   // Usually version script is not provided when linking executable,
253   // but we may still want to override a versioned symbol from DSO,
254   // so we do not report error in this case.
255   if (Config->Shared)
256     error(toString(getFile()) + ": symbol " + S + " has undefined version " +
257           Verstr);
258 }
259 
260 Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
261                  uint8_t Type)
262     : SymbolBody(K, Name, IsLocal, StOther, Type) {}
263 
264 template <class ELFT> bool DefinedRegular::isMipsPIC() const {
265   typedef typename ELFT::Ehdr Elf_Ehdr;
266   if (!Section || !isFunc())
267     return false;
268 
269   auto *Sec = cast<InputSectionBase>(Section);
270   const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
271   return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
272          (Hdr->e_flags & EF_MIPS_PIC);
273 }
274 
275 Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
276                      uint8_t Type)
277     : SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
278 
279 DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
280                              uint8_t StOther, uint8_t Type)
281     : Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
282               Type),
283       Alignment(Alignment), Size(Size) {}
284 
285 // If a shared symbol is referred via a copy relocation, its alignment
286 // becomes part of the ABI. This function returns a symbol alignment.
287 // Because symbols don't have alignment attributes, we need to infer that.
288 template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
289   SharedFile<ELFT> *File = getFile<ELFT>();
290   uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
291   uint64_t SymValue = getSym<ELFT>().st_value;
292   uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
293   return std::min(SecAlign, SymAlign);
294 }
295 
296 InputFile *Lazy::fetch() {
297   if (auto *S = dyn_cast<LazyArchive>(this))
298     return S->fetch();
299   return cast<LazyObject>(this)->fetch();
300 }
301 
302 LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
303     : Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
304 
305 LazyObject::LazyObject(StringRef Name, uint8_t Type)
306     : Lazy(LazyObjectKind, Name, Type) {}
307 
308 ArchiveFile *LazyArchive::getFile() {
309   return cast<ArchiveFile>(SymbolBody::getFile());
310 }
311 
312 InputFile *LazyArchive::fetch() {
313   std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
314 
315   // getMember returns an empty buffer if the member was already
316   // read from the library.
317   if (MBInfo.first.getBuffer().empty())
318     return nullptr;
319   return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
320 }
321 
322 LazyObjFile *LazyObject::getFile() {
323   return cast<LazyObjFile>(SymbolBody::getFile());
324 }
325 
326 InputFile *LazyObject::fetch() { return getFile()->fetch(); }
327 
328 uint8_t Symbol::computeBinding() const {
329   if (Config->Relocatable)
330     return Binding;
331   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
332     return STB_LOCAL;
333   if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
334     return STB_LOCAL;
335   if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
336     return STB_GLOBAL;
337   return Binding;
338 }
339 
340 bool Symbol::includeInDynsym() const {
341   if (!Config->HasDynSymTab)
342     return false;
343   if (computeBinding() == STB_LOCAL)
344     return false;
345   if (!body()->isInCurrentDSO())
346     return true;
347   return ExportDynamic;
348 }
349 
350 // Print out a log message for --trace-symbol.
351 void elf::printTraceSymbol(Symbol *Sym) {
352   SymbolBody *B = Sym->body();
353   std::string S;
354   if (B->isUndefined())
355     S = ": reference to ";
356   else if (B->isCommon())
357     S = ": common definition of ";
358   else
359     S = ": definition of ";
360 
361   message(toString(Sym->File) + S + B->getName());
362 }
363 
364 // Returns a symbol for an error message.
365 std::string lld::toString(const SymbolBody &B) {
366   if (Config->Demangle)
367     if (Optional<std::string> S = demangle(B.getName()))
368       return *S;
369   return B.getName();
370 }
371 
372 template uint32_t SymbolBody::template getSize<ELF32LE>() const;
373 template uint32_t SymbolBody::template getSize<ELF32BE>() const;
374 template uint64_t SymbolBody::template getSize<ELF64LE>() const;
375 template uint64_t SymbolBody::template getSize<ELF64BE>() const;
376 
377 template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
378 template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
379 template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
380 template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
381 
382 template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
383 template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
384 template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
385 template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
386