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