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