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