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