xref: /llvm-project-15.0.7/lld/ELF/Symbols.cpp (revision 5a127cdc)
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::getPPC64LongBranchOffset() const {
142   assert(PPC64BranchltIndex != 0xffff);
143   return PPC64BranchltIndex * Target->GotPltEntrySize;
144 }
145 
146 uint64_t Symbol::getPltVA() const {
147   PltSection *Plt = IsInIplt ? In.Iplt : In.Plt;
148   return Plt->getVA() + Plt->HeaderSize + PltIndex * Target->PltEntrySize;
149 }
150 
151 uint64_t Symbol::getPPC64LongBranchTableVA() const {
152   assert(PPC64BranchltIndex != 0xffff);
153   return In.PPC64LongBranchTarget->getVA() +
154          PPC64BranchltIndex * Target->GotPltEntrySize;
155 }
156 
157 uint64_t Symbol::getSize() const {
158   if (const auto *DR = dyn_cast<Defined>(this))
159     return DR->Size;
160   return cast<SharedSymbol>(this)->Size;
161 }
162 
163 OutputSection *Symbol::getOutputSection() const {
164   if (auto *S = dyn_cast<Defined>(this)) {
165     if (auto *Sec = S->Section)
166       return Sec->Repl->getOutputSection();
167     return nullptr;
168   }
169   return nullptr;
170 }
171 
172 // If a symbol name contains '@', the characters after that is
173 // a symbol version name. This function parses that.
174 void Symbol::parseSymbolVersion() {
175   StringRef S = getName();
176   size_t Pos = S.find('@');
177   if (Pos == 0 || Pos == StringRef::npos)
178     return;
179   StringRef Verstr = S.substr(Pos + 1);
180   if (Verstr.empty())
181     return;
182 
183   // Truncate the symbol name so that it doesn't include the version string.
184   NameSize = Pos;
185 
186   // If this is not in this DSO, it is not a definition.
187   if (!isDefined())
188     return;
189 
190   // '@@' in a symbol name means the default version.
191   // It is usually the most recent one.
192   bool IsDefault = (Verstr[0] == '@');
193   if (IsDefault)
194     Verstr = Verstr.substr(1);
195 
196   for (VersionDefinition &Ver : Config->VersionDefinitions) {
197     if (Ver.Name != Verstr)
198       continue;
199 
200     if (IsDefault)
201       VersionId = Ver.Id;
202     else
203       VersionId = Ver.Id | VERSYM_HIDDEN;
204     return;
205   }
206 
207   // It is an error if the specified version is not defined.
208   // Usually version script is not provided when linking executable,
209   // but we may still want to override a versioned symbol from DSO,
210   // so we do not report error in this case. We also do not error
211   // if the symbol has a local version as it won't be in the dynamic
212   // symbol table.
213   if (Config->Shared && VersionId != VER_NDX_LOCAL)
214     error(toString(File) + ": symbol " + S + " has undefined version " +
215           Verstr);
216 }
217 
218 InputFile *LazyArchive::fetch() { return cast<ArchiveFile>(File)->fetch(Sym); }
219 
220 MemoryBufferRef LazyArchive::getMemberBuffer() {
221   Archive::Child C = CHECK(
222       Sym.getMember(), "could not get the member for symbol " + Sym.getName());
223 
224   return CHECK(C.getMemoryBufferRef(),
225                "could not get the buffer for the member defining symbol " +
226                    Sym.getName());
227 }
228 
229 uint8_t Symbol::computeBinding() const {
230   if (Config->Relocatable)
231     return Binding;
232   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
233     return STB_LOCAL;
234   if (VersionId == VER_NDX_LOCAL && isDefined() && !IsPreemptible)
235     return STB_LOCAL;
236   if (!Config->GnuUnique && Binding == STB_GNU_UNIQUE)
237     return STB_GLOBAL;
238   return Binding;
239 }
240 
241 bool Symbol::includeInDynsym() const {
242   if (!Config->HasDynSymTab)
243     return false;
244   if (computeBinding() == STB_LOCAL)
245     return false;
246   if (!isDefined())
247     return true;
248   return ExportDynamic;
249 }
250 
251 // Print out a log message for --trace-symbol.
252 void elf::printTraceSymbol(Symbol *Sym) {
253   std::string S;
254   if (Sym->isUndefined())
255     S = ": reference to ";
256   else if (Sym->isLazy())
257     S = ": lazy definition of ";
258   else if (Sym->isShared())
259     S = ": shared definition of ";
260   else if (dyn_cast_or_null<BssSection>(cast<Defined>(Sym)->Section))
261     S = ": common definition of ";
262   else
263     S = ": definition of ";
264 
265   message(toString(Sym->File) + S + Sym->getName());
266 }
267 
268 void elf::maybeWarnUnorderableSymbol(const Symbol *Sym) {
269   if (!Config->WarnSymbolOrdering)
270     return;
271 
272   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
273   // is emitted. It makes sense to not warn on undefined symbols.
274   //
275   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
276   // but we don't have to be compatible here.
277   if (Sym->isUndefined() &&
278       Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
279     return;
280 
281   const InputFile *File = Sym->File;
282   auto *D = dyn_cast<Defined>(Sym);
283 
284   auto Warn = [&](StringRef S) { warn(toString(File) + S + Sym->getName()); };
285 
286   if (Sym->isUndefined())
287     Warn(": unable to order undefined symbol: ");
288   else if (Sym->isShared())
289     Warn(": unable to order shared symbol: ");
290   else if (D && !D->Section)
291     Warn(": unable to order absolute symbol: ");
292   else if (D && isa<OutputSection>(D->Section))
293     Warn(": unable to order synthetic symbol: ");
294   else if (D && !D->Section->Repl->Live)
295     Warn(": unable to order discarded symbol: ");
296 }
297 
298 // Returns a symbol for an error message.
299 std::string lld::toString(const Symbol &B) {
300   if (Config->Demangle)
301     if (Optional<std::string> S = demangleItanium(B.getName()))
302       return *S;
303   return B.getName();
304 }
305