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