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