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 linker merges EH (exception handling) frames and creates a 996 // .eh_frame_hdr section for runtime. So we handle them with a special 997 // class. For relocatable outputs, they are just passed through. 998 if (name == ".eh_frame" && !config->relocatable) 999 return make<EhInputSection>(*this, sec, name); 1000 1001 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name)) 1002 return make<MergeInputSection>(*this, sec, name); 1003 return make<InputSection>(*this, sec, name); 1004 } 1005 1006 // Initialize this->Symbols. this->Symbols is a parallel array as 1007 // its corresponding ELF symbol table. 1008 template <class ELFT> 1009 void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) { 1010 SymbolTable &symtab = *elf::symtab; 1011 1012 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1013 symbols.resize(eSyms.size()); 1014 1015 // Some entries have been filled by LazyObjFile. 1016 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 1017 if (!symbols[i]) 1018 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 1019 1020 // Perform symbol resolution on non-local symbols. 1021 SmallVector<unsigned, 32> undefineds; 1022 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 1023 const Elf_Sym &eSym = eSyms[i]; 1024 uint8_t binding = eSym.getBinding(); 1025 if (LLVM_UNLIKELY(binding == STB_LOCAL)) { 1026 errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) + 1027 ") found at index >= .symtab's sh_info (" + 1028 Twine(firstGlobal) + ")"); 1029 continue; 1030 } 1031 uint32_t secIdx = eSym.st_shndx; 1032 if (secIdx == SHN_UNDEF) { 1033 undefineds.push_back(i); 1034 continue; 1035 } 1036 1037 uint8_t stOther = eSym.st_other; 1038 uint8_t type = eSym.getType(); 1039 uint64_t value = eSym.st_value; 1040 uint64_t size = eSym.st_size; 1041 1042 Symbol *sym = symbols[i]; 1043 sym->isUsedInRegularObj = true; 1044 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) { 1045 if (value == 0 || value >= UINT32_MAX) 1046 fatal(toString(this) + ": common symbol '" + sym->getName() + 1047 "' has invalid alignment: " + Twine(value)); 1048 hasCommonSyms = true; 1049 sym->resolve( 1050 CommonSymbol{this, StringRef(), binding, stOther, type, value, size}); 1051 continue; 1052 } 1053 1054 // Handle global defined symbols. Defined::section will be set in postParse. 1055 if (binding == STB_GLOBAL || binding == STB_WEAK || 1056 binding == STB_GNU_UNIQUE) { 1057 sym->resolve(Defined{this, StringRef(), binding, stOther, type, value, 1058 size, nullptr}); 1059 continue; 1060 } 1061 1062 fatal(toString(this) + ": unexpected binding: " + Twine((int)binding)); 1063 } 1064 1065 // Undefined symbols (excluding those defined relative to non-prevailing 1066 // sections) can trigger recursive extract. Process defined symbols first so 1067 // that the relative order between a defined symbol and an undefined symbol 1068 // does not change the symbol resolution behavior. In addition, a set of 1069 // interconnected symbols will all be resolved to the same file, instead of 1070 // being resolved to different files. 1071 for (unsigned i : undefineds) { 1072 const Elf_Sym &eSym = eSyms[i]; 1073 Symbol *sym = symbols[i]; 1074 sym->resolve(Undefined{this, StringRef(), eSym.getBinding(), eSym.st_other, 1075 eSym.getType()}); 1076 sym->isUsedInRegularObj = true; 1077 sym->referenced = true; 1078 } 1079 } 1080 1081 template <class ELFT> void ObjFile<ELFT>::initializeLocalSymbols() { 1082 if (!firstGlobal) 1083 return; 1084 localSymStorage = std::make_unique<SymbolUnion[]>(firstGlobal); 1085 SymbolUnion *locals = localSymStorage.get(); 1086 1087 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1088 for (size_t i = 0, end = firstGlobal; i != end; ++i) { 1089 const Elf_Sym &eSym = eSyms[i]; 1090 uint32_t secIdx = eSym.st_shndx; 1091 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1092 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1093 else if (secIdx >= SHN_LORESERVE) 1094 secIdx = 0; 1095 if (LLVM_UNLIKELY(secIdx >= sections.size())) 1096 fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 1097 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL)) 1098 error(toString(this) + ": non-local symbol (" + Twine(i) + 1099 ") found at index < .symtab's sh_info (" + Twine(end) + ")"); 1100 1101 InputSectionBase *sec = sections[secIdx]; 1102 uint8_t type = eSym.getType(); 1103 if (type == STT_FILE) 1104 sourceFile = CHECK(eSym.getName(stringTable), this); 1105 if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name)) 1106 fatal(toString(this) + ": invalid symbol name offset"); 1107 StringRef name(stringTable.data() + eSym.st_name); 1108 1109 symbols[i] = reinterpret_cast<Symbol *>(locals + i); 1110 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded) 1111 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type, 1112 /*discardedSecIdx=*/secIdx); 1113 else 1114 new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type, 1115 eSym.st_value, eSym.st_size, sec); 1116 symbols[i]->isUsedInRegularObj = true; 1117 } 1118 } 1119 1120 // Called after all ObjFile::parse is called for all ObjFiles. This checks 1121 // duplicate symbols and may do symbol property merge in the future. 1122 template <class ELFT> void ObjFile<ELFT>::postParse() { 1123 static std::mutex mu; 1124 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>(); 1125 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) { 1126 const Elf_Sym &eSym = eSyms[i]; 1127 Symbol &sym = *symbols[i]; 1128 uint32_t secIdx = eSym.st_shndx; 1129 1130 // st_value of STT_TLS represents the assigned offset, not the actual 1131 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can 1132 // only be referenced by special TLS relocations. It is usually an error if 1133 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa. 1134 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS && 1135 eSym.getType() != STT_NOTYPE) 1136 errorOrWarn("TLS attribute mismatch: " + toString(sym) + "\n>>> in " + 1137 toString(sym.file) + "\n>>> in " + toString(this)); 1138 1139 // Handle non-COMMON defined symbol below. !sym.file allows a symbol 1140 // assignment to redefine a symbol without an error. 1141 if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF || 1142 secIdx == SHN_COMMON) 1143 continue; 1144 1145 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX)) 1146 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable)); 1147 else if (secIdx >= SHN_LORESERVE) 1148 secIdx = 0; 1149 if (LLVM_UNLIKELY(secIdx >= sections.size())) 1150 fatal(toString(this) + ": invalid section index: " + Twine(secIdx)); 1151 InputSectionBase *sec = sections[secIdx]; 1152 if (sec == &InputSection::discarded) { 1153 if (sym.traced) { 1154 printTraceSymbol(Undefined{this, sym.getName(), sym.binding, 1155 sym.stOther, sym.type, secIdx}, 1156 sym.getName()); 1157 } 1158 if (sym.file == this) { 1159 std::lock_guard<std::mutex> lock(mu); 1160 ctx->nonPrevailingSyms.emplace_back(&sym, secIdx); 1161 } 1162 continue; 1163 } 1164 1165 if (sym.file == this) { 1166 cast<Defined>(sym).section = sec; 1167 continue; 1168 } 1169 1170 if (eSym.getBinding() == STB_WEAK) 1171 continue; 1172 std::lock_guard<std::mutex> lock(mu); 1173 ctx->duplicates.push_back({&sym, this, sec, eSym.st_value}); 1174 } 1175 } 1176 1177 // The handling of tentative definitions (COMMON symbols) in archives is murky. 1178 // A tentative definition will be promoted to a global definition if there are 1179 // no non-tentative definitions to dominate it. When we hold a tentative 1180 // definition to a symbol and are inspecting archive members for inclusion 1181 // there are 2 ways we can proceed: 1182 // 1183 // 1) Consider the tentative definition a 'real' definition (ie promotion from 1184 // tentative to real definition has already happened) and not inspect 1185 // archive members for Global/Weak definitions to replace the tentative 1186 // definition. An archive member would only be included if it satisfies some 1187 // other undefined symbol. This is the behavior Gold uses. 1188 // 1189 // 2) Consider the tentative definition as still undefined (ie the promotion to 1190 // a real definition happens only after all symbol resolution is done). 1191 // The linker searches archive members for STB_GLOBAL definitions to 1192 // replace the tentative definition with. This is the behavior used by 1193 // GNU ld. 1194 // 1195 // The second behavior is inherited from SysVR4, which based it on the FORTRAN 1196 // COMMON BLOCK model. This behavior is needed for proper initialization in old 1197 // (pre F90) FORTRAN code that is packaged into an archive. 1198 // 1199 // The following functions search archive members for definitions to replace 1200 // tentative definitions (implementing behavior 2). 1201 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName, 1202 StringRef archiveName) { 1203 IRSymtabFile symtabFile = check(readIRSymtab(mb)); 1204 for (const irsymtab::Reader::SymbolRef &sym : 1205 symtabFile.TheReader.symbols()) { 1206 if (sym.isGlobal() && sym.getName() == symName) 1207 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon(); 1208 } 1209 return false; 1210 } 1211 1212 template <class ELFT> 1213 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1214 StringRef archiveName) { 1215 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName); 1216 StringRef stringtable = obj->getStringTable(); 1217 1218 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) { 1219 Expected<StringRef> name = sym.getName(stringtable); 1220 if (name && name.get() == symName) 1221 return sym.isDefined() && sym.getBinding() == STB_GLOBAL && 1222 !sym.isCommon(); 1223 } 1224 return false; 1225 } 1226 1227 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName, 1228 StringRef archiveName) { 1229 switch (getELFKind(mb, archiveName)) { 1230 case ELF32LEKind: 1231 return isNonCommonDef<ELF32LE>(mb, symName, archiveName); 1232 case ELF32BEKind: 1233 return isNonCommonDef<ELF32BE>(mb, symName, archiveName); 1234 case ELF64LEKind: 1235 return isNonCommonDef<ELF64LE>(mb, symName, archiveName); 1236 case ELF64BEKind: 1237 return isNonCommonDef<ELF64BE>(mb, symName, archiveName); 1238 default: 1239 llvm_unreachable("getELFKind"); 1240 } 1241 } 1242 1243 unsigned SharedFile::vernauxNum; 1244 1245 // Parse the version definitions in the object file if present, and return a 1246 // vector whose nth element contains a pointer to the Elf_Verdef for version 1247 // identifier n. Version identifiers that are not definitions map to nullptr. 1248 template <typename ELFT> 1249 static SmallVector<const void *, 0> 1250 parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) { 1251 if (!sec) 1252 return {}; 1253 1254 // Build the Verdefs array by following the chain of Elf_Verdef objects 1255 // from the start of the .gnu.version_d section. 1256 SmallVector<const void *, 0> verdefs; 1257 const uint8_t *verdef = base + sec->sh_offset; 1258 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) { 1259 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef); 1260 verdef += curVerdef->vd_next; 1261 unsigned verdefIndex = curVerdef->vd_ndx; 1262 if (verdefIndex >= verdefs.size()) 1263 verdefs.resize(verdefIndex + 1); 1264 verdefs[verdefIndex] = curVerdef; 1265 } 1266 return verdefs; 1267 } 1268 1269 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined 1270 // symbol. We detect fatal issues which would cause vulnerabilities, but do not 1271 // implement sophisticated error checking like in llvm-readobj because the value 1272 // of such diagnostics is low. 1273 template <typename ELFT> 1274 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj, 1275 const typename ELFT::Shdr *sec) { 1276 if (!sec) 1277 return {}; 1278 std::vector<uint32_t> verneeds; 1279 ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this); 1280 const uint8_t *verneedBuf = data.begin(); 1281 for (unsigned i = 0; i != sec->sh_info; ++i) { 1282 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end()) 1283 fatal(toString(this) + " has an invalid Verneed"); 1284 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf); 1285 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux; 1286 for (unsigned j = 0; j != vn->vn_cnt; ++j) { 1287 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end()) 1288 fatal(toString(this) + " has an invalid Vernaux"); 1289 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf); 1290 if (aux->vna_name >= this->stringTable.size()) 1291 fatal(toString(this) + " has a Vernaux with an invalid vna_name"); 1292 uint16_t version = aux->vna_other & VERSYM_VERSION; 1293 if (version >= verneeds.size()) 1294 verneeds.resize(version + 1); 1295 verneeds[version] = aux->vna_name; 1296 vernauxBuf += aux->vna_next; 1297 } 1298 verneedBuf += vn->vn_next; 1299 } 1300 return verneeds; 1301 } 1302 1303 // We do not usually care about alignments of data in shared object 1304 // files because the loader takes care of it. However, if we promote a 1305 // DSO symbol to point to .bss due to copy relocation, we need to keep 1306 // the original alignment requirements. We infer it in this function. 1307 template <typename ELFT> 1308 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections, 1309 const typename ELFT::Sym &sym) { 1310 uint64_t ret = UINT64_MAX; 1311 if (sym.st_value) 1312 ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value); 1313 if (0 < sym.st_shndx && sym.st_shndx < sections.size()) 1314 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign); 1315 return (ret > UINT32_MAX) ? 0 : ret; 1316 } 1317 1318 // Fully parse the shared object file. 1319 // 1320 // This function parses symbol versions. If a DSO has version information, 1321 // the file has a ".gnu.version_d" section which contains symbol version 1322 // definitions. Each symbol is associated to one version through a table in 1323 // ".gnu.version" section. That table is a parallel array for the symbol 1324 // table, and each table entry contains an index in ".gnu.version_d". 1325 // 1326 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for 1327 // VER_NDX_GLOBAL. There's no table entry for these special versions in 1328 // ".gnu.version_d". 1329 // 1330 // The file format for symbol versioning is perhaps a bit more complicated 1331 // than necessary, but you can easily understand the code if you wrap your 1332 // head around the data structure described above. 1333 template <class ELFT> void SharedFile::parse() { 1334 using Elf_Dyn = typename ELFT::Dyn; 1335 using Elf_Shdr = typename ELFT::Shdr; 1336 using Elf_Sym = typename ELFT::Sym; 1337 using Elf_Verdef = typename ELFT::Verdef; 1338 using Elf_Versym = typename ELFT::Versym; 1339 1340 ArrayRef<Elf_Dyn> dynamicTags; 1341 const ELFFile<ELFT> obj = this->getObj<ELFT>(); 1342 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>(); 1343 1344 const Elf_Shdr *versymSec = nullptr; 1345 const Elf_Shdr *verdefSec = nullptr; 1346 const Elf_Shdr *verneedSec = nullptr; 1347 1348 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d. 1349 for (const Elf_Shdr &sec : sections) { 1350 switch (sec.sh_type) { 1351 default: 1352 continue; 1353 case SHT_DYNAMIC: 1354 dynamicTags = 1355 CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this); 1356 break; 1357 case SHT_GNU_versym: 1358 versymSec = &sec; 1359 break; 1360 case SHT_GNU_verdef: 1361 verdefSec = &sec; 1362 break; 1363 case SHT_GNU_verneed: 1364 verneedSec = &sec; 1365 break; 1366 } 1367 } 1368 1369 if (versymSec && numELFSyms == 0) { 1370 error("SHT_GNU_versym should be associated with symbol table"); 1371 return; 1372 } 1373 1374 // Search for a DT_SONAME tag to initialize this->soName. 1375 for (const Elf_Dyn &dyn : dynamicTags) { 1376 if (dyn.d_tag == DT_NEEDED) { 1377 uint64_t val = dyn.getVal(); 1378 if (val >= this->stringTable.size()) 1379 fatal(toString(this) + ": invalid DT_NEEDED entry"); 1380 dtNeeded.push_back(this->stringTable.data() + val); 1381 } else if (dyn.d_tag == DT_SONAME) { 1382 uint64_t val = dyn.getVal(); 1383 if (val >= this->stringTable.size()) 1384 fatal(toString(this) + ": invalid DT_SONAME entry"); 1385 soName = this->stringTable.data() + val; 1386 } 1387 } 1388 1389 // DSOs are uniquified not by filename but by soname. 1390 DenseMap<CachedHashStringRef, SharedFile *>::iterator it; 1391 bool wasInserted; 1392 std::tie(it, wasInserted) = 1393 symtab->soNames.try_emplace(CachedHashStringRef(soName), this); 1394 1395 // If a DSO appears more than once on the command line with and without 1396 // --as-needed, --no-as-needed takes precedence over --as-needed because a 1397 // user can add an extra DSO with --no-as-needed to force it to be added to 1398 // the dependency list. 1399 it->second->isNeeded |= isNeeded; 1400 if (!wasInserted) 1401 return; 1402 1403 sharedFiles.push_back(this); 1404 1405 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec); 1406 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec); 1407 1408 // Parse ".gnu.version" section which is a parallel array for the symbol 1409 // table. If a given file doesn't have a ".gnu.version" section, we use 1410 // VER_NDX_GLOBAL. 1411 size_t size = numELFSyms - firstGlobal; 1412 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL); 1413 if (versymSec) { 1414 ArrayRef<Elf_Versym> versym = 1415 CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec), 1416 this) 1417 .slice(firstGlobal); 1418 for (size_t i = 0; i < size; ++i) 1419 versyms[i] = versym[i].vs_index; 1420 } 1421 1422 // System libraries can have a lot of symbols with versions. Using a 1423 // fixed buffer for computing the versions name (foo@ver) can save a 1424 // lot of allocations. 1425 SmallString<0> versionedNameBuffer; 1426 1427 // Add symbols to the symbol table. 1428 SymbolTable &symtab = *elf::symtab; 1429 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>(); 1430 for (size_t i = 0, e = syms.size(); i != e; ++i) { 1431 const Elf_Sym &sym = syms[i]; 1432 1433 // ELF spec requires that all local symbols precede weak or global 1434 // symbols in each symbol table, and the index of first non-local symbol 1435 // is stored to sh_info. If a local symbol appears after some non-local 1436 // symbol, that's a violation of the spec. 1437 StringRef name = CHECK(sym.getName(stringTable), this); 1438 if (sym.getBinding() == STB_LOCAL) { 1439 warn("found local symbol '" + name + 1440 "' in global part of symbol table in file " + toString(this)); 1441 continue; 1442 } 1443 1444 uint16_t idx = versyms[i] & ~VERSYM_HIDDEN; 1445 if (sym.isUndefined()) { 1446 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but 1447 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL. 1448 if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) { 1449 if (idx >= verneeds.size()) { 1450 error("corrupt input file: version need index " + Twine(idx) + 1451 " for symbol " + name + " is out of bounds\n>>> defined in " + 1452 toString(this)); 1453 continue; 1454 } 1455 StringRef verName = stringTable.data() + verneeds[idx]; 1456 versionedNameBuffer.clear(); 1457 name = saver().save( 1458 (name + "@" + verName).toStringRef(versionedNameBuffer)); 1459 } 1460 Symbol *s = symtab.addSymbol( 1461 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()}); 1462 s->exportDynamic = true; 1463 if (s->isUndefined() && sym.getBinding() != STB_WEAK && 1464 config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) 1465 requiredSymbols.push_back(s); 1466 continue; 1467 } 1468 1469 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly 1470 // assigns VER_NDX_LOCAL to this section global symbol. Here is a 1471 // workaround for this bug. 1472 if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL && 1473 name == "_gp_disp") 1474 continue; 1475 1476 uint32_t alignment = getAlignment<ELFT>(sections, sym); 1477 if (!(versyms[i] & VERSYM_HIDDEN)) { 1478 auto *s = symtab.addSymbol( 1479 SharedSymbol{*this, name, sym.getBinding(), sym.st_other, 1480 sym.getType(), sym.st_value, sym.st_size, alignment}); 1481 if (s->file == this) 1482 s->verdefIndex = idx; 1483 } 1484 1485 // Also add the symbol with the versioned name to handle undefined symbols 1486 // with explicit versions. 1487 if (idx == VER_NDX_GLOBAL) 1488 continue; 1489 1490 if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) { 1491 error("corrupt input file: version definition index " + Twine(idx) + 1492 " for symbol " + name + " is out of bounds\n>>> defined in " + 1493 toString(this)); 1494 continue; 1495 } 1496 1497 StringRef verName = 1498 stringTable.data() + 1499 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name; 1500 versionedNameBuffer.clear(); 1501 name = (name + "@" + verName).toStringRef(versionedNameBuffer); 1502 auto *s = symtab.addSymbol( 1503 SharedSymbol{*this, saver().save(name), sym.getBinding(), sym.st_other, 1504 sym.getType(), sym.st_value, sym.st_size, alignment}); 1505 if (s->file == this) 1506 s->verdefIndex = idx; 1507 } 1508 } 1509 1510 static ELFKind getBitcodeELFKind(const Triple &t) { 1511 if (t.isLittleEndian()) 1512 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind; 1513 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind; 1514 } 1515 1516 static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) { 1517 switch (t.getArch()) { 1518 case Triple::aarch64: 1519 case Triple::aarch64_be: 1520 return EM_AARCH64; 1521 case Triple::amdgcn: 1522 case Triple::r600: 1523 return EM_AMDGPU; 1524 case Triple::arm: 1525 case Triple::thumb: 1526 return EM_ARM; 1527 case Triple::avr: 1528 return EM_AVR; 1529 case Triple::hexagon: 1530 return EM_HEXAGON; 1531 case Triple::mips: 1532 case Triple::mipsel: 1533 case Triple::mips64: 1534 case Triple::mips64el: 1535 return EM_MIPS; 1536 case Triple::msp430: 1537 return EM_MSP430; 1538 case Triple::ppc: 1539 case Triple::ppcle: 1540 return EM_PPC; 1541 case Triple::ppc64: 1542 case Triple::ppc64le: 1543 return EM_PPC64; 1544 case Triple::riscv32: 1545 case Triple::riscv64: 1546 return EM_RISCV; 1547 case Triple::x86: 1548 return t.isOSIAMCU() ? EM_IAMCU : EM_386; 1549 case Triple::x86_64: 1550 return EM_X86_64; 1551 default: 1552 error(path + ": could not infer e_machine from bitcode target triple " + 1553 t.str()); 1554 return EM_NONE; 1555 } 1556 } 1557 1558 static uint8_t getOsAbi(const Triple &t) { 1559 switch (t.getOS()) { 1560 case Triple::AMDHSA: 1561 return ELF::ELFOSABI_AMDGPU_HSA; 1562 case Triple::AMDPAL: 1563 return ELF::ELFOSABI_AMDGPU_PAL; 1564 case Triple::Mesa3D: 1565 return ELF::ELFOSABI_AMDGPU_MESA3D; 1566 default: 1567 return ELF::ELFOSABI_NONE; 1568 } 1569 } 1570 1571 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1572 uint64_t offsetInArchive, bool lazy) 1573 : InputFile(BitcodeKind, mb) { 1574 this->archiveName = archiveName; 1575 this->lazy = lazy; 1576 1577 std::string path = mb.getBufferIdentifier().str(); 1578 if (config->thinLTOIndexOnly) 1579 path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 1580 1581 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1582 // name. If two archives define two members with the same name, this 1583 // causes a collision which result in only one of the objects being taken 1584 // into consideration at LTO time (which very likely causes undefined 1585 // symbols later in the link stage). So we append file offset to make 1586 // filename unique. 1587 StringRef name = archiveName.empty() 1588 ? saver().save(path) 1589 : saver().save(archiveName + "(" + path::filename(path) + 1590 " at " + utostr(offsetInArchive) + ")"); 1591 MemoryBufferRef mbref(mb.getBuffer(), name); 1592 1593 obj = CHECK(lto::InputFile::create(mbref), this); 1594 1595 Triple t(obj->getTargetTriple()); 1596 ekind = getBitcodeELFKind(t); 1597 emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t); 1598 osabi = getOsAbi(t); 1599 } 1600 1601 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) { 1602 switch (gvVisibility) { 1603 case GlobalValue::DefaultVisibility: 1604 return STV_DEFAULT; 1605 case GlobalValue::HiddenVisibility: 1606 return STV_HIDDEN; 1607 case GlobalValue::ProtectedVisibility: 1608 return STV_PROTECTED; 1609 } 1610 llvm_unreachable("unknown visibility"); 1611 } 1612 1613 template <class ELFT> 1614 static void 1615 createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats, 1616 const lto::InputFile::Symbol &objSym, BitcodeFile &f) { 1617 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL; 1618 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE; 1619 uint8_t visibility = mapVisibility(objSym.getVisibility()); 1620 1621 if (!sym) 1622 sym = symtab->insert(saver().save(objSym.getName())); 1623 1624 int c = objSym.getComdatIndex(); 1625 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) { 1626 Undefined newSym(&f, StringRef(), binding, visibility, type); 1627 sym->resolve(newSym); 1628 sym->referenced = true; 1629 return; 1630 } 1631 1632 if (objSym.isCommon()) { 1633 sym->resolve(CommonSymbol{&f, StringRef(), binding, visibility, STT_OBJECT, 1634 objSym.getCommonAlignment(), 1635 objSym.getCommonSize()}); 1636 } else { 1637 Defined newSym(&f, StringRef(), binding, visibility, type, 0, 0, nullptr); 1638 if (objSym.canBeOmittedFromSymbolTable()) 1639 newSym.exportDynamic = false; 1640 sym->resolve(newSym); 1641 } 1642 } 1643 1644 template <class ELFT> void BitcodeFile::parse() { 1645 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) { 1646 keptComdats.push_back( 1647 s.second == Comdat::NoDeduplicate || 1648 symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this) 1649 .second); 1650 } 1651 1652 symbols.resize(obj->symbols().size()); 1653 // Process defined symbols first. See the comment in 1654 // ObjFile<ELFT>::initializeSymbols. 1655 for (auto it : llvm::enumerate(obj->symbols())) 1656 if (!it.value().isUndefined()) { 1657 Symbol *&sym = symbols[it.index()]; 1658 createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this); 1659 } 1660 for (auto it : llvm::enumerate(obj->symbols())) 1661 if (it.value().isUndefined()) { 1662 Symbol *&sym = symbols[it.index()]; 1663 createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this); 1664 } 1665 1666 for (auto l : obj->getDependentLibraries()) 1667 addDependentLibrary(l, this); 1668 } 1669 1670 void BitcodeFile::parseLazy() { 1671 SymbolTable &symtab = *elf::symtab; 1672 symbols.resize(obj->symbols().size()); 1673 for (auto it : llvm::enumerate(obj->symbols())) 1674 if (!it.value().isUndefined()) { 1675 auto *sym = symtab.insert(saver().save(it.value().getName())); 1676 sym->resolve(LazyObject{*this}); 1677 symbols[it.index()] = sym; 1678 } 1679 } 1680 1681 void BitcodeFile::postParse() { 1682 for (auto it : llvm::enumerate(obj->symbols())) { 1683 const Symbol &sym = *symbols[it.index()]; 1684 const auto &objSym = it.value(); 1685 if (sym.file == this || !sym.isDefined() || objSym.isUndefined() || 1686 objSym.isCommon() || objSym.isWeak()) 1687 continue; 1688 int c = objSym.getComdatIndex(); 1689 if (c != -1 && !keptComdats[c]) 1690 continue; 1691 reportDuplicate(sym, this, nullptr, 0); 1692 } 1693 } 1694 1695 void BinaryFile::parse() { 1696 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer()); 1697 auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 1698 8, data, ".data"); 1699 sections.push_back(section); 1700 1701 // For each input file foo that is embedded to a result as a binary 1702 // blob, we define _binary_foo_{start,end,size} symbols, so that 1703 // user programs can access blobs by name. Non-alphanumeric 1704 // characters in a filename are replaced with underscore. 1705 std::string s = "_binary_" + mb.getBufferIdentifier().str(); 1706 for (size_t i = 0; i < s.size(); ++i) 1707 if (!isAlnum(s[i])) 1708 s[i] = '_'; 1709 1710 llvm::StringSaver &saver = lld::saver(); 1711 1712 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_start"), 1713 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 0, 1714 0, section}); 1715 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_end"), 1716 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 1717 data.size(), 0, section}); 1718 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_size"), 1719 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 1720 data.size(), 0, nullptr}); 1721 } 1722 1723 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName, 1724 uint64_t offsetInArchive) { 1725 if (isBitcode(mb)) 1726 return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false); 1727 1728 switch (getELFKind(mb, archiveName)) { 1729 case ELF32LEKind: 1730 return make<ObjFile<ELF32LE>>(mb, archiveName); 1731 case ELF32BEKind: 1732 return make<ObjFile<ELF32BE>>(mb, archiveName); 1733 case ELF64LEKind: 1734 return make<ObjFile<ELF64LE>>(mb, archiveName); 1735 case ELF64BEKind: 1736 return make<ObjFile<ELF64BE>>(mb, archiveName); 1737 default: 1738 llvm_unreachable("getELFKind"); 1739 } 1740 } 1741 1742 InputFile *elf::createLazyFile(MemoryBufferRef mb, StringRef archiveName, 1743 uint64_t offsetInArchive) { 1744 if (isBitcode(mb)) 1745 return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/true); 1746 1747 auto *file = 1748 cast<ELFFileBase>(createObjectFile(mb, archiveName, offsetInArchive)); 1749 file->lazy = true; 1750 return file; 1751 } 1752 1753 template <class ELFT> void ObjFile<ELFT>::parseLazy() { 1754 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>(); 1755 SymbolTable &symtab = *elf::symtab; 1756 1757 symbols.resize(eSyms.size()); 1758 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) 1759 if (eSyms[i].st_shndx != SHN_UNDEF) 1760 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this)); 1761 1762 // Replace existing symbols with LazyObject symbols. 1763 // 1764 // resolve() may trigger this->extract() if an existing symbol is an undefined 1765 // symbol. If that happens, this function has served its purpose, and we can 1766 // exit from the loop early. 1767 for (Symbol *sym : makeArrayRef(symbols).slice(firstGlobal)) 1768 if (sym) { 1769 sym->resolve(LazyObject{*this}); 1770 if (!lazy) 1771 return; 1772 } 1773 } 1774 1775 bool InputFile::shouldExtractForCommon(StringRef name) { 1776 if (isBitcode(mb)) 1777 return isBitcodeNonCommonDef(mb, name, archiveName); 1778 1779 return isNonCommonDef(mb, name, archiveName); 1780 } 1781 1782 std::string elf::replaceThinLTOSuffix(StringRef path) { 1783 StringRef suffix = config->thinLTOObjectSuffixReplace.first; 1784 StringRef repl = config->thinLTOObjectSuffixReplace.second; 1785 1786 if (path.consume_back(suffix)) 1787 return (path + repl).str(); 1788 return std::string(path); 1789 } 1790 1791 template void BitcodeFile::parse<ELF32LE>(); 1792 template void BitcodeFile::parse<ELF32BE>(); 1793 template void BitcodeFile::parse<ELF64LE>(); 1794 template void BitcodeFile::parse<ELF64BE>(); 1795 1796 template class elf::ObjFile<ELF32LE>; 1797 template class elf::ObjFile<ELF32BE>; 1798 template class elf::ObjFile<ELF64LE>; 1799 template class elf::ObjFile<ELF64BE>; 1800 1801 template void SharedFile::parse<ELF32LE>(); 1802 template void SharedFile::parse<ELF32BE>(); 1803 template void SharedFile::parse<ELF64LE>(); 1804 template void SharedFile::parse<ELF64BE>(); 1805