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