1 //===- InputFiles.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 "InputFiles.h" 10 #include "Config.h" 11 #include "DWARF.h" 12 #include "Driver.h" 13 #include "InputSection.h" 14 #include "LinkerScript.h" 15 #include "SymbolTable.h" 16 #include "Symbols.h" 17 #include "SyntheticSections.h" 18 #include "Target.h" 19 #include "lld/Common/CommonLinkerContext.h" 20 #include "lld/Common/DWARF.h" 21 #include "llvm/ADT/CachedHashString.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/LTO/LTO.h" 24 #include "llvm/Object/IRObjectFile.h" 25 #include "llvm/Support/ARMAttributeParser.h" 26 #include "llvm/Support/ARMBuildAttributes.h" 27 #include "llvm/Support/Endian.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Path.h" 30 #include "llvm/Support/RISCVAttributeParser.h" 31 #include "llvm/Support/TarWriter.h" 32 #include "llvm/Support/raw_ostream.h" 33 34 using namespace llvm; 35 using namespace llvm::ELF; 36 using namespace llvm::object; 37 using namespace llvm::sys; 38 using namespace llvm::sys::fs; 39 using namespace llvm::support::endian; 40 using namespace lld; 41 using namespace lld::elf; 42 43 bool InputFile::isInGroup; 44 uint32_t InputFile::nextGroupId; 45 46 std::unique_ptr<TarWriter> elf::tar; 47 48 DenseMap<StringRef, StringRef> elf::gnuWarnings; 49 50 // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 51 std::string lld::toString(const InputFile *f) { 52 static std::mutex mu; 53 if (!f) 54 return "<internal>"; 55 56 { 57 std::lock_guard<std::mutex> lock(mu); 58 if (f->toStringCache.empty()) { 59 if (f->archiveName.empty()) 60 f->toStringCache = f->getName(); 61 else 62 (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache); 63 } 64 } 65 return std::string(f->toStringCache); 66 } 67 68 // .gnu.warning.SYMBOL are treated as warning symbols for the given symbol 69 void lld::parseGNUWarning(StringRef name, ArrayRef<char> data, size_t size) { 70 static std::mutex mu; 71 if (!name.empty() && name.startswith(".gnu.warning.")) { 72 std::lock_guard<std::mutex> lock(mu); 73 StringRef wsym = name.substr(13); 74 StringRef s(data.begin()); 75 StringRef wng(s.substr(0, size)); 76 symtab.insert(wsym)->gwarn = true; 77 gnuWarnings.insert({wsym, wng}); 78 } 79 } 80 81 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) { 82 unsigned char size; 83 unsigned char endian; 84 std::tie(size, endian) = getElfArchType(mb.getBuffer()); 85 86 auto report = [&](StringRef msg) { 87 StringRef filename = mb.getBufferIdentifier(); 88 if (archiveName.empty()) 89 fatal(filename + ": " + msg); 90 else 91 fatal(archiveName + "(" + filename + "): " + msg); 92 }; 93 94 if (!mb.getBuffer().startswith(ElfMagic)) 95 report("not an ELF file"); 96 if (endian != ELFDATA2LSB && endian != ELFDATA2MSB) 97 report("corrupted ELF file: invalid data encoding"); 98 if (size != ELFCLASS32 && size != ELFCLASS64) 99 report("corrupted ELF file: invalid file class"); 100 101 size_t bufSize = mb.getBuffer().size(); 102 if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) || 103 (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr))) 104 report("corrupted ELF file: file is too short"); 105 106 if (size == ELFCLASS32) 107 return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind; 108 return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind; 109 } 110 111 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD 112 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how 113 // the input objects have been compiled. 114 static void updateARMVFPArgs(const ARMAttributeParser &attributes, 115 const InputFile *f) { 116 std::optional<unsigned> attr = 117 attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args); 118 if (!attr) 119 // If an ABI tag isn't present then it is implicitly given the value of 0 120 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files, 121 // including some in glibc that don't use FP args (and should have value 3) 122 // don't have the attribute so we do not consider an implicit value of 0 123 // as a clash. 124 return; 125 126 unsigned vfpArgs = *attr; 127 ARMVFPArgKind arg; 128 switch (vfpArgs) { 129 case ARMBuildAttrs::BaseAAPCS: 130 arg = ARMVFPArgKind::Base; 131 break; 132 case ARMBuildAttrs::HardFPAAPCS: 133 arg = ARMVFPArgKind::VFP; 134 break; 135 case ARMBuildAttrs::ToolChainFPPCS: 136 // Tool chain specific convention that conforms to neither AAPCS variant. 137 arg = ARMVFPArgKind::ToolChain; 138 break; 139 case ARMBuildAttrs::CompatibleFPAAPCS: 140 // Object compatible with all conventions. 141 return; 142 default: 143 error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs)); 144 return; 145 } 146 // Follow ld.bfd and error if there is a mix of calling conventions. 147 if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default) 148 error(toString(f) + ": incompatible Tag_ABI_VFP_args"); 149 else 150 config->armVFPArgs = arg; 151 } 152 153 // The ARM support in lld makes some use of instructions that are not available 154 // on all ARM architectures. Namely: 155 // - Use of BLX instruction for interworking between ARM and Thumb state. 156 // - Use of the extended Thumb branch encoding in relocation. 157 // - Use of the MOVT/MOVW instructions in Thumb Thunks. 158 // The ARM Attributes section contains information about the architecture chosen 159 // at compile time. We follow the convention that if at least one input object 160 // is compiled with an architecture that supports these features then lld is 161 // permitted to use them. 162 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) { 163 std::optional<unsigned> attr = 164 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); 165 if (!attr) 166 return; 167 auto arch = *attr; 168 switch (arch) { 169 case ARMBuildAttrs::Pre_v4: 170 case ARMBuildAttrs::v4: 171 case ARMBuildAttrs::v4T: 172 // Architectures prior to v5 do not support BLX instruction 173 break; 174 case ARMBuildAttrs::v5T: 175 case ARMBuildAttrs::v5TE: 176 case ARMBuildAttrs::v5TEJ: 177 case ARMBuildAttrs::v6: 178 case ARMBuildAttrs::v6KZ: 179 case ARMBuildAttrs::v6K: 180 config->armHasBlx = true; 181 // Architectures used in pre-Cortex processors do not support 182 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception 183 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do. 184 break; 185 default: 186 // All other Architectures have BLX and extended branch encoding 187 config->armHasBlx = true; 188 config->armJ1J2BranchEncoding = true; 189 if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M) 190 // All Architectures used in Cortex processors with the exception 191 // of v6-M and v6S-M have the MOVT and MOVW instructions. 192 config->armHasMovtMovw = true; 193 break; 194 } 195 } 196 197 InputFile::InputFile(Kind k, MemoryBufferRef m) 198 : mb(m), groupId(nextGroupId), fileKind(k) { 199 // All files within the same --{start,end}-group get the same group ID. 200 // Otherwise, a new file will get a new group ID. 201 if (!isInGroup) 202 ++nextGroupId; 203 } 204 205 std::optional<MemoryBufferRef> elf::readFile(StringRef path) { 206 llvm::TimeTraceScope timeScope("Load input files", path); 207 208 // The --chroot option changes our virtual root directory. 209 // This is useful when you are dealing with files created by --reproduce. 210 if (!config->chroot.empty() && path.startswith("/")) 211 path = saver().save(config->chroot + path); 212 213 log(path); 214 config->dependencyFiles.insert(llvm::CachedHashString(path)); 215 216 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 217 /*RequiresNullTerminator=*/false); 218 if (auto ec = mbOrErr.getError()) { 219 error("cannot open " + path + ": " + ec.message()); 220 return std::nullopt; 221 } 222 223 MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef(); 224 ctx.memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership 225 226 if (tar) 227 tar->append(relativeToRoot(path), mbref.getBuffer()); 228 return mbref; 229 } 230 231 // All input object files must be for the same architecture 232 // (e.g. it does not make sense to link x86 object files with 233 // MIPS object files.) This function checks for that error. 234 static bool isCompatible(InputFile *file) { 235 if (!file->isElf() && !isa<BitcodeFile>(file)) 236 return true; 237 238 if (file->ekind == config->ekind && file->emachine == config->emachine) { 239 if (config->emachine != EM_MIPS) 240 return true; 241 if (isMipsN32Abi(file) == config->mipsN32Abi) 242 return true; 243 } 244 245 StringRef target = 246 !config->bfdname.empty() ? config->bfdname : config->emulation; 247 if (!target.empty()) { 248 error(toString(file) + " is incompatible with " + target); 249 return false; 250 } 251 252 InputFile *existing = nullptr; 253 if (!ctx.objectFiles.empty()) 254 existing = ctx.objectFiles[0]; 255 else if (!ctx.sharedFiles.empty()) 256 existing = ctx.sharedFiles[0]; 257 else if (!ctx.bitcodeFiles.empty()) 258 existing = ctx.bitcodeFiles[0]; 259 std::string with; 260 if (existing) 261 with = " with " + toString(existing); 262 error(toString(file) + " is incompatible" + with); 263 return false; 264 } 265 266 template <class ELFT> static void doParseFile(InputFile *file) { 267 if (!isCompatible(file)) 268 return; 269 270 // Binary file 271 if (auto *f = dyn_cast<BinaryFile>(file)) { 272 ctx.binaryFiles.push_back(f); 273 f->parse(); 274 return; 275 } 276 277 // Lazy object file 278 if (file->lazy) { 279 if (auto *f = dyn_cast<BitcodeFile>(file)) { 280 ctx.lazyBitcodeFiles.push_back(f); 281 f->parseLazy(); 282 } else { 283 cast<ObjFile<ELFT>>(file)->parseLazy(); 284 } 285 return; 286 } 287 288 if (config->trace) 289 message(toString(file)); 290 291 // .so file 292 if (auto *f = dyn_cast<SharedFile>(file)) { 293 f->parse<ELFT>(); 294 return; 295 } 296 297 // LLVM bitcode file 298 if (auto *f = dyn_cast<BitcodeFile>(file)) { 299 ctx.bitcodeFiles.push_back(f); 300 f->parse(); 301 return; 302 } 303 304 // Regular object file 305 ctx.objectFiles.push_back(cast<ELFFileBase>(file)); 306 cast<ObjFile<ELFT>>(file)->parse(); 307 } 308 309 // Add symbols in File to the symbol table. 310 void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); } 311 312 // Concatenates arguments to construct a string representing an error location. 313 static std::string createFileLineMsg(StringRef path, unsigned line) { 314 std::string filename = std::string(path::filename(path)); 315 std::string lineno = ":" + std::to_string(line); 316 if (filename == path) 317 return filename + lineno; 318 return filename + lineno + " (" + path.str() + lineno + ")"; 319 } 320 321 template <class ELFT> 322 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym, 323 InputSectionBase &sec, uint64_t offset) { 324 // In DWARF, functions and variables are stored to different places. 325 // First, look up a function for a given offset. 326 if (std::optional<DILineInfo> info = file.getDILineInfo(&sec, offset)) 327 return createFileLineMsg(info->FileName, info->Line); 328 329 // If it failed, look up again as a variable. 330 if (std::optional<std::pair<std::string, unsigned>> fileLine = 331 file.getVariableLoc(sym.getName())) 332 return createFileLineMsg(fileLine->first, fileLine->second); 333 334 // File.sourceFile contains STT_FILE symbol, and that is a last resort. 335 return std::string(file.sourceFile); 336 } 337 338 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec, 339 uint64_t offset) { 340 if (kind() != ObjKind) 341 return ""; 342 switch (ekind) { 343 default: 344 llvm_unreachable("Invalid kind"); 345 case ELF32LEKind: 346 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset); 347 case ELF32BEKind: 348 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset); 349 case ELF64LEKind: 350 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset); 351 case ELF64BEKind: 352 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset); 353 } 354 } 355 356 StringRef InputFile::getNameForScript() const { 357 if (archiveName.empty()) 358 return getName(); 359 360 if (nameForScriptCache.empty()) 361 nameForScriptCache = (archiveName + Twine(':') + getName()).str(); 362 363 return nameForScriptCache; 364 } 365 366 // An ELF object file may contain a `.deplibs` section. If it exists, the 367 // section contains a list of library specifiers such as `m` for libm. This 368 // function resolves a given name by finding the first matching library checking 369 // the various ways that a library can be specified to LLD. This ELF extension 370 // is a form of autolinking and is called `dependent libraries`. It is currently 371 // unique to LLVM and lld. 372 static void addDependentLibrary(StringRef specifier, const InputFile *f) { 373 if (!config->dependentLibraries) 374 return; 375 if (std::optional<std::string> s = searchLibraryBaseName(specifier)) 376 ctx.driver.addFile(saver().save(*s), /*withLOption=*/true); 377 else if (std::optional<std::string> s = findFromSearchPaths(specifier)) 378 ctx.driver.addFile(saver().save(*s), /*withLOption=*/true); 379 else if (fs::exists(specifier)) 380 ctx.driver.addFile(specifier, /*withLOption=*/false); 381 else 382 error(toString(f) + 383 ": unable to find library from dependent library specifier: " + 384 specifier); 385 } 386 387 // Record the membership of a section group so that in the garbage collection 388 // pass, section group members are kept or discarded as a unit. 389 template <class ELFT> 390 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections, 391 ArrayRef<typename ELFT::Word> entries) { 392 bool hasAlloc = false; 393 for (uint32_t index : entries.slice(1)) { 394 if (index >= sections.size()) 395 return; 396 if (InputSectionBase *s = sections[index]) 397 if (s != &InputSection::discarded && s->flags & SHF_ALLOC) 398 hasAlloc = true; 399 } 400 401 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage 402 // collection. See the comment in markLive(). This rule retains .debug_types 403 // and .rela.debug_types. 404 if (!hasAlloc) 405 return; 406 407 // Connect the members in a circular doubly-linked list via 408 // nextInSectionGroup. 409 InputSectionBase *head; 410 InputSectionBase *prev = nullptr; 411 for (uint32_t index : entries.slice(1)) { 412 InputSectionBase *s = sections[index]; 413 if (!s || s == &InputSection::discarded) 414 continue; 415 if (prev) 416 prev->nextInSectionGroup = s; 417 else 418 head = s; 419 prev = s; 420 } 421 if (prev) 422 prev->nextInSectionGroup = head; 423 } 424 425 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() { 426 llvm::call_once(initDwarf, [this]() { 427 dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 428 std::make_unique<LLDDwarfObj<ELFT>>(this), "", 429 [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 430 [&](Error warning) { 431 warn(getName() + ": " + toString(std::move(warning))); 432 })); 433 }); 434 435 return dwarf.get(); 436 } 437 438 // Returns the pair of file name and line number describing location of data 439 // object (variable, array, etc) definition. 440 template <class ELFT> 441 std::optional<std::pair<std::string, unsigned>> 442 ObjFile<ELFT>::getVariableLoc(StringRef name) { 443 return getDwarf()->getVariableLoc(name); 444 } 445 446 // Returns source line information for a given offset 447 // using DWARF debug info. 448 template <class ELFT> 449 std::optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s, 450 uint64_t offset) { 451 // Detect SectionIndex for specified section. 452 uint64_t sectionIndex = object::SectionedAddress::UndefSection; 453 ArrayRef<InputSectionBase *> sections = s->file->getSections(); 454 for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) { 455 if (s == sections[curIndex]) { 456 sectionIndex = curIndex; 457 break; 458 } 459 } 460 461 return getDwarf()->getDILineInfo(offset, sectionIndex); 462 } 463 464 ELFFileBase::ELFFileBase(Kind k, ELFKind ekind, MemoryBufferRef mb) 465 : InputFile(k, mb) { 466 this->ekind = ekind; 467 } 468 469 template <typename Elf_Shdr> 470 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) { 471 for (const Elf_Shdr &sec : sections) 472 if (sec.sh_type == type) 473 return &sec; 474 return nullptr; 475 } 476 477 void ELFFileBase::init() { 478 switch (ekind) { 479 case ELF32LEKind: 480 init<ELF32LE>(fileKind); 481 break; 482 case ELF32BEKind: 483 init<ELF32BE>(fileKind); 484 break; 485 case ELF64LEKind: 486 init<ELF64LE>(fileKind); 487 break; 488 case ELF64BEKind: 489 init<ELF64BE>(fileKind); 490 break; 491 default: 492 llvm_unreachable("getELFKind"); 493 } 494 } 495 496 template <class ELFT> void ELFFileBase::init(InputFile::Kind k) { 497 using Elf_Shdr = typename ELFT::Shdr; 498 using Elf_Sym = typename ELFT::Sym; 499 500 // Initialize trivial attributes. 501 const ELFFile<ELFT> &obj = getObj<ELFT>(); 502 emachine = obj.getHeader().e_machine; 503 osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI]; 504 abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION]; 505 506 ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this); 507 elfShdrs = sections.data(); 508 numELFShdrs = sections.size(); 509 510 // Find a symbol table. 511 const Elf_Shdr *symtabSec = 512 findSection(sections, k == SharedKind ? SHT_DYNSYM : SHT_SYMTAB); 513 514 if (!symtabSec) 515 return; 516 517 // Initialize members corresponding to a symbol table. 518 firstGlobal = symtabSec->sh_info; 519 520 ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this); 521 if (firstGlobal == 0 || firstGlobal > eSyms.size()) 522 fatal(toString(this) + ": invalid sh_info in symbol table"); 523 524 elfSyms = reinterpret_cast<const void *>(eSyms.data()); 525 numELFSyms = uint32_t(eSyms.size()); 526 stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this); 527 } 528 529 template <class ELFT> 530 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const { 531 return CHECK( 532 this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable), 533 this); 534 } 535 536 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) { 537 object::ELFFile<ELFT> obj = this->getObj(); 538 // Read a section table. justSymbols is usually false. 539 if (this->justSymbols) { 540 initializeJustSymbols(); 541 initializeSymbols(obj); 542 return; 543 } 544 545 // Handle dependent libraries and selection of section groups as these are not 546 // done in parallel. 547 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>(); 548 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this); 549 uint64_t size = objSections.size(); 550 sections.resize(size); 551 for (size_t i = 0; i != size; ++i) { 552 const Elf_Shdr &sec = objSections[i]; 553 if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) { 554 StringRef name = check(obj.getSectionName(sec, shstrtab)); 555 ArrayRef<char> data = CHECK( 556 this->getObj().template getSectionContentsAsArray<char>(sec), this); 557 if (!data.empty() && data.back() != '\0') { 558 error( 559 toString(this) + 560 ": corrupted dependent libraries section (unterminated string): " + 561 name); 562 } else { 563 for (const char *d = data.begin(), *e = data.end(); d < e;) { 564 StringRef s(d); 565 addDependentLibrary(s, this); 566 d += s.size() + 1; 567 } 568 } 569 this->sections[i] = &InputSection::discarded; 570 continue; 571 } 572 573 if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) { 574 ARMAttributeParser attributes; 575 ArrayRef<uint8_t> contents = 576 check(this->getObj().getSectionContents(sec)); 577 StringRef name = check(obj.getSectionName(sec, shstrtab)); 578 this->sections[i] = &InputSection::discarded; 579 if (Error e = 580 attributes.parse(contents, ekind == ELF32LEKind ? support::little 581 : support::big)) { 582 InputSection isec(*this, sec, name); 583 warn(toString(&isec) + ": " + llvm::toString(std::move(e))); 584 } else { 585 updateSupportedARMFeatures(attributes); 586 updateARMVFPArgs(attributes, this); 587 588 // FIXME: Retain the first attribute section we see. The eglibc ARM 589 // dynamic loaders require the presence of an attribute section for 590 // dlopen to work. In a full implementation we would merge all attribute 591 // sections. 592 if (in.attributes == nullptr) { 593 in.attributes = std::make_unique<InputSection>(*this, sec, name); 594 this->sections[i] = in.attributes.get(); 595 } 596 } 597 } 598 599 if (sec.sh_type != SHT_GROUP) 600 continue; 601 StringRef signature = getShtGroupSignature(objSections, sec); 602 ArrayRef<Elf_Word> entries = 603 CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this); 604 if (entries.empty()) 605 fatal(toString(this) + ": empty SHT_GROUP"); 606 607 Elf_Word flag = entries[0]; 608 if (flag && flag != GRP_COMDAT) 609 fatal(toString(this) + ": unsupported SHT_GROUP format"); 610 611 bool keepGroup = 612 (flag & GRP_COMDAT) == 0 || ignoreComdats || 613 symtab.comdatGroups.try_emplace(CachedHashStringRef(signature), this) 614 .second; 615 if (keepGroup) { 616 if (config->relocatable) 617 this->sections[i] = createInputSection( 618 i, sec, check(obj.getSectionName(sec, shstrtab))); 619 continue; 620 } 621 622 // Otherwise, discard group members. 623 for (uint32_t secIndex : entries.slice(1)) { 624 if (secIndex >= size) 625 fatal(toString(this) + 626 ": invalid section index in group: " + Twine(secIndex)); 627 this->sections[secIndex] = &InputSection::discarded; 628 } 629 } 630 631 // Read a symbol table. 632 initializeSymbols(obj); 633 } 634 635 // Sections with SHT_GROUP and comdat bits define comdat section groups. 636 // They are identified and deduplicated by group name. This function 637 // returns a group name. 638 template <class ELFT> 639 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections, 640 const Elf_Shdr &sec) { 641 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>(); 642 if (sec.sh_info >= symbols.size()) 643 fatal(toString(this) + ": invalid symbol index"); 644 const typename ELFT::Sym &sym = symbols[sec.sh_info]; 645 return CHECK(sym.getName(this->stringTable), this); 646 } 647 648 template <class ELFT> 649 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) { 650 // On a regular link we don't merge sections if -O0 (default is -O1). This 651 // sometimes makes the linker significantly faster, although the output will 652 // be bigger. 653 // 654 // Doing the same for -r would create a problem as it would combine sections 655 // with different sh_entsize. One option would be to just copy every SHF_MERGE 656 // section as is to the output. While this would produce a valid ELF file with 657 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when 658 // they see two .debug_str. We could have separate logic for combining 659 // SHF_MERGE sections based both on their name and sh_entsize, but that seems 660 // to be more trouble than it is worth. Instead, we just use the regular (-O1) 661 // logic for -r. 662 if (config->optimize == 0 && !config->relocatable) 663 return false; 664 665 // A mergeable section with size 0 is useless because they don't have 666 // any data to merge. A mergeable string section with size 0 can be 667 // argued as invalid because it doesn't end with a null character. 668 // We'll avoid a mess by handling them as if they were non-mergeable. 669 if (sec.sh_size == 0) 670 return false; 671 672 // Check for sh_entsize. The ELF spec is not clear about the zero 673 // sh_entsize. It says that "the member [sh_entsize] contains 0 if 674 // the section does not hold a table of fixed-size entries". We know 675 // that Rust 1.13 produces a string mergeable section with a zero 676 // sh_entsize. Here we just accept it rather than being picky about it. 677 uint64_t entSize = sec.sh_entsize; 678 if (entSize == 0) 679 return false; 680 if (sec.sh_size % entSize) 681 fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" + 682 Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" + 683 Twine(entSize) + ")"); 684 685 if (sec.sh_flags & SHF_WRITE) 686 fatal(toString(this) + ":(" + name + 687 "): writable SHF_MERGE section is not supported"); 688 689 return true; 690 } 691 692 // This is for --just-symbols. 693 // 694 // --just-symbols is a very minor feature that allows you to link your 695 // output against other existing program, so that if you load both your 696 // program and the other program into memory, your output can refer the 697 // other program's symbols. 698 // 699 // When the option is given, we link "just symbols". The section table is 700 // initialized with null pointers. 701 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() { 702 sections.resize(numELFShdrs); 703 } 704 705 template <class ELFT> 706 void ObjFile<ELFT>::initializeSections(bool ignoreComdats, 707 const llvm::object::ELFFile<ELFT> &obj) { 708 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>(); 709 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this); 710 uint64_t size = objSections.size(); 711 SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups; 712 for (size_t i = 0; i != size; ++i) { 713 if (this->sections[i] == &InputSection::discarded) 714 continue; 715 const Elf_Shdr &sec = objSections[i]; 716 717 // SHF_EXCLUDE'ed sections are discarded by the linker. However, 718 // if -r is given, we'll let the final link discard such sections. 719 // This is compatible with GNU. 720 if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) { 721 if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE) 722 cgProfileSectionIndex = i; 723 if (sec.sh_type == SHT_LLVM_ADDRSIG) { 724 // We ignore the address-significance table if we know that the object 725 // file was created by objcopy or ld -r. This is because these tools 726 // will reorder the symbols in the symbol table, invalidating the data 727 // in the address-significance table, which refers to symbols by index. 728 if (sec.sh_link != 0) 729 this->addrsigSec = &sec; 730 else if (config->icf == ICFLevel::Safe) 731 warn(toString(this) + 732 ": --icf=safe conservatively ignores " 733 "SHT_LLVM_ADDRSIG [index " + 734 Twine(i) + 735 "] with sh_link=0 " 736 "(likely created using objcopy or ld -r)"); 737 } 738 this->sections[i] = &InputSection::discarded; 739 continue; 740 } 741 742 switch (sec.sh_type) { 743 case SHT_GROUP: { 744 if (!config->relocatable) 745 sections[i] = &InputSection::discarded; 746 StringRef signature = 747 cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable)); 748 ArrayRef<Elf_Word> entries = 749 cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec)); 750 if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats || 751 symtab.comdatGroups.find(CachedHashStringRef(signature))->second == 752 this) 753 selectedGroups.push_back(entries); 754 break; 755 } 756 case SHT_SYMTAB_SHNDX: 757 shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this); 758 break; 759 case SHT_SYMTAB: 760 case SHT_STRTAB: 761 case SHT_REL: 762 case SHT_RELA: 763 case SHT_NULL: 764 break; 765 case SHT_PROGBITS: { 766 this->sections[i] = createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab))); 767 StringRef name = check(obj.getSectionName(sec, shstrtab)); 768 ArrayRef<char> data = 769 CHECK(obj.template getSectionContentsAsArray<char>(sec), this); 770 parseGNUWarning(name, data, sec.sh_size); 771 } 772 break; 773 case SHT_LLVM_SYMPART: 774 ctx.hasSympart.store(true, std::memory_order_relaxed); 775 [[fallthrough]]; 776 default: 777 this->sections[i] = 778 createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab))); 779 } 780 } 781 782 // We have a second loop. It is used to: 783 // 1) handle SHF_LINK_ORDER sections. 784 // 2) create SHT_REL[A] sections. In some cases the section header index of a 785 // relocation section may be smaller than that of the relocated section. In 786 // such cases, the relocation section would attempt to reference a target 787 // section that has not yet been created. For simplicity, delay creation of 788 // relocation sections until now. 789 for (size_t i = 0; i != size; ++i) { 790 if (this->sections[i] == &InputSection::discarded) 791 continue; 792 const Elf_Shdr &sec = objSections[i]; 793 794 if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) { 795 // Find a relocation target section and associate this section with that. 796 // Target may have been discarded if it is in a different section group 797 // and the group is discarded, even though it's a violation of the spec. 798 // We handle that situation gracefully by discarding dangling relocation 799 // sections. 800 const uint32_t info = sec.sh_info; 801 InputSectionBase *s = getRelocTarget(i, sec, info); 802 if (!s) 803 continue; 804 805 // ELF spec allows mergeable sections with relocations, but they are rare, 806 // and it is in practice hard to merge such sections by contents, because 807 // applying relocations at end of linking changes section contents. So, we 808 // simply handle such sections as non-mergeable ones. Degrading like this 809 // is acceptable because section merging is optional. 810 if (auto *ms = dyn_cast<MergeInputSection>(s)) { 811 s = makeThreadLocal<InputSection>( 812 ms->file, ms->flags, ms->type, ms->addralign, 813 ms->contentMaybeDecompress(), ms->name); 814 sections[info] = s; 815 } 816 817 if (s->relSecIdx != 0) 818 error( 819 toString(s) + 820 ": multiple relocation sections to one section are not supported"); 821 s->relSecIdx = i; 822 823 // Relocation sections are usually removed from the output, so return 824 // `nullptr` for the normal case. However, if -r or --emit-relocs is 825 // specified, we need to copy them to the output. (Some post link analysis 826 // tools specify --emit-relocs to obtain the information.) 827 if (config->copyRelocs) { 828 auto *isec = makeThreadLocal<InputSection>( 829 *this, sec, check(obj.getSectionName(sec, shstrtab))); 830 // If the relocated section is discarded (due to /DISCARD/ or 831 // --gc-sections), the relocation section should be discarded as well. 832 s->dependentSections.push_back(isec); 833 sections[i] = isec; 834 } 835 continue; 836 } 837 838 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have 839 // the flag. 840 if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER)) 841 continue; 842 843 InputSectionBase *linkSec = nullptr; 844 if (sec.sh_link < size) 845 linkSec = this->sections[sec.sh_link]; 846 if (!linkSec) 847 fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link)); 848 849 // A SHF_LINK_ORDER section is discarded if its linked-to section is 850 // discarded. 851 InputSection *isec = cast<InputSection>(this->sections[i]); 852 linkSec->dependentSections.push_back(isec); 853 if (!isa<InputSection>(linkSec)) 854 error("a section " + isec->name + 855 " with SHF_LINK_ORDER should not refer a non-regular section: " + 856 toString(linkSec)); 857 } 858 859 for (ArrayRef<Elf_Word> entries : selectedGroups) 860 handleSectionGroup<ELFT>(this->sections, entries); 861 } 862 863 // If a source file is compiled with x86 hardware-assisted call flow control 864 // enabled, the generated object file contains feature flags indicating that 865 // fact. This function reads the feature flags and returns it. 866 // 867 // Essentially we want to read a single 32-bit value in this function, but this 868 // function is rather complicated because the value is buried deep inside a 869 // .note.gnu.property section. 870 // 871 // The section consists of one or more NOTE records. Each NOTE record consists 872 // of zero or more type-length-value fields. We want to find a field of a 873 // certain type. It seems a bit too much to just store a 32-bit value, perhaps 874 // the ABI is unnecessarily complicated. 875 template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) { 876 using Elf_Nhdr = typename ELFT::Nhdr; 877 using Elf_Note = typename ELFT::Note; 878 879 uint32_t featuresSet = 0; 880 ArrayRef<uint8_t> data = sec.content(); 881 auto reportFatal = [&](const uint8_t *place, const char *msg) { 882 fatal(toString(sec.file) + ":(" + sec.name + "+0x" + 883 Twine::utohexstr(place - sec.content().data()) + "): " + msg); 884 }; 885 while (!data.empty()) { 886 // Read one NOTE record. 887 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data()); 888 if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize()) 889 reportFatal(data.data(), "data is too short"); 890 891 Elf_Note note(*nhdr); 892 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") { 893 data = data.slice(nhdr->getSize()); 894 continue; 895 } 896 897 uint32_t featureAndType = config->emachine == EM_AARCH64 898 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND 899 : GNU_PROPERTY_X86_FEATURE_1_AND; 900 901 // Read a body of a NOTE record, which consists of type-length-value fields. 902 ArrayRef<uint8_t> desc = note.getDesc(); 903 while (!desc.empty()) { 904 const uint8_t *place = desc.data(); 905 if (desc.size() < 8) 906 reportFatal(place, "program property is too short"); 907 uint32_t type = read32<ELFT::TargetEndianness>(desc.data()); 908 uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4); 909 desc = desc.slice(8); 910 if (desc.size() < size) 911 reportFatal(place, "program property is too short"); 912 913 if (type == featureAndType) { 914 // We found a FEATURE_1_AND field. There may be more than one of these 915 // in a .note.gnu.property section, for a relocatable object we 916 // accumulate the bits set. 917 if (size < 4) 918 reportFatal(place, "FEATURE_1_AND entry is too short"); 919 featuresSet |= read32<ELFT::TargetEndianness>(desc.data()); 920 } 921 922 // Padding is present in the note descriptor, if necessary. 923 desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size)); 924 } 925 926 // Go to next NOTE record to look for more FEATURE_1_AND descriptions. 927 data = data.slice(nhdr->getSize()); 928 } 929 930 return featuresSet; 931 } 932 933 template <class ELFT> 934 InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, 935 const Elf_Shdr &sec, 936 uint32_t info) { 937 if (info < this->sections.size()) { 938 InputSectionBase *target = this->sections[info]; 939 940 // Strictly speaking, a relocation section must be included in the 941 // group of the section it relocates. However, LLVM 3.3 and earlier 942 // would fail to do so, so we gracefully handle that case. 943 if (target == &InputSection::discarded) 944 return nullptr; 945 946 if (target != nullptr) 947 return target; 948 } 949 950 error(toString(this) + Twine(": relocation section (index ") + Twine(idx) + 951 ") has invalid sh_info (" + Twine(info) + ")"); 952 return nullptr; 953 } 954 955 // The function may be called concurrently for different input files. For 956 // allocation, prefer makeThreadLocal which does not require holding a lock. 957 template <class ELFT> 958 InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx, 959 const Elf_Shdr &sec, 960 StringRef name) { 961 if (name.startswith(".n")) { 962 // The GNU linker uses .note.GNU-stack section as a marker indicating 963 // that the code in the object file does not expect that the stack is 964 // executable (in terms of NX bit). If all input files have the marker, 965 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to 966 // make the stack non-executable. Most object files have this section as 967 // of 2017. 968 // 969 // But making the stack non-executable is a norm today for security 970 // reasons. Failure to do so may result in a serious security issue. 971 // Therefore, we make LLD always add PT_GNU_STACK unless it is 972 // explicitly told to do otherwise (by -z execstack). Because the stack 973 // executable-ness is controlled solely by command line options, 974 // .note.GNU-stack sections are simply ignored. 975 if (name == ".note.GNU-stack") 976 return &InputSection::discarded; 977 978 // Object files that use processor features such as Intel Control-Flow 979 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a 980 // .note.gnu.property section containing a bitfield of feature bits like the 981 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag. 982 // 983 // Since we merge bitmaps from multiple object files to create a new 984 // .note.gnu.property containing a single AND'ed bitmap, we discard an input 985 // file's .note.gnu.property section. 986 if (name == ".note.gnu.property") { 987 this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name)); 988 return &InputSection::discarded; 989 } 990 991 // Split stacks is a feature to support a discontiguous stack, 992 // commonly used in the programming language Go. For the details, 993 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled 994 // for split stack will include a .note.GNU-split-stack section. 995 if (name == ".note.GNU-split-stack") { 996 if (config->relocatable) { 997 error( 998 "cannot mix split-stack and non-split-stack in a relocatable link"); 999 return &InputSection::discarded; 1000 } 1001 this->splitStack = true; 1002 return &InputSection::discarded; 1003 } 1004 1005 // An object file compiled for split stack, but where some of the 1006 // functions were compiled with the no_split_stack_attribute will 1007 // include a .note.GNU-no-split-stack section. 1008 if (name == ".note.GNU-no-split-stack") { 1009 this->someNoSplitStack = true; 1010 return &InputSection::discarded; 1011 } 1012 1013 // Strip existing .note.gnu.build-id sections so that the output won't have 1014 // more than one build-id. This is not usually a problem because input 1015 // object files normally don't have .build-id sections, but you can create 1016 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard 1017 // against it. 1018 if (name == ".note.gnu.build-id") 1019 return &InputSection::discarded; 1020 } 1021 1022 // The linker merges EH (exception handling) frames and creates a 1023 // .eh_frame_hdr section for runtime. So we handle them with a special 1024 // class. For relocatable outputs, they are just passed through. 1025 if (name == ".eh_frame" && !config->relocatable) 1026 return makeThreadLocal<EhInputSection>(*this, sec, name); 1027 1028 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name)) 1029 return makeThreadLocal<MergeInputSection>(*this, sec, name); 1030 return makeThreadLocal<InputSection>(*this, sec, name); 1031 } 1032 1033 // Initialize this->Symbols. this->Symbols is a parallel array as 1034 // its corresponding ELF symbol table. 1035 template <class ELFT> 1036 void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) { 1037 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1038 if (numSymbols == 0) { 1039 numSymbols = eSyms.size(); 1040 symbols = std::make_unique<Symbol *[]>(numSymbols); 1041 } 1042 1043 // Some entries have been filled by LazyObjFile. 1044 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 1045 if (!symbols[i]) 1046 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 1047 1048 // Perform symbol resolution on non-local symbols. 1049 SmallVector<unsigned, 32> undefineds; 1050 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 1051 const Elf_Sym &eSym = eSyms[i]; 1052 uint32_t secIdx = eSym.st_shndx; 1053 if (secIdx == SHN_UNDEF) { 1054 undefineds.push_back(i); 1055 continue; 1056 } 1057 1058 uint8_t binding = eSym.getBinding(); 1059 uint8_t stOther = eSym.st_other; 1060 uint8_t type = eSym.getType(); 1061 uint64_t value = eSym.st_value; 1062 uint64_t size = eSym.st_size; 1063 1064 Symbol *sym = symbols[i]; 1065 sym->isUsedInRegularObj = true; 1066 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) { 1067 if (value == 0 || value >= UINT32_MAX) 1068 fatal(toString(this) + ": common symbol '" + sym->getName() + 1069 "' has invalid alignment: " + Twine(value)); 1070 hasCommonSyms = true; 1071 sym->resolve( 1072 CommonSymbol{this, StringRef(), binding, stOther, type, value, size}); 1073 continue; 1074 } 1075 1076 // Handle global defined symbols. Defined::section will be set in postParse. 1077 sym->resolve(Defined{this, StringRef(), binding, stOther, type, value, size, 1078 nullptr}); 1079 } 1080 1081 // Undefined symbols (excluding those defined relative to non-prevailing 1082 // sections) can trigger recursive extract. Process defined symbols first so 1083 // that the relative order between a defined symbol and an undefined symbol 1084 // does not change the symbol resolution behavior. In addition, a set of 1085 // interconnected symbols will all be resolved to the same file, instead of 1086 // being resolved to different files. 1087 for (unsigned i : undefineds) { 1088 const Elf_Sym &eSym = eSyms[i]; 1089 Symbol *sym = symbols[i]; 1090 sym->resolve(Undefined{this, StringRef(), eSym.getBinding(), eSym.st_other, 1091 eSym.getType()}); 1092 sym->isUsedInRegularObj = true; 1093 sym->referenced = true; 1094 } 1095 } 1096 1097 template <class ELFT> 1098 void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) { 1099 if (!justSymbols) 1100 initializeSections(ignoreComdats, getObj()); 1101 1102 if (!firstGlobal) 1103 return; 1104 SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal); 1105 memset(locals, 0, sizeof(SymbolUnion) * firstGlobal); 1106 1107 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1108 for (size_t i = 0, end = firstGlobal; i != end; ++i) { 1109 const Elf_Sym &eSym = eSyms[i]; 1110 uint32_t secIdx = eSym.st_shndx; 1111 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1112 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1113 else if (secIdx >= SHN_LORESERVE) 1114 secIdx = 0; 1115 if (LLVM_UNLIKELY(secIdx >= sections.size())) 1116 fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 1117 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL)) 1118 error(toString(this) + ": non-local symbol (" + Twine(i) + 1119 ") found at index < .symtab's sh_info (" + Twine(end) + ")"); 1120 1121 InputSectionBase *sec = sections[secIdx]; 1122 uint8_t type = eSym.getType(); 1123 if (type == STT_FILE) 1124 sourceFile = CHECK(eSym.getName(stringTable), this); 1125 if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name)) 1126 fatal(toString(this) + ": invalid symbol name offset"); 1127 StringRef name(stringTable.data() + eSym.st_name); 1128 1129 symbols[i] = reinterpret_cast<Symbol *>(locals + i); 1130 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded) 1131 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type, 1132 /*discardedSecIdx=*/secIdx); 1133 else 1134 new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type, 1135 eSym.st_value, eSym.st_size, sec); 1136 symbols[i]->partition = 1; 1137 symbols[i]->isUsedInRegularObj = true; 1138 } 1139 } 1140 1141 // Called after all ObjFile::parse is called for all ObjFiles. This checks 1142 // duplicate symbols and may do symbol property merge in the future. 1143 template <class ELFT> void ObjFile<ELFT>::postParse() { 1144 static std::mutex mu; 1145 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1146 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 1147 const Elf_Sym &eSym = eSyms[i]; 1148 Symbol &sym = *symbols[i]; 1149 uint32_t secIdx = eSym.st_shndx; 1150 uint8_t binding = eSym.getBinding(); 1151 if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK && 1152 binding != STB_GNU_UNIQUE)) 1153 errorOrWarn(toString(this) + ": symbol (" + Twine(i) + 1154 ") has invalid binding: " + Twine((int)binding)); 1155 1156 // st_value of STT_TLS represents the assigned offset, not the actual 1157 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can 1158 // only be referenced by special TLS relocations. It is usually an error if 1159 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa. 1160 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS && 1161 eSym.getType() != STT_NOTYPE) 1162 errorOrWarn("TLS attribute mismatch: " + toString(sym) + "\n>>> in " + 1163 toString(sym.file) + "\n>>> in " + toString(this)); 1164 1165 // Handle non-COMMON defined symbol below. !sym.file allows a symbol 1166 // assignment to redefine a symbol without an error. 1167 if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF || 1168 secIdx == SHN_COMMON) 1169 continue; 1170 1171 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1172 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1173 else if (secIdx >= SHN_LORESERVE) 1174 secIdx = 0; 1175 if (LLVM_UNLIKELY(secIdx >= sections.size())) 1176 fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 1177 InputSectionBase *sec = sections[secIdx]; 1178 if (sec == &InputSection::discarded) { 1179 if (sym.traced) { 1180 printTraceSymbol(Undefined{this, sym.getName(), sym.binding, 1181 sym.stOther, sym.type, secIdx}, 1182 sym.getName()); 1183 } 1184 if (sym.file == this) { 1185 std::lock_guard<std::mutex> lock(mu); 1186 ctx.nonPrevailingSyms.emplace_back(&sym, secIdx); 1187 } 1188 continue; 1189 } 1190 1191 if (sym.file == this) { 1192 cast<Defined>(sym).section = sec; 1193 continue; 1194 } 1195 1196 if (sym.binding == STB_WEAK || binding == STB_WEAK) 1197 continue; 1198 std::lock_guard<std::mutex> lock(mu); 1199 ctx.duplicates.push_back({&sym, this, sec, eSym.st_value}); 1200 } 1201 } 1202 1203 // The handling of tentative definitions (COMMON symbols) in archives is murky. 1204 // A tentative definition will be promoted to a global definition if there are 1205 // no non-tentative definitions to dominate it. When we hold a tentative 1206 // definition to a symbol and are inspecting archive members for inclusion 1207 // there are 2 ways we can proceed: 1208 // 1209 // 1) Consider the tentative definition a 'real' definition (ie promotion from 1210 // tentative to real definition has already happened) and not inspect 1211 // archive members for Global/Weak definitions to replace the tentative 1212 // definition. An archive member would only be included if it satisfies some 1213 // other undefined symbol. This is the behavior Gold uses. 1214 // 1215 // 2) Consider the tentative definition as still undefined (ie the promotion to 1216 // a real definition happens only after all symbol resolution is done). 1217 // The linker searches archive members for STB_GLOBAL definitions to 1218 // replace the tentative definition with. This is the behavior used by 1219 // GNU ld. 1220 // 1221 // The second behavior is inherited from SysVR4, which based it on the FORTRAN 1222 // COMMON BLOCK model. This behavior is needed for proper initialization in old 1223 // (pre F90) FORTRAN code that is packaged into an archive. 1224 // 1225 // The following functions search archive members for definitions to replace 1226 // tentative definitions (implementing behavior 2). 1227 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName, 1228 StringRef archiveName) { 1229 IRSymtabFile symtabFile = check(readIRSymtab(mb)); 1230 for (const irsymtab::Reader::SymbolRef &sym : 1231 symtabFile.TheReader.symbols()) { 1232 if (sym.isGlobal() && sym.getName() == symName) 1233 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon(); 1234 } 1235 return false; 1236 } 1237 1238 template <class ELFT> 1239 static bool isNonCommonDef(ELFKind ekind, MemoryBufferRef mb, StringRef symName, 1240 StringRef archiveName) { 1241 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ekind, mb, archiveName); 1242 obj->init(); 1243 StringRef stringtable = obj->getStringTable(); 1244 1245 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) { 1246 Expected<StringRef> name = sym.getName(stringtable); 1247 if (name && name.get() == symName) 1248 return sym.isDefined() && sym.getBinding() == STB_GLOBAL && 1249 !sym.isCommon(); 1250 } 1251 return false; 1252 } 1253 1254 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1255 StringRef archiveName) { 1256 switch (getELFKind(mb, archiveName)) { 1257 case ELF32LEKind: 1258 return isNonCommonDef<ELF32LE>(ELF32LEKind, mb, symName, archiveName); 1259 case ELF32BEKind: 1260 return isNonCommonDef<ELF32BE>(ELF32BEKind, mb, symName, archiveName); 1261 case ELF64LEKind: 1262 return isNonCommonDef<ELF64LE>(ELF64LEKind, mb, symName, archiveName); 1263 case ELF64BEKind: 1264 return isNonCommonDef<ELF64BE>(ELF64BEKind, mb, symName, archiveName); 1265 default: 1266 llvm_unreachable("getELFKind"); 1267 } 1268 } 1269 1270 unsigned SharedFile::vernauxNum; 1271 1272 SharedFile::SharedFile(MemoryBufferRef m, StringRef defaultSoName) 1273 : ELFFileBase(SharedKind, getELFKind(m, ""), m), soName(defaultSoName), 1274 isNeeded(!config->asNeeded) {} 1275 1276 // Parse the version definitions in the object file if present, and return a 1277 // vector whose nth element contains a pointer to the Elf_Verdef for version 1278 // identifier n. Version identifiers that are not definitions map to nullptr. 1279 template <typename ELFT> 1280 static SmallVector<const void *, 0> 1281 parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) { 1282 if (!sec) 1283 return {}; 1284 1285 // Build the Verdefs array by following the chain of Elf_Verdef objects 1286 // from the start of the .gnu.version_d section. 1287 SmallVector<const void *, 0> verdefs; 1288 const uint8_t *verdef = base + sec->sh_offset; 1289 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) { 1290 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef); 1291 verdef += curVerdef->vd_next; 1292 unsigned verdefIndex = curVerdef->vd_ndx; 1293 if (verdefIndex >= verdefs.size()) 1294 verdefs.resize(verdefIndex + 1); 1295 verdefs[verdefIndex] = curVerdef; 1296 } 1297 return verdefs; 1298 } 1299 1300 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined 1301 // symbol. We detect fatal issues which would cause vulnerabilities, but do not 1302 // implement sophisticated error checking like in llvm-readobj because the value 1303 // of such diagnostics is low. 1304 template <typename ELFT> 1305 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj, 1306 const typename ELFT::Shdr *sec) { 1307 if (!sec) 1308 return {}; 1309 std::vector<uint32_t> verneeds; 1310 ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this); 1311 const uint8_t *verneedBuf = data.begin(); 1312 for (unsigned i = 0; i != sec->sh_info; ++i) { 1313 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) 1314 fatal(toString(this) + " has an invalid Verneed"); 1315 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf); 1316 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux; 1317 for (unsigned j = 0; j != vn->vn_cnt; ++j) { 1318 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) 1319 fatal(toString(this) + " has an invalid Vernaux"); 1320 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf); 1321 if (aux->vna_name >= this->stringTable.size()) 1322 fatal(toString(this) + " has a Vernaux with an invalid vna_name"); 1323 uint16_t version = aux->vna_other & VERSYM_VERSION; 1324 if (version >= verneeds.size()) 1325 verneeds.resize(version + 1); 1326 verneeds[version] = aux->vna_name; 1327 vernauxBuf += aux->vna_next; 1328 } 1329 verneedBuf += vn->vn_next; 1330 } 1331 return verneeds; 1332 } 1333 1334 // We do not usually care about alignments of data in shared object 1335 // files because the loader takes care of it. However, if we promote a 1336 // DSO symbol to point to .bss due to copy relocation, we need to keep 1337 // the original alignment requirements. We infer it in this function. 1338 template <typename ELFT> 1339 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections, 1340 const typename ELFT::Sym &sym) { 1341 uint64_t ret = UINT64_MAX; 1342 if (sym.st_value) 1343 ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value); 1344 if (0 < sym.st_shndx && sym.st_shndx < sections.size()) 1345 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign); 1346 return (ret > UINT32_MAX) ? 0 : ret; 1347 } 1348 1349 // Fully parse the shared object file. 1350 // 1351 // This function parses symbol versions. If a DSO has version information, 1352 // the file has a ".gnu.version_d" section which contains symbol version 1353 // definitions. Each symbol is associated to one version through a table in 1354 // ".gnu.version" section. That table is a parallel array for the symbol 1355 // table, and each table entry contains an index in ".gnu.version_d". 1356 // 1357 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 1358 // VER_NDX_GLOBAL. There's no table entry for these special versions in 1359 // ".gnu.version_d". 1360 // 1361 // The file format for symbol versioning is perhaps a bit more complicated 1362 // than necessary, but you can easily understand the code if you wrap your 1363 // head around the data structure described above. 1364 template <class ELFT> void SharedFile::parse() { 1365 using Elf_Dyn = typename ELFT::Dyn; 1366 using Elf_Shdr = typename ELFT::Shdr; 1367 using Elf_Sym = typename ELFT::Sym; 1368 using Elf_Verdef = typename ELFT::Verdef; 1369 using Elf_Versym = typename ELFT::Versym; 1370 1371 ArrayRef<Elf_Dyn> dynamicTags; 1372 const ELFFile<ELFT> obj = this->getObj<ELFT>(); 1373 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>(); 1374 1375 StringRef sectionStringTable = 1376 CHECK(obj.getSectionStringTable(sections), this); 1377 1378 const Elf_Shdr *versymSec = nullptr; 1379 const Elf_Shdr *verdefSec = nullptr; 1380 const Elf_Shdr *verneedSec = nullptr; 1381 1382 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 1383 for (const Elf_Shdr &sec : sections) { 1384 switch (sec.sh_type) { 1385 default: 1386 continue; 1387 case SHT_DYNAMIC: 1388 dynamicTags = 1389 CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this); 1390 break; 1391 case SHT_GNU_versym: 1392 versymSec = &sec; 1393 break; 1394 case SHT_GNU_verdef: 1395 verdefSec = &sec; 1396 break; 1397 case SHT_GNU_verneed: 1398 verneedSec = &sec; 1399 break; 1400 case SHT_PROGBITS: { 1401 StringRef name = CHECK(obj.getSectionName(sec, sectionStringTable), this); 1402 ArrayRef<char> data = 1403 CHECK(obj.template getSectionContentsAsArray<char>(sec), this); 1404 parseGNUWarning(name, data, sec.sh_size); 1405 break; 1406 } 1407 } 1408 } 1409 1410 if (versymSec && numELFSyms == 0) { 1411 error("SHT_GNU_versym should be associated with symbol table"); 1412 return; 1413 } 1414 1415 // Search for a DT_SONAME tag to initialize this->soName. 1416 for (const Elf_Dyn &dyn : dynamicTags) { 1417 if (dyn.d_tag == DT_NEEDED) { 1418 uint64_t val = dyn.getVal(); 1419 if (val >= this->stringTable.size()) 1420 fatal(toString(this) + ": invalid DT_NEEDED entry"); 1421 dtNeeded.push_back(this->stringTable.data() + val); 1422 } else if (dyn.d_tag == DT_SONAME) { 1423 uint64_t val = dyn.getVal(); 1424 if (val >= this->stringTable.size()) 1425 fatal(toString(this) + ": invalid DT_SONAME entry"); 1426 soName = this->stringTable.data() + val; 1427 } 1428 } 1429 1430 // DSOs are uniquified not by filename but by soname. 1431 DenseMap<CachedHashStringRef, SharedFile *>::iterator it; 1432 bool wasInserted; 1433 std::tie(it, wasInserted) = 1434 symtab.soNames.try_emplace(CachedHashStringRef(soName), this); 1435 1436 // If a DSO appears more than once on the command line with and without 1437 // --as-needed, --no-as-needed takes precedence over --as-needed because a 1438 // user can add an extra DSO with --no-as-needed to force it to be added to 1439 // the dependency list. 1440 it->second->isNeeded |= isNeeded; 1441 if (!wasInserted) 1442 return; 1443 1444 ctx.sharedFiles.push_back(this); 1445 1446 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec); 1447 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec); 1448 1449 // Parse ".gnu.version" section which is a parallel array for the symbol 1450 // table. If a given file doesn't have a ".gnu.version" section, we use 1451 // VER_NDX_GLOBAL. 1452 size_t size = numELFSyms - firstGlobal; 1453 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL); 1454 if (versymSec) { 1455 ArrayRef<Elf_Versym> versym = 1456 CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec), 1457 this) 1458 .slice(firstGlobal); 1459 for (size_t i = 0; i < size; ++i) 1460 versyms[i] = versym[i].vs_index; 1461 } 1462 1463 // System libraries can have a lot of symbols with versions. Using a 1464 // fixed buffer for computing the versions name (foo@ver) can save a 1465 // lot of allocations. 1466 SmallString<0> versionedNameBuffer; 1467 1468 // Add symbols to the symbol table. 1469 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>(); 1470 for (size_t i = 0, e = syms.size(); i != e; ++i) { 1471 const Elf_Sym &sym = syms[i]; 1472 1473 // ELF spec requires that all local symbols precede weak or global 1474 // symbols in each symbol table, and the index of first non-local symbol 1475 // is stored to sh_info. If a local symbol appears after some non-local 1476 // symbol, that's a violation of the spec. 1477 StringRef name = CHECK(sym.getName(stringTable), this); 1478 if (sym.getBinding() == STB_LOCAL) { 1479 errorOrWarn(toString(this) + ": invalid local symbol '" + name + 1480 "' in global part of symbol table"); 1481 continue; 1482 } 1483 1484 const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN; 1485 if (sym.isUndefined()) { 1486 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but 1487 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL. 1488 if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) { 1489 if (idx >= verneeds.size()) { 1490 error("corrupt input file: version need index " + Twine(idx) + 1491 " for symbol " + name + " is out of bounds\n>>> defined in " + 1492 toString(this)); 1493 continue; 1494 } 1495 StringRef verName = stringTable.data() + verneeds[idx]; 1496 versionedNameBuffer.clear(); 1497 name = saver().save( 1498 (name + "@" + verName).toStringRef(versionedNameBuffer)); 1499 } 1500 Symbol *s = symtab.addSymbol( 1501 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()}); 1502 s->exportDynamic = true; 1503 if (s->isUndefined() && sym.getBinding() != STB_WEAK && 1504 config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) 1505 requiredSymbols.push_back(s); 1506 continue; 1507 } 1508 1509 if (ver == VER_NDX_LOCAL || 1510 (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) { 1511 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the 1512 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns 1513 // VER_NDX_LOCAL. Workaround this bug. 1514 if (config->emachine == EM_MIPS && name == "_gp_disp") 1515 continue; 1516 error("corrupt input file: version definition index " + Twine(idx) + 1517 " for symbol " + name + " is out of bounds\n>>> defined in " + 1518 toString(this)); 1519 continue; 1520 } 1521 1522 uint32_t alignment = getAlignment<ELFT>(sections, sym); 1523 if (ver == idx) { 1524 auto *s = symtab.addSymbol( 1525 SharedSymbol{*this, name, sym.getBinding(), sym.st_other, 1526 sym.getType(), sym.st_value, sym.st_size, alignment}); 1527 if (s->file == this) 1528 s->verdefIndex = ver; 1529 } 1530 1531 // Also add the symbol with the versioned name to handle undefined symbols 1532 // with explicit versions. 1533 if (ver == VER_NDX_GLOBAL) 1534 continue; 1535 1536 StringRef verName = 1537 stringTable.data() + 1538 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name; 1539 versionedNameBuffer.clear(); 1540 name = (name + "@" + verName).toStringRef(versionedNameBuffer); 1541 auto *s = symtab.addSymbol( 1542 SharedSymbol{*this, saver().save(name), sym.getBinding(), sym.st_other, 1543 sym.getType(), sym.st_value, sym.st_size, alignment}); 1544 if (s->file == this) 1545 s->verdefIndex = idx; 1546 } 1547 } 1548 1549 static ELFKind getBitcodeELFKind(const Triple &t) { 1550 if (t.isLittleEndian()) 1551 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 1552 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 1553 } 1554 1555 static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) { 1556 switch (t.getArch()) { 1557 case Triple::aarch64: 1558 case Triple::aarch64_be: 1559 return EM_AARCH64; 1560 case Triple::amdgcn: 1561 case Triple::r600: 1562 return EM_AMDGPU; 1563 case Triple::arm: 1564 case Triple::thumb: 1565 return EM_ARM; 1566 case Triple::avr: 1567 return EM_AVR; 1568 case Triple::hexagon: 1569 return EM_HEXAGON; 1570 case Triple::mips: 1571 case Triple::mipsel: 1572 case Triple::mips64: 1573 case Triple::mips64el: 1574 return EM_MIPS; 1575 case Triple::msp430: 1576 return EM_MSP430; 1577 case Triple::ppc: 1578 case Triple::ppcle: 1579 return EM_PPC; 1580 case Triple::ppc64: 1581 case Triple::ppc64le: 1582 return EM_PPC64; 1583 case Triple::riscv32: 1584 case Triple::riscv64: 1585 return EM_RISCV; 1586 case Triple::x86: 1587 return t.isOSIAMCU() ? EM_IAMCU : EM_386; 1588 case Triple::x86_64: 1589 return EM_X86_64; 1590 default: 1591 error(path + ": could not infer e_machine from bitcode target triple " + 1592 t.str()); 1593 return EM_NONE; 1594 } 1595 } 1596 1597 static uint8_t getOsAbi(const Triple &t) { 1598 switch (t.getOS()) { 1599 case Triple::AMDHSA: 1600 return ELF::ELFOSABI_AMDGPU_HSA; 1601 case Triple::AMDPAL: 1602 return ELF::ELFOSABI_AMDGPU_PAL; 1603 case Triple::Mesa3D: 1604 return ELF::ELFOSABI_AMDGPU_MESA3D; 1605 default: 1606 return ELF::ELFOSABI_NONE; 1607 } 1608 } 1609 1610 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1611 uint64_t offsetInArchive, bool lazy) 1612 : InputFile(BitcodeKind, mb) { 1613 this->archiveName = archiveName; 1614 this->lazy = lazy; 1615 1616 std::string path = mb.getBufferIdentifier().str(); 1617 if (config->thinLTOIndexOnly) 1618 path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 1619 1620 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1621 // name. If two archives define two members with the same name, this 1622 // causes a collision which result in only one of the objects being taken 1623 // into consideration at LTO time (which very likely causes undefined 1624 // symbols later in the link stage). So we append file offset to make 1625 // filename unique. 1626 StringRef name = archiveName.empty() 1627 ? saver().save(path) 1628 : saver().save(archiveName + "(" + path::filename(path) + 1629 " at " + utostr(offsetInArchive) + ")"); 1630 MemoryBufferRef mbref(mb.getBuffer(), name); 1631 1632 obj = CHECK(lto::InputFile::create(mbref), this); 1633 1634 Triple t(obj->getTargetTriple()); 1635 ekind = getBitcodeELFKind(t); 1636 emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t); 1637 osabi = getOsAbi(t); 1638 } 1639 1640 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 1641 switch (gvVisibility) { 1642 case GlobalValue::DefaultVisibility: 1643 return STV_DEFAULT; 1644 case GlobalValue::HiddenVisibility: 1645 return STV_HIDDEN; 1646 case GlobalValue::ProtectedVisibility: 1647 return STV_PROTECTED; 1648 } 1649 llvm_unreachable("unknown visibility"); 1650 } 1651 1652 static void 1653 createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats, 1654 const lto::InputFile::Symbol &objSym, BitcodeFile &f) { 1655 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL; 1656 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE; 1657 uint8_t visibility = mapVisibility(objSym.getVisibility()); 1658 1659 if (!sym) 1660 sym = symtab.insert(saver().save(objSym.getName())); 1661 1662 int c = objSym.getComdatIndex(); 1663 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) { 1664 Undefined newSym(&f, StringRef(), binding, visibility, type); 1665 sym->resolve(newSym); 1666 sym->referenced = true; 1667 return; 1668 } 1669 1670 if (objSym.isCommon()) { 1671 sym->resolve(CommonSymbol{&f, StringRef(), binding, visibility, STT_OBJECT, 1672 objSym.getCommonAlignment(), 1673 objSym.getCommonSize()}); 1674 } else { 1675 Defined newSym(&f, StringRef(), binding, visibility, type, 0, 0, nullptr); 1676 if (objSym.canBeOmittedFromSymbolTable()) 1677 newSym.exportDynamic = false; 1678 sym->resolve(newSym); 1679 } 1680 } 1681 1682 void BitcodeFile::parse() { 1683 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) { 1684 keptComdats.push_back( 1685 s.second == Comdat::NoDeduplicate || 1686 symtab.comdatGroups.try_emplace(CachedHashStringRef(s.first), this) 1687 .second); 1688 } 1689 1690 if (numSymbols == 0) { 1691 numSymbols = obj->symbols().size(); 1692 symbols = std::make_unique<Symbol *[]>(numSymbols); 1693 } 1694 // Process defined symbols first. See the comment in 1695 // ObjFile<ELFT>::initializeSymbols. 1696 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) 1697 if (!irSym.isUndefined()) 1698 createBitcodeSymbol(symbols[i], keptComdats, irSym, *this); 1699 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) 1700 if (irSym.isUndefined()) 1701 createBitcodeSymbol(symbols[i], keptComdats, irSym, *this); 1702 1703 for (auto l : obj->getDependentLibraries()) 1704 addDependentLibrary(l, this); 1705 } 1706 1707 void BitcodeFile::parseLazy() { 1708 numSymbols = obj->symbols().size(); 1709 symbols = std::make_unique<Symbol *[]>(numSymbols); 1710 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) 1711 if (!irSym.isUndefined()) { 1712 auto *sym = symtab.insert(saver().save(irSym.getName())); 1713 sym->resolve(LazyObject{*this}); 1714 symbols[i] = sym; 1715 } 1716 } 1717 1718 void BitcodeFile::postParse() { 1719 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) { 1720 const Symbol &sym = *symbols[i]; 1721 if (sym.file == this || !sym.isDefined() || irSym.isUndefined() || 1722 irSym.isCommon() || irSym.isWeak()) 1723 continue; 1724 int c = irSym.getComdatIndex(); 1725 if (c != -1 && !keptComdats[c]) 1726 continue; 1727 reportDuplicate(sym, this, nullptr, 0); 1728 } 1729 } 1730 1731 void BinaryFile::parse() { 1732 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer()); 1733 auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1734 8, data, ".data"); 1735 sections.push_back(section); 1736 1737 // For each input file foo that is embedded to a result as a binary 1738 // blob, we define _binary_foo_{start,end,size} symbols, so that 1739 // user programs can access blobs by name. Non-alphanumeric 1740 // characters in a filename are replaced with underscore. 1741 std::string s = "_binary_" + mb.getBufferIdentifier().str(); 1742 for (size_t i = 0; i < s.size(); ++i) 1743 if (!isAlnum(s[i])) 1744 s[i] = '_'; 1745 1746 llvm::StringSaver &saver = lld::saver(); 1747 1748 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_start"), 1749 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 0, 0, 1750 section}); 1751 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_end"), 1752 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 1753 data.size(), 0, section}); 1754 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_size"), 1755 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 1756 data.size(), 0, nullptr}); 1757 } 1758 1759 ELFFileBase *elf::createObjFile(MemoryBufferRef mb, StringRef archiveName, 1760 bool lazy) { 1761 ELFFileBase *f; 1762 switch (getELFKind(mb, archiveName)) { 1763 case ELF32LEKind: 1764 f = make<ObjFile<ELF32LE>>(ELF32LEKind, mb, archiveName); 1765 break; 1766 case ELF32BEKind: 1767 f = make<ObjFile<ELF32BE>>(ELF32BEKind, mb, archiveName); 1768 break; 1769 case ELF64LEKind: 1770 f = make<ObjFile<ELF64LE>>(ELF64LEKind, mb, archiveName); 1771 break; 1772 case ELF64BEKind: 1773 f = make<ObjFile<ELF64BE>>(ELF64BEKind, mb, archiveName); 1774 break; 1775 default: 1776 llvm_unreachable("getELFKind"); 1777 } 1778 f->init(); 1779 f->lazy = lazy; 1780 return f; 1781 } 1782 1783 template <class ELFT> void ObjFile<ELFT>::parseLazy() { 1784 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>(); 1785 numSymbols = eSyms.size(); 1786 symbols = std::make_unique<Symbol *[]>(numSymbols); 1787 1788 // resolve() may trigger this->extract() if an existing symbol is an undefined 1789 // symbol. If that happens, this function has served its purpose, and we can 1790 // exit from the loop early. 1791 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 1792 if (eSyms[i].st_shndx == SHN_UNDEF) 1793 continue; 1794 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 1795 symbols[i]->resolve(LazyObject{*this}); 1796 if (!lazy) 1797 break; 1798 } 1799 } 1800 1801 bool InputFile::shouldExtractForCommon(StringRef name) { 1802 if (isa<BitcodeFile>(this)) 1803 return isBitcodeNonCommonDef(mb, name, archiveName); 1804 1805 return isNonCommonDef(mb, name, archiveName); 1806 } 1807 1808 std::string elf::replaceThinLTOSuffix(StringRef path) { 1809 auto [suffix, repl] = config->thinLTOObjectSuffixReplace; 1810 if (path.consume_back(suffix)) 1811 return (path + repl).str(); 1812 return std::string(path); 1813 } 1814 1815 template class elf::ObjFile<ELF32LE>; 1816 template class elf::ObjFile<ELF32BE>; 1817 template class elf::ObjFile<ELF64LE>; 1818 template class elf::ObjFile<ELF64BE>; 1819 1820 template void SharedFile::parse<ELF32LE>(); 1821 template void SharedFile::parse<ELF32BE>(); 1822 template void SharedFile::parse<ELF64LE>(); 1823 template void SharedFile::parse<ELF64BE>(); 1824