]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lld/ELF/Symbols.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lld / ELF / Symbols.cpp
1 //===- Symbols.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "Symbols.h"
10 #include "InputFiles.h"
11 #include "InputSection.h"
12 #include "OutputSections.h"
13 #include "SyntheticSections.h"
14 #include "Target.h"
15 #include "Writer.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Strings.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Path.h"
20 #include <cstring>
21
22 using namespace llvm;
23 using namespace llvm::object;
24 using namespace llvm::ELF;
25
26 using namespace lld;
27 using namespace lld::elf;
28
29 Defined *ElfSym::bss;
30 Defined *ElfSym::etext1;
31 Defined *ElfSym::etext2;
32 Defined *ElfSym::edata1;
33 Defined *ElfSym::edata2;
34 Defined *ElfSym::end1;
35 Defined *ElfSym::end2;
36 Defined *ElfSym::globalOffsetTable;
37 Defined *ElfSym::mipsGp;
38 Defined *ElfSym::mipsGpDisp;
39 Defined *ElfSym::mipsLocalGp;
40 Defined *ElfSym::relaIpltStart;
41 Defined *ElfSym::relaIpltEnd;
42 Defined *ElfSym::riscvGlobalPointer;
43 Defined *ElfSym::tlsModuleBase;
44
45 // Returns a symbol for an error message.
46 static std::string demangle(StringRef symName) {
47   if (config->demangle)
48     if (Optional<std::string> s = demangleItanium(symName))
49       return *s;
50   return symName;
51 }
52 namespace lld {
53 std::string toString(const Symbol &b) { return demangle(b.getName()); }
54 std::string toELFString(const Archive::Symbol &b) {
55   return demangle(b.getName());
56 }
57 } // namespace lld
58
59 static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
60   switch (sym.kind()) {
61   case Symbol::DefinedKind: {
62     auto &d = cast<Defined>(sym);
63     SectionBase *isec = d.section;
64
65     // This is an absolute symbol.
66     if (!isec)
67       return d.value;
68
69     assert(isec != &InputSection::discarded);
70     isec = isec->repl;
71
72     uint64_t offset = d.value;
73
74     // An object in an SHF_MERGE section might be referenced via a
75     // section symbol (as a hack for reducing the number of local
76     // symbols).
77     // Depending on the addend, the reference via a section symbol
78     // refers to a different object in the merge section.
79     // Since the objects in the merge section are not necessarily
80     // contiguous in the output, the addend can thus affect the final
81     // VA in a non-linear way.
82     // To make this work, we incorporate the addend into the section
83     // offset (and zero out the addend for later processing) so that
84     // we find the right object in the section.
85     if (d.isSection()) {
86       offset += addend;
87       addend = 0;
88     }
89
90     // In the typical case, this is actually very simple and boils
91     // down to adding together 3 numbers:
92     // 1. The address of the output section.
93     // 2. The offset of the input section within the output section.
94     // 3. The offset within the input section (this addition happens
95     //    inside InputSection::getOffset).
96     //
97     // If you understand the data structures involved with this next
98     // line (and how they get built), then you have a pretty good
99     // understanding of the linker.
100     uint64_t va = isec->getVA(offset);
101
102     // MIPS relocatable files can mix regular and microMIPS code.
103     // Linker needs to distinguish such code. To do so microMIPS
104     // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
105     // field. Unfortunately, the `MIPS::relocateOne()` method has
106     // a symbol value only. To pass type of the symbol (regular/microMIPS)
107     // to that routine as well as other places where we write
108     // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
109     // field etc) do the same trick as compiler uses to mark microMIPS
110     // for CPU - set the less-significant bit.
111     if (config->emachine == EM_MIPS && isMicroMips() &&
112         ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
113       va |= 1;
114
115     if (d.isTls() && !config->relocatable) {
116       // Use the address of the TLS segment's first section rather than the
117       // segment's address, because segment addresses aren't initialized until
118       // after sections are finalized. (e.g. Measuring the size of .rela.dyn
119       // for Android relocation packing requires knowing TLS symbol addresses
120       // during section finalization.)
121       if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
122         fatal(toString(d.file) +
123               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
124       return va - Out::tlsPhdr->firstSec->addr;
125     }
126     return va;
127   }
128   case Symbol::SharedKind:
129   case Symbol::UndefinedKind:
130     return 0;
131   case Symbol::LazyArchiveKind:
132   case Symbol::LazyObjectKind:
133     assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
134     return 0;
135   case Symbol::CommonKind:
136     llvm_unreachable("common symbol reached writer");
137   case Symbol::PlaceholderKind:
138     llvm_unreachable("placeholder symbol reached writer");
139   }
140   llvm_unreachable("invalid symbol kind");
141 }
142
143 uint64_t Symbol::getVA(int64_t addend) const {
144   uint64_t outVA = getSymVA(*this, addend);
145   return outVA + addend;
146 }
147
148 uint64_t Symbol::getGotVA() const {
149   if (gotInIgot)
150     return in.igotPlt->getVA() + getGotPltOffset();
151   return in.got->getVA() + getGotOffset();
152 }
153
154 uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
155
156 uint64_t Symbol::getGotPltVA() const {
157   if (isInIplt)
158     return in.igotPlt->getVA() + getGotPltOffset();
159   return in.gotPlt->getVA() + getGotPltOffset();
160 }
161
162 uint64_t Symbol::getGotPltOffset() const {
163   if (isInIplt)
164     return pltIndex * config->wordsize;
165   return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
166 }
167
168 uint64_t Symbol::getPPC64LongBranchOffset() const {
169   assert(ppc64BranchltIndex != 0xffff);
170   return ppc64BranchltIndex * config->wordsize;
171 }
172
173 uint64_t Symbol::getPltVA() const {
174   PltSection *plt = isInIplt ? in.iplt : in.plt;
175   uint64_t outVA =
176       plt->getVA() + plt->headerSize + pltIndex * target->pltEntrySize;
177   // While linking microMIPS code PLT code are always microMIPS
178   // code. Set the less-significant bit to track that fact.
179   // See detailed comment in the `getSymVA` function.
180   if (config->emachine == EM_MIPS && isMicroMips())
181     outVA |= 1;
182   return outVA;
183 }
184
185 uint64_t Symbol::getPPC64LongBranchTableVA() const {
186   assert(ppc64BranchltIndex != 0xffff);
187   return in.ppc64LongBranchTarget->getVA() +
188          ppc64BranchltIndex * config->wordsize;
189 }
190
191 uint64_t Symbol::getSize() const {
192   if (const auto *dr = dyn_cast<Defined>(this))
193     return dr->size;
194   return cast<SharedSymbol>(this)->size;
195 }
196
197 OutputSection *Symbol::getOutputSection() const {
198   if (auto *s = dyn_cast<Defined>(this)) {
199     if (auto *sec = s->section)
200       return sec->repl->getOutputSection();
201     return nullptr;
202   }
203   return nullptr;
204 }
205
206 // If a symbol name contains '@', the characters after that is
207 // a symbol version name. This function parses that.
208 void Symbol::parseSymbolVersion() {
209   StringRef s = getName();
210   size_t pos = s.find('@');
211   if (pos == 0 || pos == StringRef::npos)
212     return;
213   StringRef verstr = s.substr(pos + 1);
214   if (verstr.empty())
215     return;
216
217   // Truncate the symbol name so that it doesn't include the version string.
218   nameSize = pos;
219
220   // If this is not in this DSO, it is not a definition.
221   if (!isDefined())
222     return;
223
224   // '@@' in a symbol name means the default version.
225   // It is usually the most recent one.
226   bool isDefault = (verstr[0] == '@');
227   if (isDefault)
228     verstr = verstr.substr(1);
229
230   for (VersionDefinition &ver : config->versionDefinitions) {
231     if (ver.name != verstr)
232       continue;
233
234     if (isDefault)
235       versionId = ver.id;
236     else
237       versionId = ver.id | VERSYM_HIDDEN;
238     return;
239   }
240
241   // It is an error if the specified version is not defined.
242   // Usually version script is not provided when linking executable,
243   // but we may still want to override a versioned symbol from DSO,
244   // so we do not report error in this case. We also do not error
245   // if the symbol has a local version as it won't be in the dynamic
246   // symbol table.
247   if (config->shared && versionId != VER_NDX_LOCAL)
248     error(toString(file) + ": symbol " + s + " has undefined version " +
249           verstr);
250 }
251
252 void Symbol::fetch() const {
253   if (auto *sym = dyn_cast<LazyArchive>(this)) {
254     cast<ArchiveFile>(sym->file)->fetch(sym->sym);
255     return;
256   }
257
258   if (auto *sym = dyn_cast<LazyObject>(this)) {
259     dyn_cast<LazyObjFile>(sym->file)->fetch();
260     return;
261   }
262
263   llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
264 }
265
266 MemoryBufferRef LazyArchive::getMemberBuffer() {
267   Archive::Child c =
268       CHECK(sym.getMember(),
269             "could not get the member for symbol " + toELFString(sym));
270
271   return CHECK(c.getMemoryBufferRef(),
272                "could not get the buffer for the member defining symbol " +
273                    toELFString(sym));
274 }
275
276 uint8_t Symbol::computeBinding() const {
277   if (config->relocatable)
278     return binding;
279   if (visibility != STV_DEFAULT && visibility != STV_PROTECTED)
280     return STB_LOCAL;
281   if (versionId == VER_NDX_LOCAL && isDefined() && !isPreemptible)
282     return STB_LOCAL;
283   if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
284     return STB_GLOBAL;
285   return binding;
286 }
287
288 bool Symbol::includeInDynsym() const {
289   if (!config->hasDynSymTab)
290     return false;
291   if (computeBinding() == STB_LOCAL)
292     return false;
293
294   // If a PIE binary was not linked against any shared libraries, then we can
295   // safely drop weak undef symbols from .dynsym.
296   if (isUndefWeak() && config->pie && sharedFiles.empty())
297     return false;
298
299   return isUndefined() || isShared() || exportDynamic;
300 }
301
302 // Print out a log message for --trace-symbol.
303 void elf::printTraceSymbol(const Symbol *sym) {
304   std::string s;
305   if (sym->isUndefined())
306     s = ": reference to ";
307   else if (sym->isLazy())
308     s = ": lazy definition of ";
309   else if (sym->isShared())
310     s = ": shared definition of ";
311   else if (sym->isCommon())
312     s = ": common definition of ";
313   else
314     s = ": definition of ";
315
316   message(toString(sym->file) + s + sym->getName());
317 }
318
319 void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
320   if (!config->warnSymbolOrdering)
321     return;
322
323   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
324   // is emitted. It makes sense to not warn on undefined symbols.
325   //
326   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
327   // but we don't have to be compatible here.
328   if (sym->isUndefined() &&
329       config->unresolvedSymbols == UnresolvedPolicy::Ignore)
330     return;
331
332   const InputFile *file = sym->file;
333   auto *d = dyn_cast<Defined>(sym);
334
335   auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
336
337   if (sym->isUndefined())
338     report(": unable to order undefined symbol: ");
339   else if (sym->isShared())
340     report(": unable to order shared symbol: ");
341   else if (d && !d->section)
342     report(": unable to order absolute symbol: ");
343   else if (d && isa<OutputSection>(d->section))
344     report(": unable to order synthetic symbol: ");
345   else if (d && !d->section->repl->isLive())
346     report(": unable to order discarded symbol: ");
347 }
348
349 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
350   if (va == STV_DEFAULT)
351     return vb;
352   if (vb == STV_DEFAULT)
353     return va;
354   return std::min(va, vb);
355 }
356
357 // Merge symbol properties.
358 //
359 // When we have many symbols of the same name, we choose one of them,
360 // and that's the result of symbol resolution. However, symbols that
361 // were not chosen still affect some symbol properties.
362 void Symbol::mergeProperties(const Symbol &other) {
363   if (other.exportDynamic)
364     exportDynamic = true;
365   if (other.isUsedInRegularObj)
366     isUsedInRegularObj = true;
367
368   // DSO symbols do not affect visibility in the output.
369   if (!other.isShared())
370     visibility = getMinVisibility(visibility, other.visibility);
371 }
372
373 void Symbol::resolve(const Symbol &other) {
374   mergeProperties(other);
375
376   if (isPlaceholder()) {
377     replace(other);
378     return;
379   }
380
381   switch (other.kind()) {
382   case Symbol::UndefinedKind:
383     resolveUndefined(cast<Undefined>(other));
384     break;
385   case Symbol::CommonKind:
386     resolveCommon(cast<CommonSymbol>(other));
387     break;
388   case Symbol::DefinedKind:
389     resolveDefined(cast<Defined>(other));
390     break;
391   case Symbol::LazyArchiveKind:
392     resolveLazy(cast<LazyArchive>(other));
393     break;
394   case Symbol::LazyObjectKind:
395     resolveLazy(cast<LazyObject>(other));
396     break;
397   case Symbol::SharedKind:
398     resolveShared(cast<SharedSymbol>(other));
399     break;
400   case Symbol::PlaceholderKind:
401     llvm_unreachable("bad symbol kind");
402   }
403 }
404
405 void Symbol::resolveUndefined(const Undefined &other) {
406   // An undefined symbol with non default visibility must be satisfied
407   // in the same DSO.
408   //
409   // If this is a non-weak defined symbol in a discarded section, override the
410   // existing undefined symbol for better error message later.
411   if ((isShared() && other.visibility != STV_DEFAULT) ||
412       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
413     replace(other);
414     return;
415   }
416
417   if (traced)
418     printTraceSymbol(&other);
419
420   if (isLazy()) {
421     // An undefined weak will not fetch archive members. See comment on Lazy in
422     // Symbols.h for the details.
423     if (other.binding == STB_WEAK) {
424       binding = STB_WEAK;
425       type = other.type;
426       return;
427     }
428
429     // Do extra check for --warn-backrefs.
430     //
431     // --warn-backrefs is an option to prevent an undefined reference from
432     // fetching an archive member written earlier in the command line. It can be
433     // used to keep compatibility with GNU linkers to some degree.
434     // I'll explain the feature and why you may find it useful in this comment.
435     //
436     // lld's symbol resolution semantics is more relaxed than traditional Unix
437     // linkers. For example,
438     //
439     //   ld.lld foo.a bar.o
440     //
441     // succeeds even if bar.o contains an undefined symbol that has to be
442     // resolved by some object file in foo.a. Traditional Unix linkers don't
443     // allow this kind of backward reference, as they visit each file only once
444     // from left to right in the command line while resolving all undefined
445     // symbols at the moment of visiting.
446     //
447     // In the above case, since there's no undefined symbol when a linker visits
448     // foo.a, no files are pulled out from foo.a, and because the linker forgets
449     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
450     // that could have been resolved otherwise.
451     //
452     // That lld accepts more relaxed form means that (besides it'd make more
453     // sense) you can accidentally write a command line or a build file that
454     // works only with lld, even if you have a plan to distribute it to wider
455     // users who may be using GNU linkers. With --warn-backrefs, you can detect
456     // a library order that doesn't work with other Unix linkers.
457     //
458     // The option is also useful to detect cyclic dependencies between static
459     // archives. Again, lld accepts
460     //
461     //   ld.lld foo.a bar.a
462     //
463     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
464     // handled as an error.
465     //
466     // Here is how the option works. We assign a group ID to each file. A file
467     // with a smaller group ID can pull out object files from an archive file
468     // with an equal or greater group ID. Otherwise, it is a reverse dependency
469     // and an error.
470     //
471     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
472     // files within the same --{start,end}-group get the same group ID. E.g.
473     //
474     //   ld.lld A B --start-group C D --end-group E
475     //
476     // A forms group 0. B form group 1. C and D (including their member object
477     // files) form group 2. E forms group 3. I think that you can see how this
478     // group assignment rule simulates the traditional linker's semantics.
479     bool backref = config->warnBackrefs && other.file &&
480                    file->groupId < other.file->groupId;
481     fetch();
482
483     // We don't report backward references to weak symbols as they can be
484     // overridden later.
485     if (backref && !isWeak())
486       warn("backward reference detected: " + other.getName() + " in " +
487            toString(other.file) + " refers to " + toString(file));
488     return;
489   }
490
491   // Undefined symbols in a SharedFile do not change the binding.
492   if (dyn_cast_or_null<SharedFile>(other.file))
493     return;
494
495   if (isUndefined()) {
496     // The binding may "upgrade" from weak to non-weak.
497     if (other.binding != STB_WEAK)
498       binding = other.binding;
499   } else if (auto *s = dyn_cast<SharedSymbol>(this)) {
500     // The binding of a SharedSymbol will be weak if there is at least one
501     // reference and all are weak. The binding has one opportunity to change to
502     // weak: if the first reference is weak.
503     if (other.binding != STB_WEAK || !s->referenced)
504       binding = other.binding;
505     s->referenced = true;
506   }
507 }
508
509 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
510 // foo@@VER. We want to effectively ignore foo, so give precedence to
511 // foo@@VER.
512 // FIXME: If users can transition to using
513 // .symver foo,foo@@@VER
514 // we can delete this hack.
515 static int compareVersion(StringRef a, StringRef b) {
516   bool x = a.contains("@@");
517   bool y = b.contains("@@");
518   if (!x && y)
519     return 1;
520   if (x && !y)
521     return -1;
522   return 0;
523 }
524
525 // Compare two symbols. Return 1 if the new symbol should win, -1 if
526 // the new symbol should lose, or 0 if there is a conflict.
527 int Symbol::compare(const Symbol *other) const {
528   assert(other->isDefined() || other->isCommon());
529
530   if (!isDefined() && !isCommon())
531     return 1;
532
533   if (int cmp = compareVersion(getName(), other->getName()))
534     return cmp;
535
536   if (other->isWeak())
537     return -1;
538
539   if (isWeak())
540     return 1;
541
542   if (isCommon() && other->isCommon()) {
543     if (config->warnCommon)
544       warn("multiple common of " + getName());
545     return 0;
546   }
547
548   if (isCommon()) {
549     if (config->warnCommon)
550       warn("common " + getName() + " is overridden");
551     return 1;
552   }
553
554   if (other->isCommon()) {
555     if (config->warnCommon)
556       warn("common " + getName() + " is overridden");
557     return -1;
558   }
559
560   auto *oldSym = cast<Defined>(this);
561   auto *newSym = cast<Defined>(other);
562
563   if (other->file && isa<BitcodeFile>(other->file))
564     return 0;
565
566   if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
567       newSym->binding == STB_GLOBAL)
568     return -1;
569
570   return 0;
571 }
572
573 static void reportDuplicate(Symbol *sym, InputFile *newFile,
574                             InputSectionBase *errSec, uint64_t errOffset) {
575   if (config->allowMultipleDefinition)
576     return;
577
578   Defined *d = cast<Defined>(sym);
579   if (!d->section || !errSec) {
580     error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
581           toString(sym->file) + "\n>>> defined in " + toString(newFile));
582     return;
583   }
584
585   // Construct and print an error message in the form of:
586   //
587   //   ld.lld: error: duplicate symbol: foo
588   //   >>> defined at bar.c:30
589   //   >>>            bar.o (/home/alice/src/bar.o)
590   //   >>> defined at baz.c:563
591   //   >>>            baz.o in archive libbaz.a
592   auto *sec1 = cast<InputSectionBase>(d->section);
593   std::string src1 = sec1->getSrcMsg(*sym, d->value);
594   std::string obj1 = sec1->getObjMsg(d->value);
595   std::string src2 = errSec->getSrcMsg(*sym, errOffset);
596   std::string obj2 = errSec->getObjMsg(errOffset);
597
598   std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
599   if (!src1.empty())
600     msg += src1 + "\n>>>            ";
601   msg += obj1 + "\n>>> defined at ";
602   if (!src2.empty())
603     msg += src2 + "\n>>>            ";
604   msg += obj2;
605   error(msg);
606 }
607
608 void Symbol::resolveCommon(const CommonSymbol &other) {
609   int cmp = compare(&other);
610   if (cmp < 0)
611     return;
612
613   if (cmp > 0) {
614     replace(other);
615     return;
616   }
617
618   CommonSymbol *oldSym = cast<CommonSymbol>(this);
619
620   oldSym->alignment = std::max(oldSym->alignment, other.alignment);
621   if (oldSym->size < other.size) {
622     oldSym->file = other.file;
623     oldSym->size = other.size;
624   }
625 }
626
627 void Symbol::resolveDefined(const Defined &other) {
628   int cmp = compare(&other);
629   if (cmp > 0)
630     replace(other);
631   else if (cmp == 0)
632     reportDuplicate(this, other.file,
633                     dyn_cast_or_null<InputSectionBase>(other.section),
634                     other.value);
635 }
636
637 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
638   if (!isUndefined())
639     return;
640
641   // An undefined weak will not fetch archive members. See comment on Lazy in
642   // Symbols.h for the details.
643   if (isWeak()) {
644     uint8_t ty = type;
645     replace(other);
646     type = ty;
647     binding = STB_WEAK;
648     return;
649   }
650
651   other.fetch();
652 }
653
654 void Symbol::resolveShared(const SharedSymbol &other) {
655   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
656     // An undefined symbol with non default visibility must be satisfied
657     // in the same DSO.
658     uint8_t bind = binding;
659     replace(other);
660     binding = bind;
661     cast<SharedSymbol>(this)->referenced = true;
662   }
663 }