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