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