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