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