xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision bacf751a)
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 "InputFiles.h"
12 #include "InputSection.h"
13 #include "OutputSections.h"
14 #include "SyntheticSections.h"
15 #include "Target.h"
16 #include "Writer.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Strings.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Path.h"
21 #include <cstring>
22 
23 using namespace llvm;
24 using namespace llvm::object;
25 using namespace llvm::ELF;
26 
27 using namespace lld;
28 using namespace lld::elf;
29 
30 Defined *ElfSym::Bss;
31 Defined *ElfSym::Etext1;
32 Defined *ElfSym::Etext2;
33 Defined *ElfSym::Edata1;
34 Defined *ElfSym::Edata2;
35 Defined *ElfSym::End1;
36 Defined *ElfSym::End2;
37 Defined *ElfSym::GlobalOffsetTable;
38 Defined *ElfSym::MipsGp;
39 Defined *ElfSym::MipsGpDisp;
40 Defined *ElfSym::MipsLocalGp;
41 Defined *ElfSym::RelaIpltEnd;
42 
43 static uint64_t getSymVA(const Symbol &Sym, int64_t &Addend) {
44   switch (Sym.kind()) {
45   case Symbol::DefinedKind: {
46     auto &D = cast<Defined>(Sym);
47     SectionBase *IS = D.Section;
48 
49     // According to the ELF spec reference to a local symbol from outside
50     // the group are not allowed. Unfortunately .eh_frame breaks that rule
51     // and must be treated specially. For now we just replace the symbol with
52     // 0.
53     if (IS == &InputSection::Discarded)
54       return 0;
55 
56     // This is an absolute symbol.
57     if (!IS)
58       return D.Value;
59 
60     IS = IS->Repl;
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     // In the typical case, this is actually very simple and boils
81     // down to adding together 3 numbers:
82     // 1. The address of the output section.
83     // 2. The offset of the input section within the output section.
84     // 3. The offset within the input section (this addition happens
85     //    inside InputSection::getOffset).
86     //
87     // If you understand the data structures involved with this next
88     // line (and how they get built), then you have a pretty good
89     // understanding of the linker.
90     uint64_t VA = IS->getVA(Offset);
91 
92     if (D.isTls() && !Config->Relocatable) {
93       // Use the address of the TLS segment's first section rather than the
94       // segment's address, because segment addresses aren't initialized until
95       // after sections are finalized. (e.g. Measuring the size of .rela.dyn
96       // for Android relocation packing requires knowing TLS symbol addresses
97       // during section finalization.)
98       if (!Out::TlsPhdr || !Out::TlsPhdr->FirstSec)
99         fatal(toString(D.File) +
100               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
101       return VA - Out::TlsPhdr->FirstSec->Addr;
102     }
103     return VA;
104   }
105   case Symbol::SharedKind:
106   case Symbol::UndefinedKind:
107     return 0;
108   case Symbol::LazyArchiveKind:
109   case Symbol::LazyObjectKind:
110     assert(Sym.IsUsedInRegularObj && "lazy symbol reached writer");
111     return 0;
112   case Symbol::PlaceholderKind:
113     llvm_unreachable("placeholder symbol reached writer");
114   }
115   llvm_unreachable("invalid symbol kind");
116 }
117 
118 uint64_t Symbol::getVA(int64_t Addend) const {
119   uint64_t OutVA = getSymVA(*this, Addend);
120   return OutVA + Addend;
121 }
122 
123 uint64_t Symbol::getGotVA() const { return In.Got->getVA() + getGotOffset(); }
124 
125 uint64_t Symbol::getGotOffset() const {
126   return GotIndex * Target->GotEntrySize;
127 }
128 
129 uint64_t Symbol::getGotPltVA() const {
130   if (this->IsInIgot)
131     return In.IgotPlt->getVA() + getGotPltOffset();
132   return In.GotPlt->getVA() + getGotPltOffset();
133 }
134 
135 uint64_t Symbol::getGotPltOffset() const {
136   if (IsInIgot)
137     return PltIndex * Target->GotPltEntrySize;
138   return (PltIndex + Target->GotPltHeaderEntriesNum) * Target->GotPltEntrySize;
139 }
140 
141 uint64_t Symbol::getPltVA() const {
142   if (this->IsInIplt)
143     return In.Iplt->getVA() + PltIndex * Target->PltEntrySize;
144   return In.Plt->getVA() + Target->getPltEntryOffset(PltIndex);
145 }
146 
147 uint64_t Symbol::getPltOffset() const {
148   assert(!this->IsInIplt);
149   return Target->getPltEntryOffset(PltIndex);
150 }
151 
152 uint64_t Symbol::getSize() const {
153   if (const auto *DR = dyn_cast<Defined>(this))
154     return DR->Size;
155   return cast<SharedSymbol>(this)->Size;
156 }
157 
158 OutputSection *Symbol::getOutputSection() const {
159   if (auto *S = dyn_cast<Defined>(this)) {
160     if (auto *Sec = S->Section)
161       return Sec->Repl->getOutputSection();
162     return nullptr;
163   }
164   return nullptr;
165 }
166 
167 // If a symbol name contains '@', the characters after that is
168 // a symbol version name. This function parses that.
169 void Symbol::parseSymbolVersion() {
170   StringRef S = getName();
171   size_t Pos = S.find('@');
172   if (Pos == 0 || Pos == StringRef::npos)
173     return;
174   StringRef Verstr = S.substr(Pos + 1);
175   if (Verstr.empty())
176     return;
177 
178   // Truncate the symbol name so that it doesn't include the version string.
179   NameSize = Pos;
180 
181   // If this is not in this DSO, it is not a definition.
182   if (!isDefined())
183     return;
184 
185   // '@@' in a symbol name means the default version.
186   // It is usually the most recent one.
187   bool IsDefault = (Verstr[0] == '@');
188   if (IsDefault)
189     Verstr = Verstr.substr(1);
190 
191   for (VersionDefinition &Ver : Config->VersionDefinitions) {
192     if (Ver.Name != Verstr)
193       continue;
194 
195     if (IsDefault)
196       VersionId = Ver.Id;
197     else
198       VersionId = Ver.Id | VERSYM_HIDDEN;
199     return;
200   }
201 
202   // It is an error if the specified version is not defined.
203   // Usually version script is not provided when linking executable,
204   // but we may still want to override a versioned symbol from DSO,
205   // so we do not report error in this case. We also do not error
206   // if the symbol has a local version as it won't be in the dynamic
207   // symbol table.
208   if (Config->Shared && VersionId != VER_NDX_LOCAL)
209     error(toString(File) + ": symbol " + S + " has undefined version " +
210           Verstr);
211 }
212 
213 InputFile *LazyArchive::fetch() { return cast<ArchiveFile>(File)->fetch(Sym); }
214 
215 MemoryBufferRef LazyArchive::getMemberBuffer() {
216   Archive::Child C = CHECK(
217       Sym.getMember(), "could not get the member for symbol " + Sym.getName());
218 
219   return CHECK(C.getMemoryBufferRef(),
220                "could not get the buffer for the member defining symbol " +
221                    Sym.getName());
222 }
223 
224 uint8_t Symbol::computeBinding() const {
225   if (Config->Relocatable)
226     return Binding;
227   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
228     return STB_LOCAL;
229   if (VersionId == VER_NDX_LOCAL && isDefined() && !IsPreemptible)
230     return STB_LOCAL;
231   if (!Config->GnuUnique && Binding == STB_GNU_UNIQUE)
232     return STB_GLOBAL;
233   return Binding;
234 }
235 
236 bool Symbol::includeInDynsym() const {
237   if (!Config->HasDynSymTab)
238     return false;
239   if (computeBinding() == STB_LOCAL)
240     return false;
241   if (!isDefined())
242     return true;
243   return ExportDynamic;
244 }
245 
246 // Print out a log message for --trace-symbol.
247 void elf::printTraceSymbol(Symbol *Sym) {
248   std::string S;
249   if (Sym->isUndefined())
250     S = ": reference to ";
251   else if (Sym->isLazy())
252     S = ": lazy definition of ";
253   else if (Sym->isShared())
254     S = ": shared definition of ";
255   else if (dyn_cast_or_null<BssSection>(cast<Defined>(Sym)->Section))
256     S = ": common definition of ";
257   else
258     S = ": definition of ";
259 
260   message(toString(Sym->File) + S + Sym->getName());
261 }
262 
263 void elf::maybeWarnUnorderableSymbol(const Symbol *Sym) {
264   if (!Config->WarnSymbolOrdering)
265     return;
266 
267   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
268   // is emitted. It makes sense to not warn on undefined symbols.
269   //
270   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
271   // but we don't have to be compatible here.
272   if (Sym->isUndefined() &&
273       Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
274     return;
275 
276   const InputFile *File = Sym->File;
277   auto *D = dyn_cast<Defined>(Sym);
278 
279   auto Warn = [&](StringRef S) { warn(toString(File) + S + Sym->getName()); };
280 
281   if (Sym->isUndefined())
282     Warn(": unable to order undefined symbol: ");
283   else if (Sym->isShared())
284     Warn(": unable to order shared symbol: ");
285   else if (D && !D->Section)
286     Warn(": unable to order absolute symbol: ");
287   else if (D && isa<OutputSection>(D->Section))
288     Warn(": unable to order synthetic symbol: ");
289   else if (D && !D->Section->Repl->Live)
290     Warn(": unable to order discarded symbol: ");
291 }
292 
293 // Returns a symbol for an error message.
294 std::string lld::toString(const Symbol &B) {
295   if (Config->Demangle)
296     if (Optional<std::string> S = demangleItanium(B.getName()))
297       return *S;
298   return B.getName();
299 }
300