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