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