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