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