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