blob: 45c545d5329627db5525f5d42cbafc67f19139d4 [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:071//===- Symbols.cpp --------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:563// 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
Michael J. Spencer84487f12015-07-24 21:03:076//
7//===----------------------------------------------------------------------===//
8
9#include "Symbols.h"
Michael J. Spencercdae0a42015-07-28 22:58:2510#include "InputFiles.h"
Rui Ueyamab5a69702016-02-01 21:00:3511#include "InputSection.h"
12#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:4713#include "SyntheticSections.h"
Rui Ueyamab5a69702016-02-01 21:00:3514#include "Target.h"
Rafael Espindola17cb7c02016-12-19 17:01:0115#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:3816#include "lld/Common/ErrorHandler.h"
Rui Ueyama53fe4692017-11-28 02:15:2617#include "lld/Common/Strings.h"
Michael J. Spencer1b348a62015-09-04 22:28:1018#include "llvm/ADT/STLExtras.h"
Eugene Leviantc958d8d2016-10-12 08:19:3019#include "llvm/Support/Path.h"
Rui Ueyamac72ba3a2016-11-23 04:57:2520#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1021
22using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0723using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5224using namespace llvm::ELF;
Michael J. Spencer84487f12015-07-24 21:03:0725
26using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:5427using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:0728
Peter Collingbournee9a9e0a2017-11-06 04:35:3129Defined *ElfSym::Bss;
30Defined *ElfSym::Etext1;
31Defined *ElfSym::Etext2;
32Defined *ElfSym::Edata1;
33Defined *ElfSym::Edata2;
34Defined *ElfSym::End1;
35Defined *ElfSym::End2;
36Defined *ElfSym::GlobalOffsetTable;
37Defined *ElfSym::MipsGp;
38Defined *ElfSym::MipsGpDisp;
39Defined *ElfSym::MipsLocalGp;
Rui Ueyama6f9d49c2019-01-15 18:30:2340Defined *ElfSym::RelaIpltStart;
Rafael Espindolaaded4092018-04-19 16:54:3041Defined *ElfSym::RelaIpltEnd;
Rui Ueyama80474a22017-02-28 19:29:5542
Rui Ueyama48882242017-11-04 00:31:0443static uint64_t getSymVA(const Symbol &Sym, int64_t &Addend) {
44 switch (Sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3145 case Symbol::DefinedKind: {
46 auto &D = cast<Defined>(Sym);
Rafael Espindola5616adf2017-03-08 22:36:2847 SectionBase *IS = D.Section;
Rui Ueyamab5a69702016-02-01 21:00:3548
Rafael Espindolaccfe3cb2016-04-04 14:04:1649 // 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.
Rafael Espindola774ea7d2017-02-23 16:49:0753 if (IS == &InputSection::Discarded)
Rafael Espindolaccfe3cb2016-04-04 14:04:1654 return 0;
55
Rui Ueyamab5a69702016-02-01 21:00:3556 // This is an absolute symbol.
Sean Silva902ae3c2016-12-15 00:57:5357 if (!IS)
Rafael Espindolaccfe3cb2016-04-04 14:04:1658 return D.Value;
Rui Ueyamab5a69702016-02-01 21:00:3559
Rafael Espindolaf4d6e8c2018-04-19 17:26:5060 IS = IS->Repl;
61
Rafael Espindola9371bab2017-03-08 15:21:3262 uint64_t Offset = D.Value;
Sean Silvaa9ba4502017-02-28 08:32:5663
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).
Sean Silvad4e60622017-03-01 04:44:0467 // 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.
Rafael Espindolaccfe3cb2016-04-04 14:04:1675 if (D.isSection()) {
Rafael Espindola1f5b70f2016-03-11 14:21:3776 Offset += Addend;
77 Addend = 0;
78 }
Sean Silvaa9ba4502017-02-28 08:32:5679
Sean Silva6ab39262017-02-28 09:01:5880 // 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.
Rafael Espindola4f058a22018-03-24 00:35:1190 uint64_t VA = IS->getVA(Offset);
Sean Silva6ab39262017-02-28 09:01:5891
Simon Atanasyanfae2a5092019-02-19 10:36:5892 // MIPS relocatable files can mix regular and microMIPS code.
93 // Linker needs to distinguish such code. To do so microMIPS
94 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
95 // field. Unfortunately, the `MIPS::relocateOne()` method has
96 // a symbol value only. To pass type of the symbol (regular/microMIPS)
97 // to that routine as well as other places where we write
98 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
99 // field etc) do the same trick as compiler uses to mark microMIPS
100 // for CPU - set the less-significant bit.
101 if (Config->EMachine == EM_MIPS && isMicroMips() &&
102 ((Sym.StOther & STO_MIPS_MICROMIPS) || Sym.NeedsPltAddr))
103 VA |= 1;
104
George Rimar6a3b1542016-10-04 08:52:51105 if (D.isTls() && !Config->Relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48106 // Use the address of the TLS segment's first section rather than the
107 // segment's address, because segment addresses aren't initialized until
108 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
109 // for Android relocation packing requires knowing TLS symbol addresses
110 // during section finalization.)
111 if (!Out::TlsPhdr || !Out::TlsPhdr->FirstSec)
Rafael Espindoladfebd362017-11-29 22:47:35112 fatal(toString(D.File) +
Peter Collingbourne3e2abde2017-07-14 00:22:46113 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Ryan Prichard1c33d142018-09-18 00:24:48114 return VA - Out::TlsPhdr->FirstSec->Addr;
George Rimar6a3b1542016-10-04 08:52:51115 }
Rafael Espindola1f5b70f2016-03-11 14:21:37116 return VA;
Rui Ueyamab5a69702016-02-01 21:00:35117 }
Rafael Espindolaab0cce52018-04-26 17:58:58118 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47119 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35120 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47121 case Symbol::LazyArchiveKind:
122 case Symbol::LazyObjectKind:
Chih-Hung Hsieh73e04842018-09-11 23:00:36123 assert(Sym.IsUsedInRegularObj && "lazy symbol reached writer");
124 return 0;
Rui Ueyama5c073a92019-05-16 03:29:03125 case Symbol::CommonKind:
126 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18127 case Symbol::PlaceholderKind:
128 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35129 }
George Rimar777f9632016-03-12 08:31:34130 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35131}
132
Rui Ueyamaf52496e2017-11-03 21:21:47133uint64_t Symbol::getVA(int64_t Addend) const {
George Rimarf64618a2017-03-17 11:56:54134 uint64_t OutVA = getSymVA(*this, Addend);
Rafael Espindola8381c562016-03-17 23:36:19135 return OutVA + Addend;
Rafael Espindola87d9f102016-03-11 12:19:05136}
137
Peter Collingbourne8331f612019-02-13 21:49:55138uint64_t Symbol::getGotVA() const {
139 if (GotInIgot)
140 return In.IgotPlt->getVA() + getGotPltOffset();
141 return In.Got->getVA() + getGotOffset();
142}
Rafael Espindola74031ba2016-04-07 15:20:56143
Rui Ueyamaf52496e2017-11-03 21:21:47144uint64_t Symbol::getGotOffset() const {
Rui Ueyama803b1202016-07-13 18:55:14145 return GotIndex * Target->GotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35146}
147
Rui Ueyamaf52496e2017-11-03 21:21:47148uint64_t Symbol::getGotPltVA() const {
Peter Collingbourne8331f612019-02-13 21:49:55149 if (IsInIplt)
Rui Ueyama4e247522018-09-25 19:26:58150 return In.IgotPlt->getVA() + getGotPltOffset();
151 return In.GotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56152}
153
Rui Ueyamaf52496e2017-11-03 21:21:47154uint64_t Symbol::getGotPltOffset() const {
Peter Collingbourne8331f612019-02-13 21:49:55155 if (IsInIplt)
Rafael Espindolaf4a9d562018-04-26 16:09:30156 return PltIndex * Target->GotPltEntrySize;
157 return (PltIndex + Target->GotPltHeaderEntriesNum) * Target->GotPltEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35158}
159
Sean Fertile614dc112018-11-14 17:56:43160uint64_t Symbol::getPPC64LongBranchOffset() const {
161 assert(PPC64BranchltIndex != 0xffff);
162 return PPC64BranchltIndex * Target->GotPltEntrySize;
163}
164
Rui Ueyamaf52496e2017-11-03 21:21:47165uint64_t Symbol::getPltVA() const {
Rui Ueyama63d397e2018-11-28 17:42:59166 PltSection *Plt = IsInIplt ? In.Iplt : In.Plt;
Simon Atanasyanfae2a5092019-02-19 10:36:58167 uint64_t OutVA =
168 Plt->getVA() + Plt->HeaderSize + PltIndex * Target->PltEntrySize;
169 // While linking microMIPS code PLT code are always microMIPS
170 // code. Set the less-significant bit to track that fact.
171 // See detailed comment in the `getSymVA` function.
172 if (Config->EMachine == EM_MIPS && isMicroMips())
173 OutVA |= 1;
174 return OutVA;
Rafael Espindolaab0cce52018-04-26 17:58:58175}
176
Sean Fertile614dc112018-11-14 17:56:43177uint64_t Symbol::getPPC64LongBranchTableVA() const {
178 assert(PPC64BranchltIndex != 0xffff);
179 return In.PPC64LongBranchTarget->getVA() +
180 PPC64BranchltIndex * Target->GotPltEntrySize;
181}
182
Rui Ueyamaf52496e2017-11-03 21:21:47183uint64_t Symbol::getSize() const {
Peter Collingbournee9a9e0a2017-11-06 04:35:31184 if (const auto *DR = dyn_cast<Defined>(this))
Rafael Espindolaccfe3cb2016-04-04 14:04:16185 return DR->Size;
George Rimar904ed692018-07-17 11:35:28186 return cast<SharedSymbol>(this)->Size;
Rui Ueyama512c61d2016-02-03 00:12:24187}
188
Rui Ueyamaf52496e2017-11-03 21:21:47189OutputSection *Symbol::getOutputSection() const {
Peter Collingbournee9a9e0a2017-11-06 04:35:31190 if (auto *S = dyn_cast<Defined>(this)) {
Rafael Espindolaf4fb5fd2017-12-13 22:59:23191 if (auto *Sec = S->Section)
Rafael Espindolaf4d6e8c2018-04-19 17:26:50192 return Sec->Repl->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42193 return nullptr;
194 }
Rui Ueyama968db482017-02-28 04:02:42195 return nullptr;
196}
197
Rui Ueyama35fa6c52016-11-23 05:48:40198// If a symbol name contains '@', the characters after that is
199// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47200void Symbol::parseSymbolVersion() {
Rui Ueyama35fa6c52016-11-23 05:48:40201 StringRef S = getName();
202 size_t Pos = S.find('@');
203 if (Pos == 0 || Pos == StringRef::npos)
204 return;
205 StringRef Verstr = S.substr(Pos + 1);
206 if (Verstr.empty())
207 return;
208
209 // Truncate the symbol name so that it doesn't include the version string.
Rafael Espindola1eeb2622018-04-25 21:44:37210 NameSize = Pos;
Rui Ueyama35fa6c52016-11-23 05:48:40211
Rafael Espindola1d6d1b42017-01-17 16:08:06212 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07213 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35214 return;
215
Rui Ueyama35fa6c52016-11-23 05:48:40216 // '@@' in a symbol name means the default version.
217 // It is usually the most recent one.
218 bool IsDefault = (Verstr[0] == '@');
219 if (IsDefault)
220 Verstr = Verstr.substr(1);
221
222 for (VersionDefinition &Ver : Config->VersionDefinitions) {
223 if (Ver.Name != Verstr)
224 continue;
225
226 if (IsDefault)
Rui Ueyamaf1f00842017-10-31 16:07:41227 VersionId = Ver.Id;
Rui Ueyama35fa6c52016-11-23 05:48:40228 else
Rui Ueyamaf1f00842017-10-31 16:07:41229 VersionId = Ver.Id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40230 return;
231 }
232
233 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13234 // Usually version script is not provided when linking executable,
235 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56236 // so we do not report error in this case. We also do not error
237 // if the symbol has a local version as it won't be in the dynamic
238 // symbol table.
239 if (Config->Shared && VersionId != VER_NDX_LOCAL)
Rafael Espindoladfebd362017-11-29 22:47:35240 error(toString(File) + ": symbol " + S + " has undefined version " +
George Rimar4d2f97622017-07-04 13:19:13241 Verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40242}
243
Rui Ueyama7f7d2b22019-05-23 09:58:08244void Symbol::fetch() const {
245 if (auto *Sym = dyn_cast<LazyArchive>(this)) {
Rui Ueyamaf5d9d232019-05-23 10:15:12246 cast<ArchiveFile>(Sym->File)->fetch(Sym->Sym);
Rui Ueyama7f7d2b22019-05-23 09:58:08247 return;
248 }
249
250 if (auto *Sym = dyn_cast<LazyObject>(this)) {
Rui Ueyamaf5d9d232019-05-23 10:15:12251 dyn_cast<LazyObjFile>(Sym->File)->fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08252 return;
253 }
254
255 llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
Rui Ueyama7d476192019-05-16 02:14:00256}
Rui Ueyamaf8baa662016-04-07 19:24:51257
Peter Collingbourne98930112018-08-08 23:48:12258MemoryBufferRef LazyArchive::getMemberBuffer() {
259 Archive::Child C = CHECK(
260 Sym.getMember(), "could not get the member for symbol " + Sym.getName());
261
262 return CHECK(C.getMemoryBufferRef(),
263 "could not get the buffer for the member defining symbol " +
264 Sym.getName());
265}
266
Rui Ueyamaf52496e2017-11-03 21:21:47267uint8_t Symbol::computeBinding() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13268 if (Config->Relocatable)
269 return Binding;
Peter Collingbournedadcc172016-04-22 18:42:48270 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
Rafael Espindolab7e2ee22017-01-10 17:08:13271 return STB_LOCAL;
George Rimarf79a8ef2018-10-03 09:33:00272 if (VersionId == VER_NDX_LOCAL && isDefined() && !IsPreemptible)
Rafael Espindolab7e2ee22017-01-10 17:08:13273 return STB_LOCAL;
Rui Ueyamaaad2e322018-02-02 21:44:06274 if (!Config->GnuUnique && Binding == STB_GNU_UNIQUE)
Rafael Espindolab7e2ee22017-01-10 17:08:13275 return STB_GLOBAL;
276 return Binding;
277}
278
Rui Ueyamaf52496e2017-11-03 21:21:47279bool Symbol::includeInDynsym() const {
Rafael Espindolae05e2f82017-09-15 18:05:02280 if (!Config->HasDynSymTab)
281 return false;
Rafael Espindolab7e2ee22017-01-10 17:08:13282 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25283 return false;
Siva Chandra1915e2b2019-03-18 15:32:57284 // If a PIE binary was not linked against any shared libraries, then we can
285 // safely drop weak undef symbols from .dynsym.
286 if (isUndefWeak() && Config->Pie && SharedFiles.empty())
287 return false;
Peter Collingbourneb472aa02017-11-06 04:39:07288 if (!isDefined())
Rafael Espindola3d9f1c02017-09-13 20:43:04289 return true;
Rafael Espindolac57f8cd2017-09-13 20:47:53290 return ExportDynamic;
Rafael Espindolaae605c12016-04-21 20:35:25291}
Rui Ueyama69c778c2016-07-17 17:50:09292
293// Print out a log message for --trace-symbol.
Sam Clegg7991b682019-05-24 13:29:17294void elf::printTraceSymbol(const Symbol *Sym) {
Rui Ueyamae6e206d2017-02-21 23:22:56295 std::string S;
Rui Ueyamaf1f00842017-10-31 16:07:41296 if (Sym->isUndefined())
Rui Ueyamae6e206d2017-02-21 23:22:56297 S = ": reference to ";
Rui Ueyamaf1f00842017-10-31 16:07:41298 else if (Sym->isLazy())
Rafael Espindolabc2b1652017-10-27 18:30:11299 S = ": lazy definition of ";
Rui Ueyamaf1f00842017-10-31 16:07:41300 else if (Sym->isShared())
Rafael Espindolabc2b1652017-10-27 18:30:11301 S = ": shared definition of ";
Rui Ueyama5c073a92019-05-16 03:29:03302 else if (Sym->isCommon())
Peter Collingbourne6c55a702017-11-06 04:33:58303 S = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09304 else
Rui Ueyamae6e206d2017-02-21 23:22:56305 S = ": definition of ";
306
Rui Ueyamaf1f00842017-10-31 16:07:41307 message(toString(Sym->File) + S + Sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09308}
309
Rui Ueyama4c06a6c2018-10-26 15:07:12310void elf::maybeWarnUnorderableSymbol(const Symbol *Sym) {
Michael J. Spencerb8427252018-04-17 23:30:05311 if (!Config->WarnSymbolOrdering)
312 return;
Rui Ueyamab774c3c2018-04-26 01:38:29313
Fangrui Song11ca54f2018-10-10 22:48:57314 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
315 // is emitted. It makes sense to not warn on undefined symbols.
316 //
317 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
318 // but we don't have to be compatible here.
319 if (Sym->isUndefined() &&
320 Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
321 return;
322
Michael J. Spencerb8427252018-04-17 23:30:05323 const InputFile *File = Sym->File;
324 auto *D = dyn_cast<Defined>(Sym);
Rui Ueyamab774c3c2018-04-26 01:38:29325
326 auto Warn = [&](StringRef S) { warn(toString(File) + S + Sym->getName()); };
327
Michael J. Spencerb8427252018-04-17 23:30:05328 if (Sym->isUndefined())
Rui Ueyamab774c3c2018-04-26 01:38:29329 Warn(": unable to order undefined symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05330 else if (Sym->isShared())
Rui Ueyamab774c3c2018-04-26 01:38:29331 Warn(": unable to order shared symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05332 else if (D && !D->Section)
Rui Ueyamab774c3c2018-04-26 01:38:29333 Warn(": unable to order absolute symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05334 else if (D && isa<OutputSection>(D->Section))
Rui Ueyamab774c3c2018-04-26 01:38:29335 Warn(": unable to order synthetic symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05336 else if (D && !D->Section->Repl->Live)
Rui Ueyamab774c3c2018-04-26 01:38:29337 Warn(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05338}
339
Rui Ueyamaa3ac1732016-11-24 20:24:18340// Returns a symbol for an error message.
Rui Ueyamaf52496e2017-11-03 21:21:47341std::string lld::toString(const Symbol &B) {
Rui Ueyamaa3ac1732016-11-24 20:24:18342 if (Config->Demangle)
Rui Ueyama53fe4692017-11-28 02:15:26343 if (Optional<std::string> S = demangleItanium(B.getName()))
Rui Ueyama4c5b8ce2016-12-07 23:17:05344 return *S;
Rui Ueyamaa3ac1732016-11-24 20:24:18345 return B.getName();
346}
Rui Ueyama7f7d2b22019-05-23 09:58:08347
348static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
349 if (VA == STV_DEFAULT)
350 return VB;
351 if (VB == STV_DEFAULT)
352 return VA;
353 return std::min(VA, VB);
354}
355
356// Merge symbol properties.
357//
358// When we have many symbols of the same name, we choose one of them,
359// and that's the result of symbol resolution. However, symbols that
360// were not chosen still affect some symbol properties.
361void Symbol::mergeProperties(const Symbol &Other) {
362 if (Other.ExportDynamic)
363 ExportDynamic = true;
364 if (Other.IsUsedInRegularObj)
365 IsUsedInRegularObj = true;
366
367 // DSO symbols do not affect visibility in the output.
368 if (!Other.isShared())
369 Visibility = getMinVisibility(Visibility, Other.Visibility);
370}
371
372void Symbol::resolve(const Symbol &Other) {
373 mergeProperties(Other);
374
375 if (isPlaceholder()) {
376 replace(Other);
377 return;
378 }
379
380 switch (Other.kind()) {
381 case Symbol::UndefinedKind:
382 resolveUndefined(cast<Undefined>(Other));
383 break;
384 case Symbol::CommonKind:
385 resolveCommon(cast<CommonSymbol>(Other));
386 break;
387 case Symbol::DefinedKind:
388 resolveDefined(cast<Defined>(Other));
389 break;
390 case Symbol::LazyArchiveKind:
391 resolveLazy(cast<LazyArchive>(Other));
392 break;
393 case Symbol::LazyObjectKind:
394 resolveLazy(cast<LazyObject>(Other));
395 break;
396 case Symbol::SharedKind:
397 resolveShared(cast<SharedSymbol>(Other));
398 break;
399 case Symbol::PlaceholderKind:
400 llvm_unreachable("bad symbol kind");
401 }
402}
403
404void Symbol::resolveUndefined(const Undefined &Other) {
405 // An undefined symbol with non default visibility must be satisfied
406 // in the same DSO.
407 //
408 // If this is a non-weak defined symbol in a discarded section, override the
409 // existing undefined symbol for better error message later.
410 if ((isShared() && Other.Visibility != STV_DEFAULT) ||
411 (isUndefined() && Other.Binding != STB_WEAK && Other.DiscardedSecIdx)) {
412 replace(Other);
413 return;
414 }
415
Sam Clegg7991b682019-05-24 13:29:17416 if (Traced)
417 printTraceSymbol(&Other);
418
Rui Ueyama7f7d2b22019-05-23 09:58:08419 if (isShared() || isLazy() || (isUndefined() && Other.Binding != STB_WEAK))
420 Binding = Other.Binding;
421
422 if (isLazy()) {
423 // An undefined weak will not fetch archive members. See comment on Lazy in
424 // Symbols.h for the details.
425 if (Other.Binding == STB_WEAK) {
426 Type = Other.Type;
427 return;
428 }
429
430 // Do extra check for --warn-backrefs.
431 //
432 // --warn-backrefs is an option to prevent an undefined reference from
433 // fetching an archive member written earlier in the command line. It can be
434 // used to keep compatibility with GNU linkers to some degree.
435 // I'll explain the feature and why you may find it useful in this comment.
436 //
437 // lld's symbol resolution semantics is more relaxed than traditional Unix
438 // linkers. For example,
439 //
440 // ld.lld foo.a bar.o
441 //
442 // succeeds even if bar.o contains an undefined symbol that has to be
443 // resolved by some object file in foo.a. Traditional Unix linkers don't
444 // allow this kind of backward reference, as they visit each file only once
445 // from left to right in the command line while resolving all undefined
446 // symbols at the moment of visiting.
447 //
448 // In the above case, since there's no undefined symbol when a linker visits
449 // foo.a, no files are pulled out from foo.a, and because the linker forgets
450 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
451 // that could have been resolved otherwise.
452 //
453 // That lld accepts more relaxed form means that (besides it'd make more
454 // sense) you can accidentally write a command line or a build file that
455 // works only with lld, even if you have a plan to distribute it to wider
456 // users who may be using GNU linkers. With --warn-backrefs, you can detect
457 // a library order that doesn't work with other Unix linkers.
458 //
459 // The option is also useful to detect cyclic dependencies between static
460 // archives. Again, lld accepts
461 //
462 // ld.lld foo.a bar.a
463 //
464 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
465 // handled as an error.
466 //
467 // Here is how the option works. We assign a group ID to each file. A file
468 // with a smaller group ID can pull out object files from an archive file
469 // with an equal or greater group ID. Otherwise, it is a reverse dependency
470 // and an error.
471 //
472 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
473 // files within the same --{start,end}-group get the same group ID. E.g.
474 //
475 // ld.lld A B --start-group C D --end-group E
476 //
477 // A forms group 0. B form group 1. C and D (including their member object
478 // files) form group 2. E forms group 3. I think that you can see how this
479 // group assignment rule simulates the traditional linker's semantics.
480 bool Backref = Config->WarnBackrefs && Other.File &&
481 File->GroupId < Other.File->GroupId;
482 fetch();
483
484 // We don't report backward references to weak symbols as they can be
485 // overridden later.
486 if (Backref && !isWeak())
487 warn("backward reference detected: " + Other.getName() + " in " +
488 toString(Other.File) + " refers to " + toString(File));
489 }
490}
491
492// Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
493// foo@@VER. We want to effectively ignore foo, so give precedence to
494// foo@@VER.
495// FIXME: If users can transition to using
496// .symver foo,foo@@@VER
497// we can delete this hack.
498static int compareVersion(StringRef A, StringRef B) {
499 bool X = A.contains("@@");
500 bool Y = B.contains("@@");
501 if (!X && Y)
502 return 1;
503 if (X && !Y)
504 return -1;
505 return 0;
506}
507
508// Compare two symbols. Return 1 if the new symbol should win, -1 if
509// the new symbol should lose, or 0 if there is a conflict.
510int Symbol::compare(const Symbol *Other) const {
511 assert(Other->isDefined() || Other->isCommon());
512
513 if (!isDefined() && !isCommon())
514 return 1;
515
516 if (int Cmp = compareVersion(getName(), Other->getName()))
517 return Cmp;
518
519 if (Other->isWeak())
520 return -1;
521
522 if (isWeak())
523 return 1;
524
525 if (isCommon() && Other->isCommon()) {
526 if (Config->WarnCommon)
527 warn("multiple common of " + getName());
528 return 0;
529 }
530
531 if (isCommon()) {
532 if (Config->WarnCommon)
533 warn("common " + getName() + " is overridden");
534 return 1;
535 }
536
537 if (Other->isCommon()) {
538 if (Config->WarnCommon)
539 warn("common " + getName() + " is overridden");
540 return -1;
541 }
542
543 auto *OldSym = cast<Defined>(this);
544 auto *NewSym = cast<Defined>(Other);
545
546 if (Other->File && isa<BitcodeFile>(Other->File))
547 return 0;
548
549 if (!OldSym->Section && !NewSym->Section && OldSym->Value == NewSym->Value &&
550 NewSym->Binding == STB_GLOBAL)
551 return -1;
552
553 return 0;
554}
555
556static void reportDuplicate(Symbol *Sym, InputFile *NewFile,
557 InputSectionBase *ErrSec, uint64_t ErrOffset) {
558 if (Config->AllowMultipleDefinition)
559 return;
560
561 Defined *D = cast<Defined>(Sym);
562 if (!D->Section || !ErrSec) {
563 error("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " +
564 toString(Sym->File) + "\n>>> defined in " + toString(NewFile));
565 return;
566 }
567
568 // Construct and print an error message in the form of:
569 //
570 // ld.lld: error: duplicate symbol: foo
571 // >>> defined at bar.c:30
572 // >>> bar.o (/home/alice/src/bar.o)
573 // >>> defined at baz.c:563
574 // >>> baz.o in archive libbaz.a
575 auto *Sec1 = cast<InputSectionBase>(D->Section);
576 std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value);
577 std::string Obj1 = Sec1->getObjMsg(D->Value);
578 std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset);
579 std::string Obj2 = ErrSec->getObjMsg(ErrOffset);
580
581 std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at ";
582 if (!Src1.empty())
583 Msg += Src1 + "\n>>> ";
584 Msg += Obj1 + "\n>>> defined at ";
585 if (!Src2.empty())
586 Msg += Src2 + "\n>>> ";
587 Msg += Obj2;
588 error(Msg);
589}
590
591void Symbol::resolveCommon(const CommonSymbol &Other) {
592 int Cmp = compare(&Other);
593 if (Cmp < 0)
594 return;
595
596 if (Cmp > 0) {
597 replace(Other);
598 return;
599 }
600
601 CommonSymbol *OldSym = cast<CommonSymbol>(this);
602
603 OldSym->Alignment = std::max(OldSym->Alignment, Other.Alignment);
604 if (OldSym->Size < Other.Size) {
605 OldSym->File = Other.File;
606 OldSym->Size = Other.Size;
607 }
608}
609
610void Symbol::resolveDefined(const Defined &Other) {
611 int Cmp = compare(&Other);
612 if (Cmp > 0)
613 replace(Other);
614 else if (Cmp == 0)
615 reportDuplicate(this, Other.File,
616 dyn_cast_or_null<InputSectionBase>(Other.Section),
617 Other.Value);
618}
619
620template <class LazyT> void Symbol::resolveLazy(const LazyT &Other) {
621 if (!isUndefined())
622 return;
623
624 // An undefined weak will not fetch archive members. See comment on Lazy in
625 // Symbols.h for the details.
626 if (isWeak()) {
627 uint8_t Ty = Type;
628 replace(Other);
629 Type = Ty;
630 Binding = STB_WEAK;
631 return;
632 }
633
634 Other.fetch();
635}
636
637void Symbol::resolveShared(const SharedSymbol &Other) {
638 if (Visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
639 // An undefined symbol with non default visibility must be satisfied
640 // in the same DSO.
641 uint8_t Bind = Binding;
642 replace(Other);
643 Binding = Bind;
644 }
645}