1 //===- Driver.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 // The driver drives the entire linking process. It is responsible for 10 // parsing command line options and doing whatever it is instructed to do. 11 // 12 // One notable thing in the LLD's driver when compared to other linkers is 13 // that the LLD's driver is agnostic on the host operating system. 14 // Other linkers usually have implicit default values (such as a dynamic 15 // linker path or library paths) for each host OS. 16 // 17 // I don't think implicit default values are useful because they are 18 // usually explicitly specified by the compiler ctx.driver. They can even 19 // be harmful when you are doing cross-linking. Therefore, in LLD, we 20 // simply trust the compiler driver to pass all required options and 21 // don't try to make effort on our side. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #include "Driver.h" 26 #include "Config.h" 27 #include "ICF.h" 28 #include "InputFiles.h" 29 #include "InputSection.h" 30 #include "LTO.h" 31 #include "LinkerScript.h" 32 #include "MarkLive.h" 33 #include "OutputSections.h" 34 #include "ScriptParser.h" 35 #include "SymbolTable.h" 36 #include "Symbols.h" 37 #include "SyntheticSections.h" 38 #include "Target.h" 39 #include "Writer.h" 40 #include "lld/Common/Args.h" 41 #include "lld/Common/CommonLinkerContext.h" 42 #include "lld/Common/Driver.h" 43 #include "lld/Common/ErrorHandler.h" 44 #include "lld/Common/Filesystem.h" 45 #include "lld/Common/Memory.h" 46 #include "lld/Common/Strings.h" 47 #include "lld/Common/TargetOptionsCommandFlags.h" 48 #include "lld/Common/Version.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/ADT/SetVector.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/ADT/StringSwitch.h" 53 #include "llvm/Config/llvm-config.h" 54 #include "llvm/LTO/LTO.h" 55 #include "llvm/Object/Archive.h" 56 #include "llvm/Object/IRObjectFile.h" 57 #include "llvm/Remarks/HotnessThresholdParser.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/SaveAndRestore.h" 60 #include "llvm/Support/Compression.h" 61 #include "llvm/Support/FileSystem.h" 62 #include "llvm/Support/GlobPattern.h" 63 #include "llvm/Support/LEB128.h" 64 #include "llvm/Support/Parallel.h" 65 #include "llvm/Support/Path.h" 66 #include "llvm/Support/TarWriter.h" 67 #include "llvm/Support/TargetSelect.h" 68 #include "llvm/Support/TimeProfiler.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include <cstdlib> 71 #include <tuple> 72 #include <utility> 73 74 using namespace llvm; 75 using namespace llvm::ELF; 76 using namespace llvm::object; 77 using namespace llvm::sys; 78 using namespace llvm::support; 79 using namespace lld; 80 using namespace lld::elf; 81 82 static void setConfigs(Ctx &ctx, opt::InputArgList &args); 83 static void readConfigs(Ctx &ctx, opt::InputArgList &args); 84 85 ELFSyncStream elf::Log(Ctx &ctx) { return {ctx, DiagLevel::Log}; } 86 ELFSyncStream elf::Msg(Ctx &ctx) { return {ctx, DiagLevel::Msg}; } 87 ELFSyncStream elf::Warn(Ctx &ctx) { return {ctx, DiagLevel::Warn}; } 88 ELFSyncStream elf::Err(Ctx &ctx) { 89 return {ctx, ctx.arg.noinhibitExec ? DiagLevel::Warn : DiagLevel::Err}; 90 } 91 ELFSyncStream elf::ErrAlways(Ctx &ctx) { return {ctx, DiagLevel::Err}; } 92 ELFSyncStream elf::Fatal(Ctx &ctx) { return {ctx, DiagLevel::Fatal}; } 93 uint64_t elf::errCount(Ctx &ctx) { return ctx.e.errorCount; } 94 95 ELFSyncStream elf::InternalErr(Ctx &ctx, const uint8_t *buf) { 96 ELFSyncStream s(ctx, DiagLevel::Err); 97 s << "internal linker error: "; 98 return s; 99 } 100 101 Ctx::Ctx() : driver(*this) {} 102 103 llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename, 104 std::error_code &ec) { 105 using namespace llvm::sys::fs; 106 OpenFlags flags = 107 auxiliaryFiles.insert(filename).second ? OF_None : OF_Append; 108 if (e.disableOutput && filename == "-") { 109 #ifdef _WIN32 110 filename = "NUL"; 111 #else 112 filename = "/dev/null"; 113 #endif 114 } 115 return {filename, ec, flags}; 116 } 117 118 namespace lld { 119 namespace elf { 120 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 121 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { 122 // This driver-specific context will be freed later by unsafeLldMain(). 123 auto *context = new Ctx; 124 Ctx &ctx = *context; 125 126 context->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 127 context->e.logName = args::getFilenameWithoutExe(args[0]); 128 context->e.errorLimitExceededMsg = 129 "too many errors emitted, stopping now (use " 130 "--error-limit=0 to see all errors)"; 131 132 LinkerScript script(ctx); 133 ctx.script = &script; 134 ctx.symAux.emplace_back(); 135 ctx.symtab = std::make_unique<SymbolTable>(ctx); 136 137 ctx.partitions.clear(); 138 ctx.partitions.emplace_back(ctx); 139 140 ctx.arg.progName = args[0]; 141 142 ctx.driver.linkerMain(args); 143 144 return errCount(ctx) == 0; 145 } 146 } // namespace elf 147 } // namespace lld 148 149 // Parses a linker -m option. 150 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(Ctx &ctx, 151 StringRef emul) { 152 uint8_t osabi = 0; 153 StringRef s = emul; 154 if (s.ends_with("_fbsd")) { 155 s = s.drop_back(5); 156 osabi = ELFOSABI_FREEBSD; 157 } 158 159 std::pair<ELFKind, uint16_t> ret = 160 StringSwitch<std::pair<ELFKind, uint16_t>>(s) 161 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 162 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 163 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 164 .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM}) 165 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 166 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 167 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 168 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 169 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 170 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 171 .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH}) 172 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 173 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 174 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 175 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 176 .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 177 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 178 .Case("elf_i386", {ELF32LEKind, EM_386}) 179 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 180 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 181 .Case("msp430elf", {ELF32LEKind, EM_MSP430}) 182 .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU}) 183 .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH}) 184 .Case("elf64_s390", {ELF64BEKind, EM_S390}) 185 .Case("hexagonelf", {ELF32LEKind, EM_HEXAGON}) 186 .Default({ELFNoneKind, EM_NONE}); 187 188 if (ret.first == ELFNoneKind) 189 ErrAlways(ctx) << "unknown emulation: " << emul; 190 if (ret.second == EM_MSP430) 191 osabi = ELFOSABI_STANDALONE; 192 else if (ret.second == EM_AMDGPU) 193 osabi = ELFOSABI_AMDGPU_HSA; 194 return std::make_tuple(ret.first, ret.second, osabi); 195 } 196 197 // Returns slices of MB by parsing MB as an archive file. 198 // Each slice consists of a member file in the archive. 199 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 200 Ctx &ctx, MemoryBufferRef mb) { 201 std::unique_ptr<Archive> file = 202 CHECK(Archive::create(mb), 203 mb.getBufferIdentifier() + ": failed to parse archive"); 204 205 std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 206 Error err = Error::success(); 207 bool addToTar = file->isThin() && ctx.tar; 208 for (const Archive::Child &c : file->children(err)) { 209 MemoryBufferRef mbref = 210 CHECK(c.getMemoryBufferRef(), 211 mb.getBufferIdentifier() + 212 ": could not get the buffer for a child of the archive"); 213 if (addToTar) 214 ctx.tar->append(relativeToRoot(check(c.getFullName())), 215 mbref.getBuffer()); 216 v.push_back(std::make_pair(mbref, c.getChildOffset())); 217 } 218 if (err) 219 Fatal(ctx) << mb.getBufferIdentifier() 220 << ": Archive::children failed: " << std::move(err); 221 222 // Take ownership of memory buffers created for members of thin archives. 223 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers(); 224 std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers)); 225 226 return v; 227 } 228 229 static bool isBitcode(MemoryBufferRef mb) { 230 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 231 } 232 233 bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName, 234 uint64_t offsetInArchive, bool lazy) { 235 if (!ctx.arg.fatLTOObjects) 236 return false; 237 Expected<MemoryBufferRef> fatLTOData = 238 IRObjectFile::findBitcodeInMemBuffer(mb); 239 if (errorToBool(fatLTOData.takeError())) 240 return false; 241 files.push_back(std::make_unique<BitcodeFile>(ctx, *fatLTOData, archiveName, 242 offsetInArchive, lazy)); 243 return true; 244 } 245 246 // Opens a file and create a file object. Path has to be resolved already. 247 void LinkerDriver::addFile(StringRef path, bool withLOption) { 248 using namespace sys::fs; 249 250 std::optional<MemoryBufferRef> buffer = readFile(ctx, path); 251 if (!buffer) 252 return; 253 MemoryBufferRef mbref = *buffer; 254 255 if (ctx.arg.formatBinary) { 256 files.push_back(std::make_unique<BinaryFile>(ctx, mbref)); 257 return; 258 } 259 260 switch (identify_magic(mbref.getBuffer())) { 261 case file_magic::unknown: 262 readLinkerScript(ctx, mbref); 263 return; 264 case file_magic::archive: { 265 auto members = getArchiveMembers(ctx, mbref); 266 if (inWholeArchive) { 267 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 268 if (isBitcode(p.first)) 269 files.push_back(std::make_unique<BitcodeFile>(ctx, p.first, path, 270 p.second, false)); 271 else if (!tryAddFatLTOFile(p.first, path, p.second, false)) 272 files.push_back(createObjFile(ctx, p.first, path)); 273 } 274 return; 275 } 276 277 archiveFiles.emplace_back(path, members.size()); 278 279 // Handle archives and --start-lib/--end-lib using the same code path. This 280 // scans all the ELF relocatable object files and bitcode files in the 281 // archive rather than just the index file, with the benefit that the 282 // symbols are only loaded once. For many projects archives see high 283 // utilization rates and it is a net performance win. --start-lib scans 284 // symbols in the same order that llvm-ar adds them to the index, so in the 285 // common case the semantics are identical. If the archive symbol table was 286 // created in a different order, or is incomplete, this strategy has 287 // different semantics. Such output differences are considered user error. 288 // 289 // All files within the archive get the same group ID to allow mutual 290 // references for --warn-backrefs. 291 SaveAndRestore saved(isInGroup, true); 292 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 293 auto magic = identify_magic(p.first.getBuffer()); 294 if (magic == file_magic::elf_relocatable) { 295 if (!tryAddFatLTOFile(p.first, path, p.second, true)) 296 files.push_back(createObjFile(ctx, p.first, path, true)); 297 } else if (magic == file_magic::bitcode) 298 files.push_back( 299 std::make_unique<BitcodeFile>(ctx, p.first, path, p.second, true)); 300 else 301 Warn(ctx) << path << ": archive member '" 302 << p.first.getBufferIdentifier() 303 << "' is neither ET_REL nor LLVM bitcode"; 304 } 305 if (!saved.get()) 306 ++nextGroupId; 307 return; 308 } 309 case file_magic::elf_shared_object: { 310 if (ctx.arg.isStatic) { 311 ErrAlways(ctx) << "attempted static link of dynamic object " << path; 312 return; 313 } 314 315 // Shared objects are identified by soname. soname is (if specified) 316 // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 317 // the directory part is ignored. Note that path may be a temporary and 318 // cannot be stored into SharedFile::soName. 319 path = mbref.getBufferIdentifier(); 320 auto f = std::make_unique<SharedFile>( 321 ctx, mbref, withLOption ? path::filename(path) : path); 322 f->init(); 323 files.push_back(std::move(f)); 324 return; 325 } 326 case file_magic::bitcode: 327 files.push_back(std::make_unique<BitcodeFile>(ctx, mbref, "", 0, inLib)); 328 break; 329 case file_magic::elf_relocatable: 330 if (!tryAddFatLTOFile(mbref, "", 0, inLib)) 331 files.push_back(createObjFile(ctx, mbref, "", inLib)); 332 break; 333 default: 334 ErrAlways(ctx) << path << ": unknown file type"; 335 } 336 } 337 338 // Add a given library by searching it from input search paths. 339 void LinkerDriver::addLibrary(StringRef name) { 340 if (std::optional<std::string> path = searchLibrary(ctx, name)) 341 addFile(ctx.saver.save(*path), /*withLOption=*/true); 342 else 343 ctx.e.error("unable to find library -l" + name, ErrorTag::LibNotFound, 344 {name}); 345 } 346 347 // This function is called on startup. We need this for LTO since 348 // LTO calls LLVM functions to compile bitcode files to native code. 349 // Technically this can be delayed until we read bitcode files, but 350 // we don't bother to do lazily because the initialization is fast. 351 static void initLLVM() { 352 InitializeAllTargets(); 353 InitializeAllTargetMCs(); 354 InitializeAllAsmPrinters(); 355 InitializeAllAsmParsers(); 356 } 357 358 // Some command line options or some combinations of them are not allowed. 359 // This function checks for such errors. 360 static void checkOptions(Ctx &ctx) { 361 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 362 // table which is a relatively new feature. 363 if (ctx.arg.emachine == EM_MIPS && ctx.arg.gnuHash) 364 ErrAlways(ctx) 365 << "the .gnu.hash section is not compatible with the MIPS target"; 366 367 if (ctx.arg.emachine == EM_ARM) { 368 if (!ctx.arg.cmseImplib) { 369 if (!ctx.arg.cmseInputLib.empty()) 370 ErrAlways(ctx) << "--in-implib may not be used without --cmse-implib"; 371 if (!ctx.arg.cmseOutputLib.empty()) 372 ErrAlways(ctx) << "--out-implib may not be used without --cmse-implib"; 373 } 374 } else { 375 if (ctx.arg.cmseImplib) 376 ErrAlways(ctx) << "--cmse-implib is only supported on ARM targets"; 377 if (!ctx.arg.cmseInputLib.empty()) 378 ErrAlways(ctx) << "--in-implib is only supported on ARM targets"; 379 if (!ctx.arg.cmseOutputLib.empty()) 380 ErrAlways(ctx) << "--out-implib is only supported on ARM targets"; 381 } 382 383 if (ctx.arg.fixCortexA53Errata843419 && ctx.arg.emachine != EM_AARCH64) 384 ErrAlways(ctx) 385 << "--fix-cortex-a53-843419 is only supported on AArch64 targets"; 386 387 if (ctx.arg.fixCortexA8 && ctx.arg.emachine != EM_ARM) 388 ErrAlways(ctx) << "--fix-cortex-a8 is only supported on ARM targets"; 389 390 if (ctx.arg.armBe8 && ctx.arg.emachine != EM_ARM) 391 ErrAlways(ctx) << "--be8 is only supported on ARM targets"; 392 393 if (ctx.arg.fixCortexA8 && !ctx.arg.isLE) 394 ErrAlways(ctx) << "--fix-cortex-a8 is not supported on big endian targets"; 395 396 if (ctx.arg.tocOptimize && ctx.arg.emachine != EM_PPC64) 397 ErrAlways(ctx) << "--toc-optimize is only supported on PowerPC64 targets"; 398 399 if (ctx.arg.pcRelOptimize && ctx.arg.emachine != EM_PPC64) 400 ErrAlways(ctx) << "--pcrel-optimize is only supported on PowerPC64 targets"; 401 402 if (ctx.arg.relaxGP && ctx.arg.emachine != EM_RISCV) 403 ErrAlways(ctx) << "--relax-gp is only supported on RISC-V targets"; 404 405 if (ctx.arg.pie && ctx.arg.shared) 406 ErrAlways(ctx) << "-shared and -pie may not be used together"; 407 408 if (!ctx.arg.shared && !ctx.arg.filterList.empty()) 409 ErrAlways(ctx) << "-F may not be used without -shared"; 410 411 if (!ctx.arg.shared && !ctx.arg.auxiliaryList.empty()) 412 ErrAlways(ctx) << "-f may not be used without -shared"; 413 414 if (ctx.arg.strip == StripPolicy::All && ctx.arg.emitRelocs) 415 ErrAlways(ctx) << "--strip-all and --emit-relocs may not be used together"; 416 417 if (ctx.arg.zText && ctx.arg.zIfuncNoplt) 418 ErrAlways(ctx) << "-z text and -z ifunc-noplt may not be used together"; 419 420 if (ctx.arg.relocatable) { 421 if (ctx.arg.shared) 422 ErrAlways(ctx) << "-r and -shared may not be used together"; 423 if (ctx.arg.gdbIndex) 424 ErrAlways(ctx) << "-r and --gdb-index may not be used together"; 425 if (ctx.arg.icf != ICFLevel::None) 426 ErrAlways(ctx) << "-r and --icf may not be used together"; 427 if (ctx.arg.pie) 428 ErrAlways(ctx) << "-r and -pie may not be used together"; 429 if (ctx.arg.exportDynamic) 430 ErrAlways(ctx) << "-r and --export-dynamic may not be used together"; 431 if (ctx.arg.debugNames) 432 ErrAlways(ctx) << "-r and --debug-names may not be used together"; 433 if (!ctx.arg.zSectionHeader) 434 ErrAlways(ctx) << "-r and -z nosectionheader may not be used together"; 435 } 436 437 if (ctx.arg.executeOnly) { 438 if (ctx.arg.emachine != EM_AARCH64) 439 ErrAlways(ctx) << "--execute-only is only supported on AArch64 targets"; 440 441 if (ctx.arg.singleRoRx && !ctx.script->hasSectionsCommand) 442 ErrAlways(ctx) 443 << "--execute-only and --no-rosegment cannot be used together"; 444 } 445 446 if (ctx.arg.zRetpolineplt && ctx.arg.zForceIbt) 447 ErrAlways(ctx) << "-z force-ibt may not be used with -z retpolineplt"; 448 449 if (ctx.arg.emachine != EM_AARCH64) { 450 if (ctx.arg.zPacPlt) 451 ErrAlways(ctx) << "-z pac-plt only supported on AArch64"; 452 if (ctx.arg.zForceBti) 453 ErrAlways(ctx) << "-z force-bti only supported on AArch64"; 454 if (ctx.arg.zBtiReport != "none") 455 ErrAlways(ctx) << "-z bti-report only supported on AArch64"; 456 if (ctx.arg.zPauthReport != "none") 457 ErrAlways(ctx) << "-z pauth-report only supported on AArch64"; 458 if (ctx.arg.zGcsReport != "none") 459 ErrAlways(ctx) << "-z gcs-report only supported on AArch64"; 460 if (ctx.arg.zGcs != GcsPolicy::Implicit) 461 ErrAlways(ctx) << "-z gcs only supported on AArch64"; 462 } 463 464 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 && 465 ctx.arg.zCetReport != "none") 466 ErrAlways(ctx) << "-z cet-report only supported on X86 and X86_64"; 467 } 468 469 static const char *getReproduceOption(opt::InputArgList &args) { 470 if (auto *arg = args.getLastArg(OPT_reproduce)) 471 return arg->getValue(); 472 return getenv("LLD_REPRODUCE"); 473 } 474 475 static bool hasZOption(opt::InputArgList &args, StringRef key) { 476 bool ret = false; 477 for (auto *arg : args.filtered(OPT_z)) 478 if (key == arg->getValue()) { 479 ret = true; 480 arg->claim(); 481 } 482 return ret; 483 } 484 485 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 486 bool defaultValue) { 487 for (auto *arg : args.filtered(OPT_z)) { 488 StringRef v = arg->getValue(); 489 if (k1 == v) 490 defaultValue = true; 491 else if (k2 == v) 492 defaultValue = false; 493 else 494 continue; 495 arg->claim(); 496 } 497 return defaultValue; 498 } 499 500 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 501 auto ret = SeparateSegmentKind::None; 502 for (auto *arg : args.filtered(OPT_z)) { 503 StringRef v = arg->getValue(); 504 if (v == "noseparate-code") 505 ret = SeparateSegmentKind::None; 506 else if (v == "separate-code") 507 ret = SeparateSegmentKind::Code; 508 else if (v == "separate-loadable-segments") 509 ret = SeparateSegmentKind::Loadable; 510 else 511 continue; 512 arg->claim(); 513 } 514 return ret; 515 } 516 517 static GnuStackKind getZGnuStack(opt::InputArgList &args) { 518 auto ret = GnuStackKind::NoExec; 519 for (auto *arg : args.filtered(OPT_z)) { 520 StringRef v = arg->getValue(); 521 if (v == "execstack") 522 ret = GnuStackKind::Exec; 523 else if (v == "noexecstack") 524 ret = GnuStackKind::NoExec; 525 else if (v == "nognustack") 526 ret = GnuStackKind::None; 527 else 528 continue; 529 arg->claim(); 530 } 531 return ret; 532 } 533 534 static uint8_t getZStartStopVisibility(Ctx &ctx, opt::InputArgList &args) { 535 uint8_t ret = STV_PROTECTED; 536 for (auto *arg : args.filtered(OPT_z)) { 537 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 538 if (kv.first == "start-stop-visibility") { 539 arg->claim(); 540 if (kv.second == "default") 541 ret = STV_DEFAULT; 542 else if (kv.second == "internal") 543 ret = STV_INTERNAL; 544 else if (kv.second == "hidden") 545 ret = STV_HIDDEN; 546 else if (kv.second == "protected") 547 ret = STV_PROTECTED; 548 else 549 ErrAlways(ctx) << "unknown -z start-stop-visibility= value: " 550 << StringRef(kv.second); 551 } 552 } 553 return ret; 554 } 555 556 static GcsPolicy getZGcs(Ctx &ctx, opt::InputArgList &args) { 557 GcsPolicy ret = GcsPolicy::Implicit; 558 for (auto *arg : args.filtered(OPT_z)) { 559 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 560 if (kv.first == "gcs") { 561 arg->claim(); 562 if (kv.second == "implicit") 563 ret = GcsPolicy::Implicit; 564 else if (kv.second == "never") 565 ret = GcsPolicy::Never; 566 else if (kv.second == "always") 567 ret = GcsPolicy::Always; 568 else 569 ErrAlways(ctx) << "unknown -z gcs= value: " << kv.second; 570 } 571 } 572 return ret; 573 } 574 575 // Report a warning for an unknown -z option. 576 static void checkZOptions(Ctx &ctx, opt::InputArgList &args) { 577 // This function is called before getTarget(), when certain options are not 578 // initialized yet. Claim them here. 579 args::getZOptionValue(args, OPT_z, "max-page-size", 0); 580 args::getZOptionValue(args, OPT_z, "common-page-size", 0); 581 getZFlag(args, "rel", "rela", false); 582 for (auto *arg : args.filtered(OPT_z)) 583 if (!arg->isClaimed()) 584 Warn(ctx) << "unknown -z value: " << StringRef(arg->getValue()); 585 } 586 587 constexpr const char *saveTempsValues[] = { 588 "resolution", "preopt", "promote", "internalize", "import", 589 "opt", "precodegen", "prelink", "combinedindex"}; 590 591 LinkerDriver::LinkerDriver(Ctx &ctx) : ctx(ctx) {} 592 593 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 594 ELFOptTable parser; 595 opt::InputArgList args = parser.parse(ctx, argsArr.slice(1)); 596 597 // Interpret these flags early because Err/Warn depend on them. 598 ctx.e.errorLimit = args::getInteger(args, OPT_error_limit, 20); 599 ctx.e.fatalWarnings = 600 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) && 601 !args.hasArg(OPT_no_warnings); 602 ctx.e.suppressWarnings = args.hasArg(OPT_no_warnings); 603 604 // Handle -help 605 if (args.hasArg(OPT_help)) { 606 printHelp(ctx); 607 return; 608 } 609 610 // Handle -v or -version. 611 // 612 // A note about "compatible with GNU linkers" message: this is a hack for 613 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 614 // a GNU compatible linker. See 615 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 616 // 617 // This is somewhat ugly hack, but in reality, we had no choice other 618 // than doing this. Considering the very long release cycle of Libtool, 619 // it is not easy to improve it to recognize LLD as a GNU compatible 620 // linker in a timely manner. Even if we can make it, there are still a 621 // lot of "configure" scripts out there that are generated by old version 622 // of Libtool. We cannot convince every software developer to migrate to 623 // the latest version and re-generate scripts. So we have this hack. 624 if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 625 Msg(ctx) << getLLDVersion() << " (compatible with GNU linkers)"; 626 627 if (const char *path = getReproduceOption(args)) { 628 // Note that --reproduce is a debug option so you can ignore it 629 // if you are trying to understand the whole picture of the code. 630 Expected<std::unique_ptr<TarWriter>> errOrWriter = 631 TarWriter::create(path, path::stem(path)); 632 if (errOrWriter) { 633 ctx.tar = std::move(*errOrWriter); 634 ctx.tar->append("response.txt", createResponseFile(args)); 635 ctx.tar->append("version.txt", getLLDVersion() + "\n"); 636 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 637 if (!ltoSampleProfile.empty()) 638 readFile(ctx, ltoSampleProfile); 639 } else { 640 ErrAlways(ctx) << "--reproduce: " << errOrWriter.takeError(); 641 } 642 } 643 644 readConfigs(ctx, args); 645 checkZOptions(ctx, args); 646 647 // The behavior of -v or --version is a bit strange, but this is 648 // needed for compatibility with GNU linkers. 649 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 650 return; 651 if (args.hasArg(OPT_version)) 652 return; 653 654 // Initialize time trace profiler. 655 if (ctx.arg.timeTraceEnabled) 656 timeTraceProfilerInitialize(ctx.arg.timeTraceGranularity, ctx.arg.progName); 657 658 { 659 llvm::TimeTraceScope timeScope("ExecuteLinker"); 660 661 initLLVM(); 662 createFiles(args); 663 if (errCount(ctx)) 664 return; 665 666 inferMachineType(); 667 setConfigs(ctx, args); 668 checkOptions(ctx); 669 if (errCount(ctx)) 670 return; 671 672 invokeELFT(link, args); 673 } 674 675 if (ctx.arg.timeTraceEnabled) { 676 checkError(ctx.e, timeTraceProfilerWrite( 677 args.getLastArgValue(OPT_time_trace_eq).str(), 678 ctx.arg.outputFile)); 679 timeTraceProfilerCleanup(); 680 } 681 } 682 683 static std::string getRpath(opt::InputArgList &args) { 684 SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath); 685 return llvm::join(v.begin(), v.end(), ":"); 686 } 687 688 // Determines what we should do if there are remaining unresolved 689 // symbols after the name resolution. 690 static void setUnresolvedSymbolPolicy(Ctx &ctx, opt::InputArgList &args) { 691 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 692 OPT_warn_unresolved_symbols, true) 693 ? UnresolvedPolicy::ReportError 694 : UnresolvedPolicy::Warn; 695 // -shared implies --unresolved-symbols=ignore-all because missing 696 // symbols are likely to be resolved at runtime. 697 bool diagRegular = !ctx.arg.shared, diagShlib = !ctx.arg.shared; 698 699 for (const opt::Arg *arg : args) { 700 switch (arg->getOption().getID()) { 701 case OPT_unresolved_symbols: { 702 StringRef s = arg->getValue(); 703 if (s == "ignore-all") { 704 diagRegular = false; 705 diagShlib = false; 706 } else if (s == "ignore-in-object-files") { 707 diagRegular = false; 708 diagShlib = true; 709 } else if (s == "ignore-in-shared-libs") { 710 diagRegular = true; 711 diagShlib = false; 712 } else if (s == "report-all") { 713 diagRegular = true; 714 diagShlib = true; 715 } else { 716 ErrAlways(ctx) << "unknown --unresolved-symbols value: " << s; 717 } 718 break; 719 } 720 case OPT_no_undefined: 721 diagRegular = true; 722 break; 723 case OPT_z: 724 if (StringRef(arg->getValue()) == "defs") 725 diagRegular = true; 726 else if (StringRef(arg->getValue()) == "undefs") 727 diagRegular = false; 728 else 729 break; 730 arg->claim(); 731 break; 732 case OPT_allow_shlib_undefined: 733 diagShlib = false; 734 break; 735 case OPT_no_allow_shlib_undefined: 736 diagShlib = true; 737 break; 738 } 739 } 740 741 ctx.arg.unresolvedSymbols = 742 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 743 ctx.arg.unresolvedSymbolsInShlib = 744 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 745 } 746 747 static Target2Policy getTarget2(Ctx &ctx, opt::InputArgList &args) { 748 StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 749 if (s == "rel") 750 return Target2Policy::Rel; 751 if (s == "abs") 752 return Target2Policy::Abs; 753 if (s == "got-rel") 754 return Target2Policy::GotRel; 755 ErrAlways(ctx) << "unknown --target2 option: " << s; 756 return Target2Policy::GotRel; 757 } 758 759 static bool isOutputFormatBinary(Ctx &ctx, opt::InputArgList &args) { 760 StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 761 if (s == "binary") 762 return true; 763 if (!s.starts_with("elf")) 764 ErrAlways(ctx) << "unknown --oformat value: " << s; 765 return false; 766 } 767 768 static DiscardPolicy getDiscard(opt::InputArgList &args) { 769 auto *arg = 770 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 771 if (!arg) 772 return DiscardPolicy::Default; 773 if (arg->getOption().getID() == OPT_discard_all) 774 return DiscardPolicy::All; 775 if (arg->getOption().getID() == OPT_discard_locals) 776 return DiscardPolicy::Locals; 777 return DiscardPolicy::None; 778 } 779 780 static StringRef getDynamicLinker(Ctx &ctx, opt::InputArgList &args) { 781 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 782 if (!arg) 783 return ""; 784 if (arg->getOption().getID() == OPT_no_dynamic_linker) { 785 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 786 ctx.arg.noDynamicLinker = true; 787 return ""; 788 } 789 return arg->getValue(); 790 } 791 792 static int getMemtagMode(Ctx &ctx, opt::InputArgList &args) { 793 StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode); 794 if (memtagModeArg.empty()) { 795 if (ctx.arg.androidMemtagStack) 796 Warn(ctx) << "--android-memtag-mode is unspecified, leaving " 797 "--android-memtag-stack a no-op"; 798 else if (ctx.arg.androidMemtagHeap) 799 Warn(ctx) << "--android-memtag-mode is unspecified, leaving " 800 "--android-memtag-heap a no-op"; 801 return ELF::NT_MEMTAG_LEVEL_NONE; 802 } 803 804 if (memtagModeArg == "sync") 805 return ELF::NT_MEMTAG_LEVEL_SYNC; 806 if (memtagModeArg == "async") 807 return ELF::NT_MEMTAG_LEVEL_ASYNC; 808 if (memtagModeArg == "none") 809 return ELF::NT_MEMTAG_LEVEL_NONE; 810 811 ErrAlways(ctx) << "unknown --android-memtag-mode value: \"" << memtagModeArg 812 << "\", should be one of {async, sync, none}"; 813 return ELF::NT_MEMTAG_LEVEL_NONE; 814 } 815 816 static ICFLevel getICF(opt::InputArgList &args) { 817 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 818 if (!arg || arg->getOption().getID() == OPT_icf_none) 819 return ICFLevel::None; 820 if (arg->getOption().getID() == OPT_icf_safe) 821 return ICFLevel::Safe; 822 return ICFLevel::All; 823 } 824 825 static StripPolicy getStrip(Ctx &ctx, opt::InputArgList &args) { 826 if (args.hasArg(OPT_relocatable)) 827 return StripPolicy::None; 828 if (!ctx.arg.zSectionHeader) 829 return StripPolicy::All; 830 831 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 832 if (!arg) 833 return StripPolicy::None; 834 if (arg->getOption().getID() == OPT_strip_all) 835 return StripPolicy::All; 836 return StripPolicy::Debug; 837 } 838 839 static uint64_t parseSectionAddress(Ctx &ctx, StringRef s, 840 opt::InputArgList &args, 841 const opt::Arg &arg) { 842 uint64_t va = 0; 843 s.consume_front("0x"); 844 if (!to_integer(s, va, 16)) 845 ErrAlways(ctx) << "invalid argument: " << arg.getAsString(args); 846 return va; 847 } 848 849 static StringMap<uint64_t> getSectionStartMap(Ctx &ctx, 850 opt::InputArgList &args) { 851 StringMap<uint64_t> ret; 852 for (auto *arg : args.filtered(OPT_section_start)) { 853 StringRef name; 854 StringRef addr; 855 std::tie(name, addr) = StringRef(arg->getValue()).split('='); 856 ret[name] = parseSectionAddress(ctx, addr, args, *arg); 857 } 858 859 if (auto *arg = args.getLastArg(OPT_Ttext)) 860 ret[".text"] = parseSectionAddress(ctx, arg->getValue(), args, *arg); 861 if (auto *arg = args.getLastArg(OPT_Tdata)) 862 ret[".data"] = parseSectionAddress(ctx, arg->getValue(), args, *arg); 863 if (auto *arg = args.getLastArg(OPT_Tbss)) 864 ret[".bss"] = parseSectionAddress(ctx, arg->getValue(), args, *arg); 865 return ret; 866 } 867 868 static SortSectionPolicy getSortSection(Ctx &ctx, opt::InputArgList &args) { 869 StringRef s = args.getLastArgValue(OPT_sort_section); 870 if (s == "alignment") 871 return SortSectionPolicy::Alignment; 872 if (s == "name") 873 return SortSectionPolicy::Name; 874 if (!s.empty()) 875 ErrAlways(ctx) << "unknown --sort-section rule: " << s; 876 return SortSectionPolicy::Default; 877 } 878 879 static OrphanHandlingPolicy getOrphanHandling(Ctx &ctx, 880 opt::InputArgList &args) { 881 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 882 if (s == "warn") 883 return OrphanHandlingPolicy::Warn; 884 if (s == "error") 885 return OrphanHandlingPolicy::Error; 886 if (s != "place") 887 ErrAlways(ctx) << "unknown --orphan-handling mode: " << s; 888 return OrphanHandlingPolicy::Place; 889 } 890 891 // Parse --build-id or --build-id=<style>. We handle "tree" as a 892 // synonym for "sha1" because all our hash functions including 893 // --build-id=sha1 are actually tree hashes for performance reasons. 894 static std::pair<BuildIdKind, SmallVector<uint8_t, 0>> 895 getBuildId(Ctx &ctx, opt::InputArgList &args) { 896 auto *arg = args.getLastArg(OPT_build_id); 897 if (!arg) 898 return {BuildIdKind::None, {}}; 899 900 StringRef s = arg->getValue(); 901 if (s == "fast") 902 return {BuildIdKind::Fast, {}}; 903 if (s == "md5") 904 return {BuildIdKind::Md5, {}}; 905 if (s == "sha1" || s == "tree") 906 return {BuildIdKind::Sha1, {}}; 907 if (s == "uuid") 908 return {BuildIdKind::Uuid, {}}; 909 if (s.starts_with("0x")) 910 return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 911 912 if (s != "none") 913 ErrAlways(ctx) << "unknown --build-id style: " << s; 914 return {BuildIdKind::None, {}}; 915 } 916 917 static std::pair<bool, bool> getPackDynRelocs(Ctx &ctx, 918 opt::InputArgList &args) { 919 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 920 if (s == "android") 921 return {true, false}; 922 if (s == "relr") 923 return {false, true}; 924 if (s == "android+relr") 925 return {true, true}; 926 927 if (s != "none") 928 ErrAlways(ctx) << "unknown --pack-dyn-relocs format: " << s; 929 return {false, false}; 930 } 931 932 static void readCallGraph(Ctx &ctx, MemoryBufferRef mb) { 933 // Build a map from symbol name to section 934 DenseMap<StringRef, Symbol *> map; 935 for (ELFFileBase *file : ctx.objectFiles) 936 for (Symbol *sym : file->getSymbols()) 937 map[sym->getName()] = sym; 938 939 auto findSection = [&](StringRef name) -> InputSectionBase * { 940 Symbol *sym = map.lookup(name); 941 if (!sym) { 942 if (ctx.arg.warnSymbolOrdering) 943 Warn(ctx) << mb.getBufferIdentifier() << ": no such symbol: " << name; 944 return nullptr; 945 } 946 maybeWarnUnorderableSymbol(ctx, sym); 947 948 if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 949 return dyn_cast_or_null<InputSectionBase>(dr->section); 950 return nullptr; 951 }; 952 953 for (StringRef line : args::getLines(mb)) { 954 SmallVector<StringRef, 3> fields; 955 line.split(fields, ' '); 956 uint64_t count; 957 958 if (fields.size() != 3 || !to_integer(fields[2], count)) { 959 ErrAlways(ctx) << mb.getBufferIdentifier() << ": parse error"; 960 return; 961 } 962 963 if (InputSectionBase *from = findSection(fields[0])) 964 if (InputSectionBase *to = findSection(fields[1])) 965 ctx.arg.callGraphProfile[std::make_pair(from, to)] += count; 966 } 967 } 968 969 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 970 // true and populates cgProfile and symbolIndices. 971 template <class ELFT> 972 static bool 973 processCallGraphRelocations(Ctx &ctx, SmallVector<uint32_t, 32> &symbolIndices, 974 ArrayRef<typename ELFT::CGProfile> &cgProfile, 975 ObjFile<ELFT> *inputObj) { 976 if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 977 return false; 978 979 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 980 inputObj->template getELFShdrs<ELFT>(); 981 symbolIndices.clear(); 982 const ELFFile<ELFT> &obj = inputObj->getObj(); 983 cgProfile = 984 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 985 objSections[inputObj->cgProfileSectionIndex])); 986 987 for (size_t i = 0, e = objSections.size(); i < e; ++i) { 988 const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 989 if (sec.sh_info == inputObj->cgProfileSectionIndex) { 990 if (sec.sh_type == SHT_CREL) { 991 auto crels = 992 CHECK(obj.crels(sec), "could not retrieve cg profile rela section"); 993 for (const auto &rel : crels.first) 994 symbolIndices.push_back(rel.getSymbol(false)); 995 for (const auto &rel : crels.second) 996 symbolIndices.push_back(rel.getSymbol(false)); 997 break; 998 } 999 if (sec.sh_type == SHT_RELA) { 1000 ArrayRef<typename ELFT::Rela> relas = 1001 CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 1002 for (const typename ELFT::Rela &rel : relas) 1003 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL)); 1004 break; 1005 } 1006 if (sec.sh_type == SHT_REL) { 1007 ArrayRef<typename ELFT::Rel> rels = 1008 CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 1009 for (const typename ELFT::Rel &rel : rels) 1010 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL)); 1011 break; 1012 } 1013 } 1014 } 1015 if (symbolIndices.empty()) 1016 Warn(ctx) 1017 << "SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"; 1018 return !symbolIndices.empty(); 1019 } 1020 1021 template <class ELFT> static void readCallGraphsFromObjectFiles(Ctx &ctx) { 1022 SmallVector<uint32_t, 32> symbolIndices; 1023 ArrayRef<typename ELFT::CGProfile> cgProfile; 1024 for (auto file : ctx.objectFiles) { 1025 auto *obj = cast<ObjFile<ELFT>>(file); 1026 if (!processCallGraphRelocations(ctx, symbolIndices, cgProfile, obj)) 1027 continue; 1028 1029 if (symbolIndices.size() != cgProfile.size() * 2) 1030 Fatal(ctx) << "number of relocations doesn't match Weights"; 1031 1032 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 1033 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 1034 uint32_t fromIndex = symbolIndices[i * 2]; 1035 uint32_t toIndex = symbolIndices[i * 2 + 1]; 1036 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 1037 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 1038 if (!fromSym || !toSym) 1039 continue; 1040 1041 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 1042 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 1043 if (from && to) 1044 ctx.arg.callGraphProfile[{from, to}] += cgpe.cgp_weight; 1045 } 1046 } 1047 } 1048 1049 template <class ELFT> 1050 static void ltoValidateAllVtablesHaveTypeInfos(Ctx &ctx, 1051 opt::InputArgList &args) { 1052 DenseSet<StringRef> typeInfoSymbols; 1053 SmallSetVector<StringRef, 0> vtableSymbols; 1054 auto processVtableAndTypeInfoSymbols = [&](StringRef name) { 1055 if (name.consume_front("_ZTI")) 1056 typeInfoSymbols.insert(name); 1057 else if (name.consume_front("_ZTV")) 1058 vtableSymbols.insert(name); 1059 }; 1060 1061 // Examine all native symbol tables. 1062 for (ELFFileBase *f : ctx.objectFiles) { 1063 using Elf_Sym = typename ELFT::Sym; 1064 for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) { 1065 if (s.st_shndx != SHN_UNDEF) { 1066 StringRef name = check(s.getName(f->getStringTable())); 1067 processVtableAndTypeInfoSymbols(name); 1068 } 1069 } 1070 } 1071 1072 for (SharedFile *f : ctx.sharedFiles) { 1073 using Elf_Sym = typename ELFT::Sym; 1074 for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) { 1075 if (s.st_shndx != SHN_UNDEF) { 1076 StringRef name = check(s.getName(f->getStringTable())); 1077 processVtableAndTypeInfoSymbols(name); 1078 } 1079 } 1080 } 1081 1082 SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI; 1083 for (StringRef s : vtableSymbols) 1084 if (!typeInfoSymbols.count(s)) 1085 vtableSymbolsWithNoRTTI.insert(s); 1086 1087 // Remove known safe symbols. 1088 for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) { 1089 StringRef knownSafeName = arg->getValue(); 1090 if (!knownSafeName.consume_front("_ZTV")) 1091 ErrAlways(ctx) 1092 << "--lto-known-safe-vtables=: expected symbol to start with _ZTV, " 1093 "but got " 1094 << knownSafeName; 1095 Expected<GlobPattern> pat = GlobPattern::create(knownSafeName); 1096 if (!pat) 1097 ErrAlways(ctx) << "--lto-known-safe-vtables=: " << pat.takeError(); 1098 vtableSymbolsWithNoRTTI.remove_if( 1099 [&](StringRef s) { return pat->match(s); }); 1100 } 1101 1102 ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty(); 1103 // Check for unmatched RTTI symbols 1104 for (StringRef s : vtableSymbolsWithNoRTTI) { 1105 Msg(ctx) << "--lto-validate-all-vtables-have-type-infos: RTTI missing for " 1106 "vtable " 1107 "_ZTV" 1108 << s << ", --lto-whole-program-visibility disabled"; 1109 } 1110 } 1111 1112 static CGProfileSortKind getCGProfileSortKind(Ctx &ctx, 1113 opt::InputArgList &args) { 1114 StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort"); 1115 if (s == "hfsort") 1116 return CGProfileSortKind::Hfsort; 1117 if (s == "cdsort") 1118 return CGProfileSortKind::Cdsort; 1119 if (s != "none") 1120 ErrAlways(ctx) << "unknown --call-graph-profile-sort= value: " << s; 1121 return CGProfileSortKind::None; 1122 } 1123 1124 static DebugCompressionType getCompressionType(Ctx &ctx, StringRef s, 1125 StringRef option) { 1126 DebugCompressionType type = StringSwitch<DebugCompressionType>(s) 1127 .Case("zlib", DebugCompressionType::Zlib) 1128 .Case("zstd", DebugCompressionType::Zstd) 1129 .Default(DebugCompressionType::None); 1130 if (type == DebugCompressionType::None) { 1131 if (s != "none") 1132 ErrAlways(ctx) << "unknown " << option << " value: " << s; 1133 } else if (const char *reason = compression::getReasonIfUnsupported( 1134 compression::formatFor(type))) { 1135 ErrAlways(ctx) << option << ": " << reason; 1136 } 1137 return type; 1138 } 1139 1140 static StringRef getAliasSpelling(opt::Arg *arg) { 1141 if (const opt::Arg *alias = arg->getAlias()) 1142 return alias->getSpelling(); 1143 return arg->getSpelling(); 1144 } 1145 1146 static std::pair<StringRef, StringRef> 1147 getOldNewOptions(Ctx &ctx, opt::InputArgList &args, unsigned id) { 1148 auto *arg = args.getLastArg(id); 1149 if (!arg) 1150 return {"", ""}; 1151 1152 StringRef s = arg->getValue(); 1153 std::pair<StringRef, StringRef> ret = s.split(';'); 1154 if (ret.second.empty()) 1155 ErrAlways(ctx) << getAliasSpelling(arg) 1156 << " expects 'old;new' format, but got " << s; 1157 return ret; 1158 } 1159 1160 // Parse options of the form "old;new[;extra]". 1161 static std::tuple<StringRef, StringRef, StringRef> 1162 getOldNewOptionsExtra(Ctx &ctx, opt::InputArgList &args, unsigned id) { 1163 auto [oldDir, second] = getOldNewOptions(ctx, args, id); 1164 auto [newDir, extraDir] = second.split(';'); 1165 return {oldDir, newDir, extraDir}; 1166 } 1167 1168 // Parse the symbol ordering file and warn for any duplicate entries. 1169 static SmallVector<StringRef, 0> getSymbolOrderingFile(Ctx &ctx, 1170 MemoryBufferRef mb) { 1171 SetVector<StringRef, SmallVector<StringRef, 0>> names; 1172 for (StringRef s : args::getLines(mb)) 1173 if (!names.insert(s) && ctx.arg.warnSymbolOrdering) 1174 Warn(ctx) << mb.getBufferIdentifier() 1175 << ": duplicate ordered symbol: " << s; 1176 1177 return names.takeVector(); 1178 } 1179 1180 static bool getIsRela(Ctx &ctx, opt::InputArgList &args) { 1181 // The psABI specifies the default relocation entry format. 1182 bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH, 1183 EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64}, 1184 ctx.arg.emachine); 1185 // If -z rel or -z rela is specified, use the last option. 1186 for (auto *arg : args.filtered(OPT_z)) { 1187 StringRef s(arg->getValue()); 1188 if (s == "rel") 1189 rela = false; 1190 else if (s == "rela") 1191 rela = true; 1192 else 1193 continue; 1194 arg->claim(); 1195 } 1196 return rela; 1197 } 1198 1199 static void parseClangOption(Ctx &ctx, StringRef opt, const Twine &msg) { 1200 std::string err; 1201 raw_string_ostream os(err); 1202 1203 const char *argv[] = {ctx.arg.progName.data(), opt.data()}; 1204 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 1205 return; 1206 ErrAlways(ctx) << msg << ": " << StringRef(err).trim(); 1207 } 1208 1209 // Checks the parameter of the bti-report and cet-report options. 1210 static bool isValidReportString(StringRef arg) { 1211 return arg == "none" || arg == "warning" || arg == "error"; 1212 } 1213 1214 // Process a remap pattern 'from-glob=to-file'. 1215 static bool remapInputs(Ctx &ctx, StringRef line, const Twine &location) { 1216 SmallVector<StringRef, 0> fields; 1217 line.split(fields, '='); 1218 if (fields.size() != 2 || fields[1].empty()) { 1219 ErrAlways(ctx) << location << ": parse error, not 'from-glob=to-file'"; 1220 return true; 1221 } 1222 if (!hasWildcard(fields[0])) 1223 ctx.arg.remapInputs[fields[0]] = fields[1]; 1224 else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) 1225 ctx.arg.remapInputsWildcards.emplace_back(std::move(*pat), fields[1]); 1226 else { 1227 ErrAlways(ctx) << location << ": " << pat.takeError() << ": " << fields[0]; 1228 return true; 1229 } 1230 return false; 1231 } 1232 1233 // Initializes Config members by the command line options. 1234 static void readConfigs(Ctx &ctx, opt::InputArgList &args) { 1235 ctx.e.verbose = args.hasArg(OPT_verbose); 1236 ctx.e.vsDiagnostics = 1237 args.hasArg(OPT_visual_studio_diagnostics_format, false); 1238 1239 ctx.arg.allowMultipleDefinition = 1240 hasZOption(args, "muldefs") || 1241 args.hasFlag(OPT_allow_multiple_definition, 1242 OPT_no_allow_multiple_definition, false); 1243 ctx.arg.androidMemtagHeap = 1244 args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false); 1245 ctx.arg.androidMemtagStack = args.hasFlag(OPT_android_memtag_stack, 1246 OPT_no_android_memtag_stack, false); 1247 ctx.arg.fatLTOObjects = 1248 args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false); 1249 ctx.arg.androidMemtagMode = getMemtagMode(ctx, args); 1250 ctx.arg.auxiliaryList = args::getStrings(args, OPT_auxiliary); 1251 ctx.arg.armBe8 = args.hasArg(OPT_be8); 1252 if (opt::Arg *arg = args.getLastArg( 1253 OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 1254 OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) { 1255 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 1256 ctx.arg.bsymbolic = BsymbolicKind::NonWeakFunctions; 1257 else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 1258 ctx.arg.bsymbolic = BsymbolicKind::Functions; 1259 else if (arg->getOption().matches(OPT_Bsymbolic_non_weak)) 1260 ctx.arg.bsymbolic = BsymbolicKind::NonWeak; 1261 else if (arg->getOption().matches(OPT_Bsymbolic)) 1262 ctx.arg.bsymbolic = BsymbolicKind::All; 1263 } 1264 ctx.arg.callGraphProfileSort = getCGProfileSortKind(ctx, args); 1265 ctx.arg.checkSections = 1266 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 1267 ctx.arg.chroot = args.getLastArgValue(OPT_chroot); 1268 if (auto *arg = args.getLastArg(OPT_compress_debug_sections)) { 1269 ctx.arg.compressDebugSections = 1270 getCompressionType(ctx, arg->getValue(), "--compress-debug-sections"); 1271 } 1272 ctx.arg.cref = args.hasArg(OPT_cref); 1273 ctx.arg.optimizeBBJumps = 1274 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 1275 ctx.arg.debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false); 1276 ctx.arg.demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1277 ctx.arg.dependencyFile = args.getLastArgValue(OPT_dependency_file); 1278 ctx.arg.dependentLibraries = 1279 args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 1280 ctx.arg.disableVerify = args.hasArg(OPT_disable_verify); 1281 ctx.arg.discard = getDiscard(args); 1282 ctx.arg.dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 1283 ctx.arg.dynamicLinker = getDynamicLinker(ctx, args); 1284 ctx.arg.ehFrameHdr = 1285 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 1286 ctx.arg.emitLLVM = args.hasArg(OPT_lto_emit_llvm); 1287 ctx.arg.emitRelocs = args.hasArg(OPT_emit_relocs); 1288 ctx.arg.enableNewDtags = 1289 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 1290 ctx.arg.enableNonContiguousRegions = 1291 args.hasArg(OPT_enable_non_contiguous_regions); 1292 ctx.arg.entry = args.getLastArgValue(OPT_entry); 1293 1294 ctx.e.errorHandlingScript = args.getLastArgValue(OPT_error_handling_script); 1295 1296 ctx.arg.executeOnly = 1297 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 1298 ctx.arg.exportDynamic = 1299 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) || 1300 args.hasArg(OPT_shared); 1301 ctx.arg.filterList = args::getStrings(args, OPT_filter); 1302 ctx.arg.fini = args.getLastArgValue(OPT_fini, "_fini"); 1303 ctx.arg.fixCortexA53Errata843419 = 1304 args.hasArg(OPT_fix_cortex_a53_843419) && !args.hasArg(OPT_relocatable); 1305 ctx.arg.cmseImplib = args.hasArg(OPT_cmse_implib); 1306 ctx.arg.cmseInputLib = args.getLastArgValue(OPT_in_implib); 1307 ctx.arg.cmseOutputLib = args.getLastArgValue(OPT_out_implib); 1308 ctx.arg.fixCortexA8 = 1309 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1310 ctx.arg.fortranCommon = 1311 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false); 1312 ctx.arg.gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 1313 ctx.arg.gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 1314 ctx.arg.gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 1315 ctx.arg.icf = getICF(args); 1316 ctx.arg.ignoreDataAddressEquality = 1317 args.hasArg(OPT_ignore_data_address_equality); 1318 ctx.arg.ignoreFunctionAddressEquality = 1319 args.hasArg(OPT_ignore_function_address_equality); 1320 ctx.arg.init = args.getLastArgValue(OPT_init, "_init"); 1321 ctx.arg.ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 1322 ctx.arg.ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1323 ctx.arg.ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1324 ctx.arg.ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1325 OPT_no_lto_pgo_warn_mismatch, true); 1326 ctx.arg.ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 1327 ctx.arg.ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 1328 ctx.arg.ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 1329 ctx.arg.ltoWholeProgramVisibility = 1330 args.hasFlag(OPT_lto_whole_program_visibility, 1331 OPT_no_lto_whole_program_visibility, false); 1332 ctx.arg.ltoValidateAllVtablesHaveTypeInfos = 1333 args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos, 1334 OPT_no_lto_validate_all_vtables_have_type_infos, false); 1335 ctx.arg.ltoo = args::getInteger(args, OPT_lto_O, 2); 1336 if (ctx.arg.ltoo > 3) 1337 ErrAlways(ctx) << "invalid optimization level for LTO: " << ctx.arg.ltoo; 1338 unsigned ltoCgo = 1339 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(ctx.arg.ltoo)); 1340 if (auto level = CodeGenOpt::getLevel(ltoCgo)) 1341 ctx.arg.ltoCgo = *level; 1342 else 1343 ErrAlways(ctx) << "invalid codegen optimization level for LTO: " << ltoCgo; 1344 ctx.arg.ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 1345 ctx.arg.ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 1346 ctx.arg.ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 1347 ctx.arg.ltoBBAddrMap = 1348 args.hasFlag(OPT_lto_basic_block_address_map, 1349 OPT_no_lto_basic_block_address_map, false); 1350 ctx.arg.ltoBasicBlockSections = 1351 args.getLastArgValue(OPT_lto_basic_block_sections); 1352 ctx.arg.ltoUniqueBasicBlockSectionNames = 1353 args.hasFlag(OPT_lto_unique_basic_block_section_names, 1354 OPT_no_lto_unique_basic_block_section_names, false); 1355 ctx.arg.mapFile = args.getLastArgValue(OPT_Map); 1356 ctx.arg.mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 1357 ctx.arg.mergeArmExidx = 1358 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1359 ctx.arg.mmapOutputFile = 1360 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 1361 ctx.arg.nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 1362 ctx.arg.noinhibitExec = args.hasArg(OPT_noinhibit_exec); 1363 ctx.arg.nostdlib = args.hasArg(OPT_nostdlib); 1364 ctx.arg.oFormatBinary = isOutputFormatBinary(ctx, args); 1365 ctx.arg.omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 1366 ctx.arg.optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 1367 ctx.arg.optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file); 1368 1369 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1370 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1371 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1372 if (!resultOrErr) 1373 ErrAlways(ctx) << arg->getSpelling() << ": invalid argument '" 1374 << arg->getValue() 1375 << "', only integer or 'auto' is supported"; 1376 else 1377 ctx.arg.optRemarksHotnessThreshold = *resultOrErr; 1378 } 1379 1380 ctx.arg.optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 1381 ctx.arg.optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 1382 ctx.arg.optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 1383 ctx.arg.optimize = args::getInteger(args, OPT_O, 1); 1384 ctx.arg.orphanHandling = getOrphanHandling(ctx, args); 1385 ctx.arg.outputFile = args.getLastArgValue(OPT_o); 1386 ctx.arg.packageMetadata = args.getLastArgValue(OPT_package_metadata); 1387 ctx.arg.pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 1388 ctx.arg.printIcfSections = 1389 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 1390 ctx.arg.printGcSections = 1391 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1392 ctx.arg.printMemoryUsage = args.hasArg(OPT_print_memory_usage); 1393 ctx.arg.printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 1394 ctx.arg.printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order); 1395 ctx.arg.rejectMismatch = !args.hasArg(OPT_no_warn_mismatch); 1396 ctx.arg.relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 1397 ctx.arg.relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false); 1398 ctx.arg.rpath = getRpath(args); 1399 ctx.arg.relocatable = args.hasArg(OPT_relocatable); 1400 ctx.arg.resolveGroups = 1401 !args.hasArg(OPT_relocatable) || args.hasArg(OPT_force_group_allocation); 1402 1403 if (args.hasArg(OPT_save_temps)) { 1404 // --save-temps implies saving all temps. 1405 for (const char *s : saveTempsValues) 1406 ctx.arg.saveTempsArgs.insert(s); 1407 } else { 1408 for (auto *arg : args.filtered(OPT_save_temps_eq)) { 1409 StringRef s = arg->getValue(); 1410 if (llvm::is_contained(saveTempsValues, s)) 1411 ctx.arg.saveTempsArgs.insert(s); 1412 else 1413 ErrAlways(ctx) << "unknown --save-temps value: " << s; 1414 } 1415 } 1416 1417 ctx.arg.searchPaths = args::getStrings(args, OPT_library_path); 1418 ctx.arg.sectionStartMap = getSectionStartMap(ctx, args); 1419 ctx.arg.shared = args.hasArg(OPT_shared); 1420 if (args.hasArg(OPT_randomize_section_padding)) 1421 ctx.arg.randomizeSectionPadding = 1422 args::getInteger(args, OPT_randomize_section_padding, 0); 1423 ctx.arg.singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 1424 ctx.arg.soName = args.getLastArgValue(OPT_soname); 1425 ctx.arg.sortSection = getSortSection(ctx, args); 1426 ctx.arg.splitStackAdjustSize = 1427 args::getInteger(args, OPT_split_stack_adjust_size, 16384); 1428 ctx.arg.zSectionHeader = 1429 getZFlag(args, "sectionheader", "nosectionheader", true); 1430 ctx.arg.strip = getStrip(ctx, args); // needs zSectionHeader 1431 ctx.arg.sysroot = args.getLastArgValue(OPT_sysroot); 1432 ctx.arg.target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 1433 ctx.arg.target2 = getTarget2(ctx, args); 1434 ctx.arg.thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 1435 ctx.arg.thinLTOCachePolicy = CHECK( 1436 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 1437 "--thinlto-cache-policy: invalid cache policy"); 1438 ctx.arg.thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1439 ctx.arg.thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) || 1440 args.hasArg(OPT_thinlto_index_only) || 1441 args.hasArg(OPT_thinlto_index_only_eq); 1442 ctx.arg.thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1443 args.hasArg(OPT_thinlto_index_only_eq); 1444 ctx.arg.thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 1445 ctx.arg.thinLTOObjectSuffixReplace = 1446 getOldNewOptions(ctx, args, OPT_thinlto_object_suffix_replace_eq); 1447 std::tie(ctx.arg.thinLTOPrefixReplaceOld, ctx.arg.thinLTOPrefixReplaceNew, 1448 ctx.arg.thinLTOPrefixReplaceNativeObject) = 1449 getOldNewOptionsExtra(ctx, args, OPT_thinlto_prefix_replace_eq); 1450 if (ctx.arg.thinLTOEmitIndexFiles && !ctx.arg.thinLTOIndexOnly) { 1451 if (args.hasArg(OPT_thinlto_object_suffix_replace_eq)) 1452 ErrAlways(ctx) << "--thinlto-object-suffix-replace is not supported with " 1453 "--thinlto-emit-index-files"; 1454 else if (args.hasArg(OPT_thinlto_prefix_replace_eq)) 1455 ErrAlways(ctx) << "--thinlto-prefix-replace is not supported with " 1456 "--thinlto-emit-index-files"; 1457 } 1458 if (!ctx.arg.thinLTOPrefixReplaceNativeObject.empty() && 1459 ctx.arg.thinLTOIndexOnlyArg.empty()) { 1460 ErrAlways(ctx) 1461 << "--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with " 1462 "--thinlto-index-only="; 1463 } 1464 ctx.arg.thinLTOModulesToCompile = 1465 args::getStrings(args, OPT_thinlto_single_module_eq); 1466 ctx.arg.timeTraceEnabled = 1467 args.hasArg(OPT_time_trace_eq) && !ctx.e.disableOutput; 1468 ctx.arg.timeTraceGranularity = 1469 args::getInteger(args, OPT_time_trace_granularity, 500); 1470 ctx.arg.trace = args.hasArg(OPT_trace); 1471 ctx.arg.undefined = args::getStrings(args, OPT_undefined); 1472 ctx.arg.undefinedVersion = 1473 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false); 1474 ctx.arg.unique = args.hasArg(OPT_unique); 1475 ctx.arg.useAndroidRelrTags = args.hasFlag( 1476 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 1477 ctx.arg.warnBackrefs = 1478 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 1479 ctx.arg.warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 1480 ctx.arg.warnSymbolOrdering = 1481 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1482 ctx.arg.whyExtract = args.getLastArgValue(OPT_why_extract); 1483 ctx.arg.zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 1484 ctx.arg.zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1485 ctx.arg.zForceBti = hasZOption(args, "force-bti"); 1486 ctx.arg.zForceIbt = hasZOption(args, "force-ibt"); 1487 ctx.arg.zGcs = getZGcs(ctx, args); 1488 ctx.arg.zGlobal = hasZOption(args, "global"); 1489 ctx.arg.zGnustack = getZGnuStack(args); 1490 ctx.arg.zHazardplt = hasZOption(args, "hazardplt"); 1491 ctx.arg.zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 1492 ctx.arg.zInitfirst = hasZOption(args, "initfirst"); 1493 ctx.arg.zInterpose = hasZOption(args, "interpose"); 1494 ctx.arg.zKeepTextSectionPrefix = getZFlag( 1495 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 1496 ctx.arg.zLrodataAfterBss = 1497 getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false); 1498 ctx.arg.zNoBtCfi = hasZOption(args, "nobtcfi"); 1499 ctx.arg.zNodefaultlib = hasZOption(args, "nodefaultlib"); 1500 ctx.arg.zNodelete = hasZOption(args, "nodelete"); 1501 ctx.arg.zNodlopen = hasZOption(args, "nodlopen"); 1502 ctx.arg.zNow = getZFlag(args, "now", "lazy", false); 1503 ctx.arg.zOrigin = hasZOption(args, "origin"); 1504 ctx.arg.zPacPlt = hasZOption(args, "pac-plt"); 1505 ctx.arg.zRelro = getZFlag(args, "relro", "norelro", true); 1506 ctx.arg.zRetpolineplt = hasZOption(args, "retpolineplt"); 1507 ctx.arg.zRodynamic = hasZOption(args, "rodynamic"); 1508 ctx.arg.zSeparate = getZSeparate(args); 1509 ctx.arg.zShstk = hasZOption(args, "shstk"); 1510 ctx.arg.zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1511 ctx.arg.zStartStopGC = 1512 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 1513 ctx.arg.zStartStopVisibility = getZStartStopVisibility(ctx, args); 1514 ctx.arg.zText = getZFlag(args, "text", "notext", true); 1515 ctx.arg.zWxneeded = hasZOption(args, "wxneeded"); 1516 setUnresolvedSymbolPolicy(ctx, args); 1517 ctx.arg.power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1518 1519 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1520 if (arg->getOption().matches(OPT_eb)) 1521 ctx.arg.optEB = true; 1522 else 1523 ctx.arg.optEL = true; 1524 } 1525 1526 for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) { 1527 StringRef value(arg->getValue()); 1528 remapInputs(ctx, value, arg->getSpelling()); 1529 } 1530 for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) { 1531 StringRef filename(arg->getValue()); 1532 std::optional<MemoryBufferRef> buffer = readFile(ctx, filename); 1533 if (!buffer) 1534 continue; 1535 // Parse 'from-glob=to-file' lines, ignoring #-led comments. 1536 for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer))) 1537 if (remapInputs(ctx, line, filename + ":" + Twine(lineno + 1))) 1538 break; 1539 } 1540 1541 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1542 constexpr StringRef errPrefix = "--shuffle-sections=: "; 1543 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1544 if (kv.first.empty() || kv.second.empty()) { 1545 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<seed>, but got '" 1546 << arg->getValue() << "'"; 1547 continue; 1548 } 1549 // Signed so that <section_glob>=-1 is allowed. 1550 int64_t v; 1551 if (!to_integer(kv.second, v)) 1552 ErrAlways(ctx) << errPrefix << "expected an integer, but got '" 1553 << kv.second << "'"; 1554 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1555 ctx.arg.shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1556 else 1557 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first; 1558 } 1559 1560 auto reports = {std::make_pair("bti-report", &ctx.arg.zBtiReport), 1561 std::make_pair("cet-report", &ctx.arg.zCetReport), 1562 std::make_pair("gcs-report", &ctx.arg.zGcsReport), 1563 std::make_pair("pauth-report", &ctx.arg.zPauthReport)}; 1564 for (opt::Arg *arg : args.filtered(OPT_z)) { 1565 std::pair<StringRef, StringRef> option = 1566 StringRef(arg->getValue()).split('='); 1567 for (auto reportArg : reports) { 1568 if (option.first != reportArg.first) 1569 continue; 1570 arg->claim(); 1571 if (!isValidReportString(option.second)) { 1572 ErrAlways(ctx) << "-z " << reportArg.first << "= parameter " 1573 << option.second << " is not recognized"; 1574 continue; 1575 } 1576 *reportArg.second = option.second; 1577 } 1578 } 1579 1580 for (opt::Arg *arg : args.filtered(OPT_compress_sections)) { 1581 SmallVector<StringRef, 0> fields; 1582 StringRef(arg->getValue()).split(fields, '='); 1583 if (fields.size() != 2 || fields[1].empty()) { 1584 ErrAlways(ctx) << arg->getSpelling() 1585 << ": parse error, not 'section-glob=[none|zlib|zstd]'"; 1586 continue; 1587 } 1588 auto [typeStr, levelStr] = fields[1].split(':'); 1589 auto type = getCompressionType(ctx, typeStr, arg->getSpelling()); 1590 unsigned level = 0; 1591 if (fields[1].size() != typeStr.size() && 1592 !llvm::to_integer(levelStr, level)) { 1593 ErrAlways(ctx) 1594 << arg->getSpelling() 1595 << ": expected a non-negative integer compression level, but got '" 1596 << levelStr << "'"; 1597 } 1598 if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) { 1599 ctx.arg.compressSections.emplace_back(std::move(*pat), type, level); 1600 } else { 1601 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError(); 1602 continue; 1603 } 1604 } 1605 1606 for (opt::Arg *arg : args.filtered(OPT_z)) { 1607 std::pair<StringRef, StringRef> option = 1608 StringRef(arg->getValue()).split('='); 1609 if (option.first != "dead-reloc-in-nonalloc") 1610 continue; 1611 arg->claim(); 1612 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1613 std::pair<StringRef, StringRef> kv = option.second.split('='); 1614 if (kv.first.empty() || kv.second.empty()) { 1615 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<value>"; 1616 continue; 1617 } 1618 uint64_t v; 1619 if (!to_integer(kv.second, v)) 1620 ErrAlways(ctx) << errPrefix 1621 << "expected a non-negative integer, but got '" 1622 << kv.second << "'"; 1623 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1624 ctx.arg.deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1625 else 1626 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first; 1627 } 1628 1629 cl::ResetAllOptionOccurrences(); 1630 1631 // Parse LTO options. 1632 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 1633 parseClangOption(ctx, ctx.saver.save("-mcpu=" + StringRef(arg->getValue())), 1634 arg->getSpelling()); 1635 1636 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1637 parseClangOption(ctx, std::string("-") + arg->getValue(), 1638 arg->getSpelling()); 1639 1640 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1641 // relative path. Just ignore. If not ended with "lto-wrapper" (or 1642 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an 1643 // unsupported LLVMgold.so option and error. 1644 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) { 1645 StringRef v(arg->getValue()); 1646 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe")) 1647 ErrAlways(ctx) << arg->getSpelling() << ": unknown plugin option '" 1648 << arg->getValue() << "'"; 1649 } 1650 1651 ctx.arg.passPlugins = args::getStrings(args, OPT_load_pass_plugins); 1652 1653 // Parse -mllvm options. 1654 for (const auto *arg : args.filtered(OPT_mllvm)) { 1655 parseClangOption(ctx, arg->getValue(), arg->getSpelling()); 1656 ctx.arg.mllvmOpts.emplace_back(arg->getValue()); 1657 } 1658 1659 ctx.arg.ltoKind = LtoKind::Default; 1660 if (auto *arg = args.getLastArg(OPT_lto)) { 1661 StringRef s = arg->getValue(); 1662 if (s == "thin") 1663 ctx.arg.ltoKind = LtoKind::UnifiedThin; 1664 else if (s == "full") 1665 ctx.arg.ltoKind = LtoKind::UnifiedRegular; 1666 else if (s == "default") 1667 ctx.arg.ltoKind = LtoKind::Default; 1668 else 1669 ErrAlways(ctx) << "unknown LTO mode: " << s; 1670 } 1671 1672 // --threads= takes a positive integer and provides the default value for 1673 // --thinlto-jobs=. If unspecified, cap the number of threads since 1674 // overhead outweighs optimization for used parallel algorithms for the 1675 // non-LTO parts. 1676 if (auto *arg = args.getLastArg(OPT_threads)) { 1677 StringRef v(arg->getValue()); 1678 unsigned threads = 0; 1679 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1680 ErrAlways(ctx) << arg->getSpelling() 1681 << ": expected a positive integer, but got '" 1682 << arg->getValue() << "'"; 1683 parallel::strategy = hardware_concurrency(threads); 1684 ctx.arg.thinLTOJobs = v; 1685 } else if (parallel::strategy.compute_thread_count() > 16) { 1686 Log(ctx) << "set maximum concurrency to 16, specify --threads= to change"; 1687 parallel::strategy = hardware_concurrency(16); 1688 } 1689 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 1690 ctx.arg.thinLTOJobs = arg->getValue(); 1691 ctx.arg.threadCount = parallel::strategy.compute_thread_count(); 1692 1693 if (ctx.arg.ltoPartitions == 0) 1694 ErrAlways(ctx) << "--lto-partitions: number of threads must be > 0"; 1695 if (!get_threadpool_strategy(ctx.arg.thinLTOJobs)) 1696 ErrAlways(ctx) << "--thinlto-jobs: invalid job count: " 1697 << ctx.arg.thinLTOJobs; 1698 1699 if (ctx.arg.splitStackAdjustSize < 0) 1700 ErrAlways(ctx) << "--split-stack-adjust-size: size must be >= 0"; 1701 1702 // The text segment is traditionally the first segment, whose address equals 1703 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1704 // is an old-fashioned option that does not play well with lld's layout. 1705 // Suggest --image-base as a likely alternative. 1706 if (args.hasArg(OPT_Ttext_segment)) 1707 ErrAlways(ctx) 1708 << "-Ttext-segment is not supported. Use --image-base if you " 1709 "intend to set the base address"; 1710 1711 // Parse ELF{32,64}{LE,BE} and CPU type. 1712 if (auto *arg = args.getLastArg(OPT_m)) { 1713 StringRef s = arg->getValue(); 1714 std::tie(ctx.arg.ekind, ctx.arg.emachine, ctx.arg.osabi) = 1715 parseEmulation(ctx, s); 1716 ctx.arg.mipsN32Abi = 1717 (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32")); 1718 ctx.arg.emulation = s; 1719 } 1720 1721 // Parse --hash-style={sysv,gnu,both}. 1722 if (auto *arg = args.getLastArg(OPT_hash_style)) { 1723 StringRef s = arg->getValue(); 1724 if (s == "sysv") 1725 ctx.arg.sysvHash = true; 1726 else if (s == "gnu") 1727 ctx.arg.gnuHash = true; 1728 else if (s == "both") 1729 ctx.arg.sysvHash = ctx.arg.gnuHash = true; 1730 else 1731 ErrAlways(ctx) << "unknown --hash-style: " << s; 1732 } 1733 1734 if (args.hasArg(OPT_print_map)) 1735 ctx.arg.mapFile = "-"; 1736 1737 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 1738 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1739 // it. Also disable RELRO for -r. 1740 if (ctx.arg.nmagic || ctx.arg.omagic || ctx.arg.relocatable) 1741 ctx.arg.zRelro = false; 1742 1743 std::tie(ctx.arg.buildId, ctx.arg.buildIdVector) = getBuildId(ctx, args); 1744 1745 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) { 1746 ctx.arg.relrGlibc = true; 1747 ctx.arg.relrPackDynRelocs = true; 1748 } else { 1749 std::tie(ctx.arg.androidPackDynRelocs, ctx.arg.relrPackDynRelocs) = 1750 getPackDynRelocs(ctx, args); 1751 } 1752 1753 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 1754 if (args.hasArg(OPT_call_graph_ordering_file)) 1755 ErrAlways(ctx) << "--symbol-ordering-file and --call-graph-order-file " 1756 "may not be used together"; 1757 if (auto buffer = readFile(ctx, arg->getValue())) 1758 ctx.arg.symbolOrderingFile = getSymbolOrderingFile(ctx, *buffer); 1759 } 1760 1761 assert(ctx.arg.versionDefinitions.empty()); 1762 ctx.arg.versionDefinitions.push_back( 1763 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 1764 ctx.arg.versionDefinitions.push_back( 1765 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 1766 1767 // If --retain-symbol-file is used, we'll keep only the symbols listed in 1768 // the file and discard all others. 1769 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 1770 ctx.arg.versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 1771 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1772 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue())) 1773 for (StringRef s : args::getLines(*buffer)) 1774 ctx.arg.versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 1775 {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 1776 } 1777 1778 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1779 StringRef pattern(arg->getValue()); 1780 if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1781 ctx.arg.warnBackrefsExclude.push_back(std::move(*pat)); 1782 else 1783 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError() << ": " 1784 << pattern; 1785 } 1786 1787 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1788 // which should be exported. For -shared, references to matched non-local 1789 // STV_DEFAULT symbols are not bound to definitions within the shared object, 1790 // even if other options express a symbolic intention: -Bsymbolic, 1791 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 1792 for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 1793 ctx.arg.dynamicList.push_back( 1794 {arg->getValue(), /*isExternCpp=*/false, 1795 /*hasWildcard=*/hasWildcard(arg->getValue())}); 1796 1797 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1798 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1799 // like semantics. 1800 ctx.arg.symbolic = 1801 ctx.arg.bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1802 for (auto *arg : 1803 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1804 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue())) 1805 readDynamicList(ctx, *buffer); 1806 1807 for (auto *arg : args.filtered(OPT_version_script)) 1808 if (std::optional<std::string> path = searchScript(ctx, arg->getValue())) { 1809 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, *path)) 1810 readVersionScript(ctx, *buffer); 1811 } else { 1812 ErrAlways(ctx) << "cannot find version script " << arg->getValue(); 1813 } 1814 } 1815 1816 // Some Config members do not directly correspond to any particular 1817 // command line options, but computed based on other Config values. 1818 // This function initialize such members. See Config.h for the details 1819 // of these values. 1820 static void setConfigs(Ctx &ctx, opt::InputArgList &args) { 1821 ELFKind k = ctx.arg.ekind; 1822 uint16_t m = ctx.arg.emachine; 1823 1824 ctx.arg.copyRelocs = (ctx.arg.relocatable || ctx.arg.emitRelocs); 1825 ctx.arg.is64 = (k == ELF64LEKind || k == ELF64BEKind); 1826 ctx.arg.isLE = (k == ELF32LEKind || k == ELF64LEKind); 1827 ctx.arg.endianness = ctx.arg.isLE ? endianness::little : endianness::big; 1828 ctx.arg.isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 1829 ctx.arg.isPic = ctx.arg.pie || ctx.arg.shared; 1830 ctx.arg.picThunk = args.hasArg(OPT_pic_veneer, ctx.arg.isPic); 1831 ctx.arg.wordsize = ctx.arg.is64 ? 8 : 4; 1832 1833 // ELF defines two different ways to store relocation addends as shown below: 1834 // 1835 // Rel: Addends are stored to the location where relocations are applied. It 1836 // cannot pack the full range of addend values for all relocation types, but 1837 // this only affects relocation types that we don't support emitting as 1838 // dynamic relocations (see getDynRel). 1839 // Rela: Addends are stored as part of relocation entry. 1840 // 1841 // In other words, Rela makes it easy to read addends at the price of extra 1842 // 4 or 8 byte for each relocation entry. 1843 // 1844 // We pick the format for dynamic relocations according to the psABI for each 1845 // processor, but a contrary choice can be made if the dynamic loader 1846 // supports. 1847 ctx.arg.isRela = getIsRela(ctx, args); 1848 1849 // If the output uses REL relocations we must store the dynamic relocation 1850 // addends to the output sections. We also store addends for RELA relocations 1851 // if --apply-dynamic-relocs is used. 1852 // We default to not writing the addends when using RELA relocations since 1853 // any standard conforming tool can find it in r_addend. 1854 ctx.arg.writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 1855 OPT_no_apply_dynamic_relocs, false) || 1856 !ctx.arg.isRela; 1857 // Validation of dynamic relocation addends is on by default for assertions 1858 // builds and disabled otherwise. This check is enabled when writeAddends is 1859 // true. 1860 #ifndef NDEBUG 1861 bool checkDynamicRelocsDefault = true; 1862 #else 1863 bool checkDynamicRelocsDefault = false; 1864 #endif 1865 ctx.arg.checkDynamicRelocs = 1866 args.hasFlag(OPT_check_dynamic_relocations, 1867 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 1868 ctx.arg.tocOptimize = 1869 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1870 ctx.arg.pcRelOptimize = 1871 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 1872 1873 if (!args.hasArg(OPT_hash_style)) { 1874 if (ctx.arg.emachine == EM_MIPS) 1875 ctx.arg.sysvHash = true; 1876 else 1877 ctx.arg.sysvHash = ctx.arg.gnuHash = true; 1878 } 1879 1880 // Set default entry point and output file if not specified by command line or 1881 // linker scripts. 1882 ctx.arg.warnMissingEntry = 1883 (!ctx.arg.entry.empty() || (!ctx.arg.shared && !ctx.arg.relocatable)); 1884 if (ctx.arg.entry.empty() && !ctx.arg.relocatable) 1885 ctx.arg.entry = ctx.arg.emachine == EM_MIPS ? "__start" : "_start"; 1886 if (ctx.arg.outputFile.empty()) 1887 ctx.arg.outputFile = "a.out"; 1888 1889 // Fail early if the output file or map file is not writable. If a user has a 1890 // long link, e.g. due to a large LTO link, they do not wish to run it and 1891 // find that it failed because there was a mistake in their command-line. 1892 { 1893 llvm::TimeTraceScope timeScope("Create output files"); 1894 if (auto e = tryCreateFile(ctx.arg.outputFile)) 1895 ErrAlways(ctx) << "cannot open output file " << ctx.arg.outputFile << ": " 1896 << e.message(); 1897 if (auto e = tryCreateFile(ctx.arg.mapFile)) 1898 ErrAlways(ctx) << "cannot open map file " << ctx.arg.mapFile << ": " 1899 << e.message(); 1900 if (auto e = tryCreateFile(ctx.arg.whyExtract)) 1901 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract 1902 << ": " << e.message(); 1903 } 1904 } 1905 1906 static bool isFormatBinary(Ctx &ctx, StringRef s) { 1907 if (s == "binary") 1908 return true; 1909 if (s == "elf" || s == "default") 1910 return false; 1911 ErrAlways(ctx) << "unknown --format value: " << s 1912 << " (supported formats: elf, default, binary)"; 1913 return false; 1914 } 1915 1916 void LinkerDriver::createFiles(opt::InputArgList &args) { 1917 llvm::TimeTraceScope timeScope("Load input files"); 1918 // For --{push,pop}-state. 1919 std::vector<std::tuple<bool, bool, bool>> stack; 1920 1921 // -r implies -Bstatic and has precedence over -Bdynamic. 1922 ctx.arg.isStatic = ctx.arg.relocatable; 1923 1924 // Iterate over argv to process input files and positional arguments. 1925 std::optional<MemoryBufferRef> defaultScript; 1926 nextGroupId = 0; 1927 isInGroup = false; 1928 bool hasInput = false, hasScript = false; 1929 for (auto *arg : args) { 1930 switch (arg->getOption().getID()) { 1931 case OPT_library: 1932 addLibrary(arg->getValue()); 1933 hasInput = true; 1934 break; 1935 case OPT_INPUT: 1936 addFile(arg->getValue(), /*withLOption=*/false); 1937 hasInput = true; 1938 break; 1939 case OPT_defsym: { 1940 readDefsym(ctx, MemoryBufferRef(arg->getValue(), "--defsym")); 1941 break; 1942 } 1943 case OPT_script: 1944 case OPT_default_script: 1945 if (std::optional<std::string> path = 1946 searchScript(ctx, arg->getValue())) { 1947 if (std::optional<MemoryBufferRef> mb = readFile(ctx, *path)) { 1948 if (arg->getOption().matches(OPT_default_script)) { 1949 defaultScript = mb; 1950 } else { 1951 readLinkerScript(ctx, *mb); 1952 hasScript = true; 1953 } 1954 } 1955 break; 1956 } 1957 ErrAlways(ctx) << "cannot find linker script " << arg->getValue(); 1958 break; 1959 case OPT_as_needed: 1960 ctx.arg.asNeeded = true; 1961 break; 1962 case OPT_format: 1963 ctx.arg.formatBinary = isFormatBinary(ctx, arg->getValue()); 1964 break; 1965 case OPT_no_as_needed: 1966 ctx.arg.asNeeded = false; 1967 break; 1968 case OPT_Bstatic: 1969 case OPT_omagic: 1970 case OPT_nmagic: 1971 ctx.arg.isStatic = true; 1972 break; 1973 case OPT_Bdynamic: 1974 if (!ctx.arg.relocatable) 1975 ctx.arg.isStatic = false; 1976 break; 1977 case OPT_whole_archive: 1978 inWholeArchive = true; 1979 break; 1980 case OPT_no_whole_archive: 1981 inWholeArchive = false; 1982 break; 1983 case OPT_just_symbols: 1984 if (std::optional<MemoryBufferRef> mb = readFile(ctx, arg->getValue())) { 1985 files.push_back(createObjFile(ctx, *mb)); 1986 files.back()->justSymbols = true; 1987 } 1988 break; 1989 case OPT_in_implib: 1990 if (armCmseImpLib) 1991 ErrAlways(ctx) << "multiple CMSE import libraries not supported"; 1992 else if (std::optional<MemoryBufferRef> mb = 1993 readFile(ctx, arg->getValue())) 1994 armCmseImpLib = createObjFile(ctx, *mb); 1995 break; 1996 case OPT_start_group: 1997 if (isInGroup) 1998 ErrAlways(ctx) << "nested --start-group"; 1999 isInGroup = true; 2000 break; 2001 case OPT_end_group: 2002 if (!isInGroup) 2003 ErrAlways(ctx) << "stray --end-group"; 2004 isInGroup = false; 2005 ++nextGroupId; 2006 break; 2007 case OPT_start_lib: 2008 if (inLib) 2009 ErrAlways(ctx) << "nested --start-lib"; 2010 if (isInGroup) 2011 ErrAlways(ctx) << "may not nest --start-lib in --start-group"; 2012 inLib = true; 2013 isInGroup = true; 2014 break; 2015 case OPT_end_lib: 2016 if (!inLib) 2017 ErrAlways(ctx) << "stray --end-lib"; 2018 inLib = false; 2019 isInGroup = false; 2020 ++nextGroupId; 2021 break; 2022 case OPT_push_state: 2023 stack.emplace_back(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive); 2024 break; 2025 case OPT_pop_state: 2026 if (stack.empty()) { 2027 ErrAlways(ctx) << "unbalanced --push-state/--pop-state"; 2028 break; 2029 } 2030 std::tie(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive) = 2031 stack.back(); 2032 stack.pop_back(); 2033 break; 2034 } 2035 } 2036 2037 if (defaultScript && !hasScript) 2038 readLinkerScript(ctx, *defaultScript); 2039 if (files.empty() && !hasInput && errCount(ctx) == 0) 2040 ErrAlways(ctx) << "no input files"; 2041 } 2042 2043 // If -m <machine_type> was not given, infer it from object files. 2044 void LinkerDriver::inferMachineType() { 2045 if (ctx.arg.ekind != ELFNoneKind) 2046 return; 2047 2048 bool inferred = false; 2049 for (auto &f : files) { 2050 if (f->ekind == ELFNoneKind) 2051 continue; 2052 if (!inferred) { 2053 inferred = true; 2054 ctx.arg.ekind = f->ekind; 2055 ctx.arg.emachine = f->emachine; 2056 ctx.arg.mipsN32Abi = ctx.arg.emachine == EM_MIPS && isMipsN32Abi(ctx, *f); 2057 } 2058 ctx.arg.osabi = f->osabi; 2059 if (f->osabi != ELFOSABI_NONE) 2060 return; 2061 } 2062 if (!inferred) 2063 ErrAlways(ctx) 2064 << "target emulation unknown: -m or at least one .o file required"; 2065 } 2066 2067 // Parse -z max-page-size=<value>. The default value is defined by 2068 // each target. 2069 static uint64_t getMaxPageSize(Ctx &ctx, opt::InputArgList &args) { 2070 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 2071 ctx.target->defaultMaxPageSize); 2072 if (!isPowerOf2_64(val)) { 2073 ErrAlways(ctx) << "max-page-size: value isn't a power of 2"; 2074 return ctx.target->defaultMaxPageSize; 2075 } 2076 if (ctx.arg.nmagic || ctx.arg.omagic) { 2077 if (val != ctx.target->defaultMaxPageSize) 2078 Warn(ctx) 2079 << "-z max-page-size set, but paging disabled by omagic or nmagic"; 2080 return 1; 2081 } 2082 return val; 2083 } 2084 2085 // Parse -z common-page-size=<value>. The default value is defined by 2086 // each target. 2087 static uint64_t getCommonPageSize(Ctx &ctx, opt::InputArgList &args) { 2088 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 2089 ctx.target->defaultCommonPageSize); 2090 if (!isPowerOf2_64(val)) { 2091 ErrAlways(ctx) << "common-page-size: value isn't a power of 2"; 2092 return ctx.target->defaultCommonPageSize; 2093 } 2094 if (ctx.arg.nmagic || ctx.arg.omagic) { 2095 if (val != ctx.target->defaultCommonPageSize) 2096 Warn(ctx) 2097 << "-z common-page-size set, but paging disabled by omagic or nmagic"; 2098 return 1; 2099 } 2100 // commonPageSize can't be larger than maxPageSize. 2101 if (val > ctx.arg.maxPageSize) 2102 val = ctx.arg.maxPageSize; 2103 return val; 2104 } 2105 2106 // Parses --image-base option. 2107 static std::optional<uint64_t> getImageBase(Ctx &ctx, opt::InputArgList &args) { 2108 // Because we are using `ctx.arg.maxPageSize` here, this function has to be 2109 // called after the variable is initialized. 2110 auto *arg = args.getLastArg(OPT_image_base); 2111 if (!arg) 2112 return std::nullopt; 2113 2114 StringRef s = arg->getValue(); 2115 uint64_t v; 2116 if (!to_integer(s, v)) { 2117 ErrAlways(ctx) << "--image-base: number expected, but got " << s; 2118 return 0; 2119 } 2120 if ((v % ctx.arg.maxPageSize) != 0) 2121 Warn(ctx) << "--image-base: address isn't multiple of page size: " << s; 2122 return v; 2123 } 2124 2125 // Parses `--exclude-libs=lib,lib,...`. 2126 // The library names may be delimited by commas or colons. 2127 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 2128 DenseSet<StringRef> ret; 2129 for (auto *arg : args.filtered(OPT_exclude_libs)) { 2130 StringRef s = arg->getValue(); 2131 for (;;) { 2132 size_t pos = s.find_first_of(",:"); 2133 if (pos == StringRef::npos) 2134 break; 2135 ret.insert(s.substr(0, pos)); 2136 s = s.substr(pos + 1); 2137 } 2138 ret.insert(s); 2139 } 2140 return ret; 2141 } 2142 2143 // Handles the --exclude-libs option. If a static library file is specified 2144 // by the --exclude-libs option, all public symbols from the archive become 2145 // private unless otherwise specified by version scripts or something. 2146 // A special library name "ALL" means all archive files. 2147 // 2148 // This is not a popular option, but some programs such as bionic libc use it. 2149 static void excludeLibs(Ctx &ctx, opt::InputArgList &args) { 2150 DenseSet<StringRef> libs = getExcludeLibs(args); 2151 bool all = libs.count("ALL"); 2152 2153 auto visit = [&](InputFile *file) { 2154 if (file->archiveName.empty() || 2155 !(all || libs.count(path::filename(file->archiveName)))) 2156 return; 2157 ArrayRef<Symbol *> symbols = file->getSymbols(); 2158 if (isa<ELFFileBase>(file)) 2159 symbols = cast<ELFFileBase>(file)->getGlobalSymbols(); 2160 for (Symbol *sym : symbols) { 2161 if (!sym->isUndefined() && sym->file == file) { 2162 sym->versionId = VER_NDX_LOCAL; 2163 sym->isExported = false; 2164 } 2165 } 2166 }; 2167 2168 for (ELFFileBase *file : ctx.objectFiles) 2169 visit(file); 2170 2171 for (BitcodeFile *file : ctx.bitcodeFiles) 2172 visit(file); 2173 } 2174 2175 // Force Sym to be entered in the output. 2176 static void handleUndefined(Ctx &ctx, Symbol *sym, const char *option) { 2177 // Since a symbol may not be used inside the program, LTO may 2178 // eliminate it. Mark the symbol as "used" to prevent it. 2179 sym->isUsedInRegularObj = true; 2180 2181 if (!sym->isLazy()) 2182 return; 2183 sym->extract(ctx); 2184 if (!ctx.arg.whyExtract.empty()) 2185 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym); 2186 } 2187 2188 // As an extension to GNU linkers, lld supports a variant of `-u` 2189 // which accepts wildcard patterns. All symbols that match a given 2190 // pattern are handled as if they were given by `-u`. 2191 static void handleUndefinedGlob(Ctx &ctx, StringRef arg) { 2192 Expected<GlobPattern> pat = GlobPattern::create(arg); 2193 if (!pat) { 2194 ErrAlways(ctx) << "--undefined-glob: " << pat.takeError() << ": " << arg; 2195 return; 2196 } 2197 2198 // Calling sym->extract() in the loop is not safe because it may add new 2199 // symbols to the symbol table, invalidating the current iterator. 2200 SmallVector<Symbol *, 0> syms; 2201 for (Symbol *sym : ctx.symtab->getSymbols()) 2202 if (!sym->isPlaceholder() && pat->match(sym->getName())) 2203 syms.push_back(sym); 2204 2205 for (Symbol *sym : syms) 2206 handleUndefined(ctx, sym, "--undefined-glob"); 2207 } 2208 2209 static void handleLibcall(Ctx &ctx, StringRef name) { 2210 Symbol *sym = ctx.symtab->find(name); 2211 if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) { 2212 if (!ctx.arg.whyExtract.empty()) 2213 ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym); 2214 sym->extract(ctx); 2215 } 2216 } 2217 2218 static void writeArchiveStats(Ctx &ctx) { 2219 if (ctx.arg.printArchiveStats.empty()) 2220 return; 2221 2222 std::error_code ec; 2223 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.printArchiveStats, ec); 2224 if (ec) { 2225 ErrAlways(ctx) << "--print-archive-stats=: cannot open " 2226 << ctx.arg.printArchiveStats << ": " << ec.message(); 2227 return; 2228 } 2229 2230 os << "members\textracted\tarchive\n"; 2231 2232 SmallVector<StringRef, 0> archives; 2233 DenseMap<CachedHashStringRef, unsigned> all, extracted; 2234 for (ELFFileBase *file : ctx.objectFiles) 2235 if (file->archiveName.size()) 2236 ++extracted[CachedHashStringRef(file->archiveName)]; 2237 for (BitcodeFile *file : ctx.bitcodeFiles) 2238 if (file->archiveName.size()) 2239 ++extracted[CachedHashStringRef(file->archiveName)]; 2240 for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) { 2241 unsigned &v = extracted[CachedHashString(f.first)]; 2242 os << f.second << '\t' << v << '\t' << f.first << '\n'; 2243 // If the archive occurs multiple times, other instances have a count of 0. 2244 v = 0; 2245 } 2246 } 2247 2248 static void writeWhyExtract(Ctx &ctx) { 2249 if (ctx.arg.whyExtract.empty()) 2250 return; 2251 2252 std::error_code ec; 2253 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.whyExtract, ec); 2254 if (ec) { 2255 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract 2256 << ": " << ec.message(); 2257 return; 2258 } 2259 2260 os << "reference\textracted\tsymbol\n"; 2261 for (auto &entry : ctx.whyExtractRecords) { 2262 os << std::get<0>(entry) << '\t' << toStr(ctx, std::get<1>(entry)) << '\t' 2263 << toStr(ctx, std::get<2>(entry)) << '\n'; 2264 } 2265 } 2266 2267 static void reportBackrefs(Ctx &ctx) { 2268 for (auto &ref : ctx.backwardReferences) { 2269 const Symbol &sym = *ref.first; 2270 std::string to = toStr(ctx, ref.second.second); 2271 // Some libraries have known problems and can cause noise. Filter them out 2272 // with --warn-backrefs-exclude=. The value may look like (for --start-lib) 2273 // *.o or (archive member) *.a(*.o). 2274 bool exclude = false; 2275 for (const llvm::GlobPattern &pat : ctx.arg.warnBackrefsExclude) 2276 if (pat.match(to)) { 2277 exclude = true; 2278 break; 2279 } 2280 if (!exclude) 2281 Warn(ctx) << "backward reference detected: " << sym.getName() << " in " 2282 << ref.second.first << " refers to " << to; 2283 } 2284 } 2285 2286 // Handle --dependency-file=<path>. If that option is given, lld creates a 2287 // file at a given path with the following contents: 2288 // 2289 // <output-file>: <input-file> ... 2290 // 2291 // <input-file>: 2292 // 2293 // where <output-file> is a pathname of an output file and <input-file> 2294 // ... is a list of pathnames of all input files. `make` command can read a 2295 // file in the above format and interpret it as a dependency info. We write 2296 // phony targets for every <input-file> to avoid an error when that file is 2297 // removed. 2298 // 2299 // This option is useful if you want to make your final executable to depend 2300 // on all input files including system libraries. Here is why. 2301 // 2302 // When you write a Makefile, you usually write it so that the final 2303 // executable depends on all user-generated object files. Normally, you 2304 // don't make your executable to depend on system libraries (such as libc) 2305 // because you don't know the exact paths of libraries, even though system 2306 // libraries that are linked to your executable statically are technically a 2307 // part of your program. By using --dependency-file option, you can make 2308 // lld to dump dependency info so that you can maintain exact dependencies 2309 // easily. 2310 static void writeDependencyFile(Ctx &ctx) { 2311 std::error_code ec; 2312 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.dependencyFile, ec); 2313 if (ec) { 2314 ErrAlways(ctx) << "cannot open " << ctx.arg.dependencyFile << ": " 2315 << ec.message(); 2316 return; 2317 } 2318 2319 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 2320 // * A space is escaped by a backslash which itself must be escaped. 2321 // * A hash sign is escaped by a single backslash. 2322 // * $ is escapes as $$. 2323 auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 2324 llvm::SmallString<256> nativePath; 2325 llvm::sys::path::native(filename.str(), nativePath); 2326 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 2327 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 2328 if (nativePath[i] == '#') { 2329 os << '\\'; 2330 } else if (nativePath[i] == ' ') { 2331 os << '\\'; 2332 unsigned j = i; 2333 while (j > 0 && nativePath[--j] == '\\') 2334 os << '\\'; 2335 } else if (nativePath[i] == '$') { 2336 os << '$'; 2337 } 2338 os << nativePath[i]; 2339 } 2340 }; 2341 2342 os << ctx.arg.outputFile << ":"; 2343 for (StringRef path : ctx.arg.dependencyFiles) { 2344 os << " \\\n "; 2345 printFilename(os, path); 2346 } 2347 os << "\n"; 2348 2349 for (StringRef path : ctx.arg.dependencyFiles) { 2350 os << "\n"; 2351 printFilename(os, path); 2352 os << ":\n"; 2353 } 2354 } 2355 2356 // Replaces common symbols with defined symbols reside in .bss sections. 2357 // This function is called after all symbol names are resolved. As a 2358 // result, the passes after the symbol resolution won't see any 2359 // symbols of type CommonSymbol. 2360 static void replaceCommonSymbols(Ctx &ctx) { 2361 llvm::TimeTraceScope timeScope("Replace common symbols"); 2362 for (ELFFileBase *file : ctx.objectFiles) { 2363 if (!file->hasCommonSyms) 2364 continue; 2365 for (Symbol *sym : file->getGlobalSymbols()) { 2366 auto *s = dyn_cast<CommonSymbol>(sym); 2367 if (!s) 2368 continue; 2369 2370 auto *bss = make<BssSection>(ctx, "COMMON", s->size, s->alignment); 2371 bss->file = s->file; 2372 ctx.inputSections.push_back(bss); 2373 Defined(ctx, s->file, StringRef(), s->binding, s->stOther, s->type, 2374 /*value=*/0, s->size, bss) 2375 .overwrite(*s); 2376 } 2377 } 2378 } 2379 2380 // The section referred to by `s` is considered address-significant. Set the 2381 // keepUnique flag on the section if appropriate. 2382 static void markAddrsig(bool icfSafe, Symbol *s) { 2383 // We don't need to keep text sections unique under --icf=all even if they 2384 // are address-significant. 2385 if (auto *d = dyn_cast_or_null<Defined>(s)) 2386 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) 2387 if (icfSafe || !(sec->flags & SHF_EXECINSTR)) 2388 sec->keepUnique = true; 2389 } 2390 2391 // Record sections that define symbols mentioned in --keep-unique <symbol> 2392 // and symbols referred to by address-significance tables. These sections are 2393 // ineligible for ICF. 2394 template <class ELFT> 2395 static void findKeepUniqueSections(Ctx &ctx, opt::InputArgList &args) { 2396 for (auto *arg : args.filtered(OPT_keep_unique)) { 2397 StringRef name = arg->getValue(); 2398 auto *d = dyn_cast_or_null<Defined>(ctx.symtab->find(name)); 2399 if (!d || !d->section) { 2400 Warn(ctx) << "could not find symbol " << name << " to keep unique"; 2401 continue; 2402 } 2403 if (auto *sec = dyn_cast<InputSectionBase>(d->section)) 2404 sec->keepUnique = true; 2405 } 2406 2407 // --icf=all --ignore-data-address-equality means that we can ignore 2408 // the dynsym and address-significance tables entirely. 2409 if (ctx.arg.icf == ICFLevel::All && ctx.arg.ignoreDataAddressEquality) 2410 return; 2411 2412 // Symbols in the dynsym could be address-significant in other executables 2413 // or DSOs, so we conservatively mark them as address-significant. 2414 bool icfSafe = ctx.arg.icf == ICFLevel::Safe; 2415 for (Symbol *sym : ctx.symtab->getSymbols()) 2416 if (sym->includeInDynsym(ctx)) 2417 markAddrsig(icfSafe, sym); 2418 2419 // Visit the address-significance table in each object file and mark each 2420 // referenced symbol as address-significant. 2421 for (InputFile *f : ctx.objectFiles) { 2422 auto *obj = cast<ObjFile<ELFT>>(f); 2423 ArrayRef<Symbol *> syms = obj->getSymbols(); 2424 if (obj->addrsigSec) { 2425 ArrayRef<uint8_t> contents = 2426 check(obj->getObj().getSectionContents(*obj->addrsigSec)); 2427 const uint8_t *cur = contents.begin(); 2428 while (cur != contents.end()) { 2429 unsigned size; 2430 const char *err = nullptr; 2431 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 2432 if (err) { 2433 Err(ctx) << f << ": could not decode addrsig section: " << err; 2434 break; 2435 } 2436 markAddrsig(icfSafe, syms[symIndex]); 2437 cur += size; 2438 } 2439 } else { 2440 // If an object file does not have an address-significance table, 2441 // conservatively mark all of its symbols as address-significant. 2442 for (Symbol *s : syms) 2443 markAddrsig(icfSafe, s); 2444 } 2445 } 2446 } 2447 2448 // This function reads a symbol partition specification section. These sections 2449 // are used to control which partition a symbol is allocated to. See 2450 // https://lld.llvm.org/Partitions.html for more details on partitions. 2451 template <typename ELFT> 2452 static void readSymbolPartitionSection(Ctx &ctx, InputSectionBase *s) { 2453 // Read the relocation that refers to the partition's entry point symbol. 2454 Symbol *sym; 2455 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 2456 auto readEntry = [](InputFile *file, const auto &rels) -> Symbol * { 2457 for (const auto &rel : rels) 2458 return &file->getRelocTargetSym(rel); 2459 return nullptr; 2460 }; 2461 if (rels.areRelocsCrel()) 2462 sym = readEntry(s->file, rels.crels); 2463 else if (rels.areRelocsRel()) 2464 sym = readEntry(s->file, rels.rels); 2465 else 2466 sym = readEntry(s->file, rels.relas); 2467 if (!isa_and_nonnull<Defined>(sym) || !sym->isExported) 2468 return; 2469 2470 StringRef partName = reinterpret_cast<const char *>(s->content().data()); 2471 for (Partition &part : ctx.partitions) { 2472 if (part.name == partName) { 2473 sym->partition = part.getNumber(ctx); 2474 return; 2475 } 2476 } 2477 2478 // Forbid partitions from being used on incompatible targets, and forbid them 2479 // from being used together with various linker features that assume a single 2480 // set of output sections. 2481 if (ctx.script->hasSectionsCommand) 2482 ErrAlways(ctx) << s->file 2483 << ": partitions cannot be used with the SECTIONS command"; 2484 if (ctx.script->hasPhdrsCommands()) 2485 ErrAlways(ctx) << s->file 2486 << ": partitions cannot be used with the PHDRS command"; 2487 if (!ctx.arg.sectionStartMap.empty()) 2488 ErrAlways(ctx) << s->file 2489 << ": partitions cannot be used with " 2490 "--section-start, -Ttext, -Tdata or -Tbss"; 2491 if (ctx.arg.emachine == EM_MIPS) 2492 ErrAlways(ctx) << s->file << ": partitions cannot be used on this target"; 2493 2494 // Impose a limit of no more than 254 partitions. This limit comes from the 2495 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 2496 // the amount of space devoted to the partition number in RankFlags. 2497 if (ctx.partitions.size() == 254) 2498 Fatal(ctx) << "may not have more than 254 partitions"; 2499 2500 ctx.partitions.emplace_back(ctx); 2501 Partition &newPart = ctx.partitions.back(); 2502 newPart.name = partName; 2503 sym->partition = newPart.getNumber(ctx); 2504 } 2505 2506 static void markBuffersAsDontNeed(Ctx &ctx, bool skipLinkedOutput) { 2507 // With --thinlto-index-only, all buffers are nearly unused from now on 2508 // (except symbol/section names used by infrequent passes). Mark input file 2509 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 2510 // thin link, saving memory. 2511 if (skipLinkedOutput) { 2512 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 2513 mb.dontNeedIfMmap(); 2514 return; 2515 } 2516 2517 // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 2518 DenseSet<const char *> bufs; 2519 for (BitcodeFile *file : ctx.bitcodeFiles) 2520 bufs.insert(file->mb.getBufferStart()); 2521 for (BitcodeFile *file : ctx.lazyBitcodeFiles) 2522 bufs.insert(file->mb.getBufferStart()); 2523 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 2524 if (bufs.count(mb.getBufferStart())) 2525 mb.dontNeedIfMmap(); 2526 } 2527 2528 // This function is where all the optimizations of link-time 2529 // optimization takes place. When LTO is in use, some input files are 2530 // not in native object file format but in the LLVM bitcode format. 2531 // This function compiles bitcode files into a few big native files 2532 // using LLVM functions and replaces bitcode symbols with the results. 2533 // Because all bitcode files that the program consists of are passed to 2534 // the compiler at once, it can do a whole-program optimization. 2535 template <class ELFT> 2536 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 2537 llvm::TimeTraceScope timeScope("LTO"); 2538 // Compile bitcode files and replace bitcode symbols. 2539 lto.reset(new BitcodeCompiler(ctx)); 2540 for (BitcodeFile *file : ctx.bitcodeFiles) 2541 lto->add(*file); 2542 2543 if (!ctx.bitcodeFiles.empty()) 2544 markBuffersAsDontNeed(ctx, skipLinkedOutput); 2545 2546 ltoObjectFiles = lto->compile(); 2547 for (auto &file : ltoObjectFiles) { 2548 auto *obj = cast<ObjFile<ELFT>>(file.get()); 2549 obj->parse(/*ignoreComdats=*/true); 2550 2551 // For defined symbols in non-relocatable output, 2552 // compute isExported and parse '@'. 2553 if (!ctx.arg.relocatable) 2554 for (Symbol *sym : obj->getGlobalSymbols()) { 2555 if (!sym->isDefined()) 2556 continue; 2557 if (ctx.hasDynsym && sym->includeInDynsym(ctx)) 2558 sym->isExported = true; 2559 if (sym->hasVersionSuffix) 2560 sym->parseSymbolVersion(ctx); 2561 } 2562 ctx.objectFiles.push_back(obj); 2563 } 2564 } 2565 2566 // The --wrap option is a feature to rename symbols so that you can write 2567 // wrappers for existing functions. If you pass `--wrap=foo`, all 2568 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2569 // expected to write `__wrap_foo` function as a wrapper). The original 2570 // symbol becomes accessible as `__real_foo`, so you can call that from your 2571 // wrapper. 2572 // 2573 // This data structure is instantiated for each --wrap option. 2574 struct WrappedSymbol { 2575 Symbol *sym; 2576 Symbol *real; 2577 Symbol *wrap; 2578 }; 2579 2580 // Handles --wrap option. 2581 // 2582 // This function instantiates wrapper symbols. At this point, they seem 2583 // like they are not being used at all, so we explicitly set some flags so 2584 // that LTO won't eliminate them. 2585 static std::vector<WrappedSymbol> addWrappedSymbols(Ctx &ctx, 2586 opt::InputArgList &args) { 2587 std::vector<WrappedSymbol> v; 2588 DenseSet<StringRef> seen; 2589 auto &ss = ctx.saver; 2590 for (auto *arg : args.filtered(OPT_wrap)) { 2591 StringRef name = arg->getValue(); 2592 if (!seen.insert(name).second) 2593 continue; 2594 2595 Symbol *sym = ctx.symtab->find(name); 2596 if (!sym) 2597 continue; 2598 2599 Symbol *wrap = 2600 ctx.symtab->addUnusedUndefined(ss.save("__wrap_" + name), sym->binding); 2601 2602 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after 2603 // processing __wrap_ as that may have referenced __real_. 2604 StringRef realName = ctx.saver.save("__real_" + name); 2605 if (Symbol *real = ctx.symtab->find(realName)) { 2606 ctx.symtab->addUnusedUndefined(name, sym->binding); 2607 // Update sym's binding, which will replace real's later in 2608 // SymbolTable::wrap. 2609 sym->binding = real->binding; 2610 } 2611 2612 Symbol *real = ctx.symtab->addUnusedUndefined(realName); 2613 v.push_back({sym, real, wrap}); 2614 2615 // We want to tell LTO not to inline symbols to be overwritten 2616 // because LTO doesn't know the final symbol contents after renaming. 2617 real->scriptDefined = true; 2618 sym->scriptDefined = true; 2619 2620 // If a symbol is referenced in any object file, bitcode file or shared 2621 // object, mark its redirection target (foo for __real_foo and __wrap_foo 2622 // for foo) as referenced after redirection, which will be used to tell LTO 2623 // to not eliminate the redirection target. If the object file defining the 2624 // symbol also references it, we cannot easily distinguish the case from 2625 // cases where the symbol is not referenced. Retain the redirection target 2626 // in this case because we choose to wrap symbol references regardless of 2627 // whether the symbol is defined 2628 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 2629 if (real->referenced || real->isDefined()) 2630 sym->referencedAfterWrap = true; 2631 if (sym->referenced || sym->isDefined()) 2632 wrap->referencedAfterWrap = true; 2633 } 2634 return v; 2635 } 2636 2637 static void combineVersionedSymbol(Ctx &ctx, Symbol &sym, 2638 DenseMap<Symbol *, Symbol *> &map) { 2639 const char *suffix1 = sym.getVersionSuffix(); 2640 if (suffix1[0] != '@' || suffix1[1] == '@') 2641 return; 2642 2643 // Check the existing symbol foo. We have two special cases to handle: 2644 // 2645 // * There is a definition of foo@v1 and foo@@v1. 2646 // * There is a definition of foo@v1 and foo. 2647 Defined *sym2 = dyn_cast_or_null<Defined>(ctx.symtab->find(sym.getName())); 2648 if (!sym2) 2649 return; 2650 const char *suffix2 = sym2->getVersionSuffix(); 2651 if (suffix2[0] == '@' && suffix2[1] == '@' && 2652 strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2653 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 2654 map.try_emplace(&sym, sym2); 2655 // If both foo@v1 and foo@@v1 are defined and non-weak, report a 2656 // duplicate definition error. 2657 if (sym.isDefined()) { 2658 sym2->checkDuplicate(ctx, cast<Defined>(sym)); 2659 sym2->resolve(ctx, cast<Defined>(sym)); 2660 } else if (sym.isUndefined()) { 2661 sym2->resolve(ctx, cast<Undefined>(sym)); 2662 } else { 2663 sym2->resolve(ctx, cast<SharedSymbol>(sym)); 2664 } 2665 // Eliminate foo@v1 from the symbol table. 2666 sym.symbolKind = Symbol::PlaceholderKind; 2667 sym.isUsedInRegularObj = false; 2668 } else if (auto *sym1 = dyn_cast<Defined>(&sym)) { 2669 if (sym2->versionId > VER_NDX_GLOBAL 2670 ? ctx.arg.versionDefinitions[sym2->versionId].name == suffix1 + 1 2671 : sym1->section == sym2->section && sym1->value == sym2->value) { 2672 // Due to an assembler design flaw, if foo is defined, .symver foo, 2673 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2674 // different version, GNU ld makes foo@v1 canonical and eliminates 2675 // foo. Emulate its behavior, otherwise we would have foo or foo@@v1 2676 // beside foo@v1. foo@v1 and foo combining does not apply if they are 2677 // not defined in the same place. 2678 map.try_emplace(sym2, &sym); 2679 sym2->symbolKind = Symbol::PlaceholderKind; 2680 sym2->isUsedInRegularObj = false; 2681 } 2682 } 2683 } 2684 2685 // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 2686 // 2687 // When this function is executed, only InputFiles and symbol table 2688 // contain pointers to symbol objects. We visit them to replace pointers, 2689 // so that wrapped symbols are swapped as instructed by the command line. 2690 static void redirectSymbols(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) { 2691 llvm::TimeTraceScope timeScope("Redirect symbols"); 2692 DenseMap<Symbol *, Symbol *> map; 2693 for (const WrappedSymbol &w : wrapped) { 2694 map[w.sym] = w.wrap; 2695 map[w.real] = w.sym; 2696 } 2697 2698 // If there are version definitions (versionDefinitions.size() > 2), enumerate 2699 // symbols with a non-default version (foo@v1) and check whether it should be 2700 // combined with foo or foo@@v1. 2701 if (ctx.arg.versionDefinitions.size() > 2) 2702 for (Symbol *sym : ctx.symtab->getSymbols()) 2703 if (sym->hasVersionSuffix) 2704 combineVersionedSymbol(ctx, *sym, map); 2705 2706 if (map.empty()) 2707 return; 2708 2709 // Update pointers in input files. 2710 parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) { 2711 for (Symbol *&sym : file->getMutableGlobalSymbols()) 2712 if (Symbol *s = map.lookup(sym)) 2713 sym = s; 2714 }); 2715 2716 // Update pointers in the symbol table. 2717 for (const WrappedSymbol &w : wrapped) 2718 ctx.symtab->wrap(w.sym, w.real, w.wrap); 2719 } 2720 2721 // To enable CET (x86's hardware-assisted control flow enforcement), each 2722 // source file must be compiled with -fcf-protection. Object files compiled 2723 // with the flag contain feature flags indicating that they are compatible 2724 // with CET. We enable the feature only when all object files are compatible 2725 // with CET. 2726 // 2727 // This is also the case with AARCH64's BTI and PAC which use the similar 2728 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 2729 // 2730 // For AArch64 PAuth-enabled object files, the core info of all of them must 2731 // match. Missing info for some object files with matching info for remaining 2732 // ones can be allowed (see -z pauth-report). 2733 static void readSecurityNotes(Ctx &ctx) { 2734 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 && 2735 ctx.arg.emachine != EM_AARCH64) 2736 return; 2737 2738 ctx.arg.andFeatures = -1; 2739 2740 StringRef referenceFileName; 2741 if (ctx.arg.emachine == EM_AARCH64) { 2742 auto it = llvm::find_if(ctx.objectFiles, [](const ELFFileBase *f) { 2743 return !f->aarch64PauthAbiCoreInfo.empty(); 2744 }); 2745 if (it != ctx.objectFiles.end()) { 2746 ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo; 2747 referenceFileName = (*it)->getName(); 2748 } 2749 } 2750 bool hasValidPauthAbiCoreInfo = llvm::any_of( 2751 ctx.aarch64PauthAbiCoreInfo, [](uint8_t c) { return c != 0; }); 2752 2753 auto report = [&](StringRef config) -> ELFSyncStream { 2754 if (config == "error") 2755 return {ctx, DiagLevel::Err}; 2756 else if (config == "warning") 2757 return {ctx, DiagLevel::Warn}; 2758 return {ctx, DiagLevel::None}; 2759 }; 2760 auto reportUnless = [&](StringRef config, bool cond) -> ELFSyncStream { 2761 if (cond) 2762 return {ctx, DiagLevel::None}; 2763 return report(config); 2764 }; 2765 for (ELFFileBase *f : ctx.objectFiles) { 2766 uint32_t features = f->andFeatures; 2767 2768 reportUnless(ctx.arg.zBtiReport, 2769 features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI) 2770 << f 2771 << ": -z bti-report: file does not have " 2772 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"; 2773 2774 reportUnless(ctx.arg.zGcsReport, 2775 features & GNU_PROPERTY_AARCH64_FEATURE_1_GCS) 2776 << f 2777 << ": -z gcs-report: file does not have " 2778 "GNU_PROPERTY_AARCH64_FEATURE_1_GCS property"; 2779 2780 reportUnless(ctx.arg.zCetReport, features & GNU_PROPERTY_X86_FEATURE_1_IBT) 2781 << f 2782 << ": -z cet-report: file does not have " 2783 "GNU_PROPERTY_X86_FEATURE_1_IBT property"; 2784 2785 reportUnless(ctx.arg.zCetReport, 2786 features & GNU_PROPERTY_X86_FEATURE_1_SHSTK) 2787 << f 2788 << ": -z cet-report: file does not have " 2789 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"; 2790 2791 if (ctx.arg.zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 2792 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 2793 if (ctx.arg.zBtiReport == "none") 2794 Warn(ctx) << f 2795 << ": -z force-bti: file does not have " 2796 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"; 2797 } else if (ctx.arg.zForceIbt && 2798 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 2799 if (ctx.arg.zCetReport == "none") 2800 Warn(ctx) << f 2801 << ": -z force-ibt: file does not have " 2802 "GNU_PROPERTY_X86_FEATURE_1_IBT property"; 2803 features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2804 } 2805 if (ctx.arg.zPacPlt && !(hasValidPauthAbiCoreInfo || 2806 (features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC))) { 2807 Warn(ctx) << f 2808 << ": -z pac-plt: file does not have " 2809 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property and no valid " 2810 "PAuth core info present for this link job"; 2811 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 2812 } 2813 ctx.arg.andFeatures &= features; 2814 2815 if (ctx.aarch64PauthAbiCoreInfo.empty()) 2816 continue; 2817 2818 if (f->aarch64PauthAbiCoreInfo.empty()) { 2819 report(ctx.arg.zPauthReport) 2820 << f 2821 << ": -z pauth-report: file does not have AArch64 " 2822 "PAuth core info while '" 2823 << referenceFileName << "' has one"; 2824 continue; 2825 } 2826 2827 if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo) 2828 Err(ctx) << "incompatible values of AArch64 PAuth core info found\n>>> " 2829 << referenceFileName << ": 0x" 2830 << toHex(ctx.aarch64PauthAbiCoreInfo, /*LowerCase=*/true) 2831 << "\n>>> " << f << ": 0x" 2832 << toHex(f->aarch64PauthAbiCoreInfo, /*LowerCase=*/true); 2833 } 2834 2835 // Force enable Shadow Stack. 2836 if (ctx.arg.zShstk) 2837 ctx.arg.andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 2838 2839 // Force enable/disable GCS 2840 if (ctx.arg.zGcs == GcsPolicy::Always) 2841 ctx.arg.andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS; 2842 else if (ctx.arg.zGcs == GcsPolicy::Never) 2843 ctx.arg.andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS; 2844 } 2845 2846 static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) { 2847 switch (file->ekind) { 2848 case ELF32LEKind: 2849 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2850 break; 2851 case ELF32BEKind: 2852 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2853 break; 2854 case ELF64LEKind: 2855 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2856 break; 2857 case ELF64BEKind: 2858 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2859 break; 2860 default: 2861 llvm_unreachable(""); 2862 } 2863 } 2864 2865 static void postParseObjectFile(ELFFileBase *file) { 2866 switch (file->ekind) { 2867 case ELF32LEKind: 2868 cast<ObjFile<ELF32LE>>(file)->postParse(); 2869 break; 2870 case ELF32BEKind: 2871 cast<ObjFile<ELF32BE>>(file)->postParse(); 2872 break; 2873 case ELF64LEKind: 2874 cast<ObjFile<ELF64LE>>(file)->postParse(); 2875 break; 2876 case ELF64BEKind: 2877 cast<ObjFile<ELF64BE>>(file)->postParse(); 2878 break; 2879 default: 2880 llvm_unreachable(""); 2881 } 2882 } 2883 2884 // Do actual linking. Note that when this function is called, 2885 // all linker scripts have already been parsed. 2886 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) { 2887 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2888 2889 // Handle --trace-symbol. 2890 for (auto *arg : args.filtered(OPT_trace_symbol)) 2891 ctx.symtab->insert(arg->getValue())->traced = true; 2892 2893 ctx.internalFile = createInternalFile(ctx, "<internal>"); 2894 2895 // Handle -u/--undefined before input files. If both a.a and b.so define foo, 2896 // -u foo a.a b.so will extract a.a. 2897 for (StringRef name : ctx.arg.undefined) 2898 ctx.symtab->addUnusedUndefined(name)->referenced = true; 2899 2900 parseFiles(ctx, files); 2901 2902 // Dynamic linking is used if there is an input DSO, 2903 // or -shared or non-static pie is specified. 2904 ctx.hasDynsym = !ctx.sharedFiles.empty() || ctx.arg.shared || 2905 (ctx.arg.pie && !ctx.arg.noDynamicLinker); 2906 // Create dynamic sections for dynamic linking and static PIE. 2907 ctx.arg.hasDynSymTab = ctx.hasDynsym || ctx.arg.isPic; 2908 2909 // If an entry symbol is in a static archive, pull out that file now. 2910 if (Symbol *sym = ctx.symtab->find(ctx.arg.entry)) 2911 handleUndefined(ctx, sym, "--entry"); 2912 2913 // Handle the `--undefined-glob <pattern>` options. 2914 for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 2915 handleUndefinedGlob(ctx, pat); 2916 2917 // After potential archive member extraction involving ENTRY and 2918 // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the 2919 // RHS may refer to definitions in just extracted object files). 2920 ctx.script->addScriptReferencedSymbolsToSymTable(); 2921 2922 // Prevent LTO from removing any definition referenced by -u. 2923 for (StringRef name : ctx.arg.undefined) 2924 if (Defined *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(name))) 2925 sym->isUsedInRegularObj = true; 2926 2927 // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2928 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.init))) 2929 sym->isUsedInRegularObj = true; 2930 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.fini))) 2931 sym->isUsedInRegularObj = true; 2932 2933 // If any of our inputs are bitcode files, the LTO code generator may create 2934 // references to certain library functions that might not be explicit in the 2935 // bitcode file's symbol table. If any of those library functions are defined 2936 // in a bitcode file in an archive member, we need to arrange to use LTO to 2937 // compile those archive members by adding them to the link beforehand. 2938 // 2939 // However, adding all libcall symbols to the link can have undesired 2940 // consequences. For example, the libgcc implementation of 2941 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 2942 // that aborts the program if the Linux kernel does not support 64-bit 2943 // atomics, which would prevent the program from running even if it does not 2944 // use 64-bit atomics. 2945 // 2946 // Therefore, we only add libcall symbols to the link before LTO if we have 2947 // to, i.e. if the symbol's definition is in bitcode. Any other required 2948 // libcall symbols will be added to the link after LTO when we add the LTO 2949 // object file to the link. 2950 if (!ctx.bitcodeFiles.empty()) { 2951 llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple()); 2952 for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT)) 2953 handleLibcall(ctx, s); 2954 } 2955 2956 // Archive members defining __wrap symbols may be extracted. 2957 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2958 2959 // No more lazy bitcode can be extracted at this point. Do post parse work 2960 // like checking duplicate symbols. 2961 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) { 2962 initSectionsAndLocalSyms(file, /*ignoreComdats=*/false); 2963 }); 2964 parallelForEach(ctx.objectFiles, postParseObjectFile); 2965 parallelForEach(ctx.bitcodeFiles, 2966 [](BitcodeFile *file) { file->postParse(); }); 2967 for (auto &it : ctx.nonPrevailingSyms) { 2968 Symbol &sym = *it.first; 2969 Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type, 2970 it.second) 2971 .overwrite(sym); 2972 cast<Undefined>(sym).nonPrevailing = true; 2973 } 2974 ctx.nonPrevailingSyms.clear(); 2975 for (const DuplicateSymbol &d : ctx.duplicates) 2976 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value); 2977 ctx.duplicates.clear(); 2978 2979 // Return if there were name resolution errors. 2980 if (errCount(ctx)) 2981 return; 2982 2983 // We want to declare linker script's symbols early, 2984 // so that we can version them. 2985 // They also might be exported if referenced by DSOs. 2986 ctx.script->declareSymbols(); 2987 2988 // Handle --exclude-libs. This is before scanVersionScript() due to a 2989 // workaround for Android ndk: for a defined versioned symbol in an archive 2990 // without a version node in the version script, Android does not expect a 2991 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2992 // GNU ld errors in this case. 2993 if (args.hasArg(OPT_exclude_libs)) 2994 excludeLibs(ctx, args); 2995 2996 // Create elfHeader early. We need a dummy section in 2997 // addReservedSymbols to mark the created symbols as not absolute. 2998 ctx.out.elfHeader = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC); 2999 3000 // We need to create some reserved symbols such as _end. Create them. 3001 if (!ctx.arg.relocatable) 3002 addReservedSymbols(ctx); 3003 3004 // Apply version scripts. 3005 // 3006 // For a relocatable output, version scripts don't make sense, and 3007 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 3008 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 3009 if (!ctx.arg.relocatable) { 3010 llvm::TimeTraceScope timeScope("Process symbol versions"); 3011 ctx.symtab->scanVersionScript(); 3012 3013 parseVersionAndComputeIsPreemptible(ctx); 3014 } 3015 3016 // Skip the normal linked output if some LTO options are specified. 3017 // 3018 // For --thinlto-index-only, index file creation is performed in 3019 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 3020 // --plugin-opt=emit-asm create output files in bitcode or assembly code, 3021 // respectively. When only certain thinLTO modules are specified for 3022 // compilation, the intermediate object file are the expected output. 3023 const bool skipLinkedOutput = ctx.arg.thinLTOIndexOnly || ctx.arg.emitLLVM || 3024 ctx.arg.ltoEmitAsm || 3025 !ctx.arg.thinLTOModulesToCompile.empty(); 3026 3027 // Handle --lto-validate-all-vtables-have-type-infos. 3028 if (ctx.arg.ltoValidateAllVtablesHaveTypeInfos) 3029 ltoValidateAllVtablesHaveTypeInfos<ELFT>(ctx, args); 3030 3031 // Do link-time optimization if given files are LLVM bitcode files. 3032 // This compiles bitcode files into real object files. 3033 // 3034 // With this the symbol table should be complete. After this, no new names 3035 // except a few linker-synthesized ones will be added to the symbol table. 3036 const size_t numObjsBeforeLTO = ctx.objectFiles.size(); 3037 const size_t numInputFilesBeforeLTO = ctx.driver.files.size(); 3038 compileBitcodeFiles<ELFT>(skipLinkedOutput); 3039 3040 // Symbol resolution finished. Report backward reference problems, 3041 // --print-archive-stats=, and --why-extract=. 3042 reportBackrefs(ctx); 3043 writeArchiveStats(ctx); 3044 writeWhyExtract(ctx); 3045 if (errCount(ctx)) 3046 return; 3047 3048 // Bail out if normal linked output is skipped due to LTO. 3049 if (skipLinkedOutput) 3050 return; 3051 3052 // compileBitcodeFiles may have produced lto.tmp object files. After this, no 3053 // more file will be added. 3054 auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO); 3055 parallelForEach(newObjectFiles, [](ELFFileBase *file) { 3056 initSectionsAndLocalSyms(file, /*ignoreComdats=*/true); 3057 }); 3058 parallelForEach(newObjectFiles, postParseObjectFile); 3059 for (const DuplicateSymbol &d : ctx.duplicates) 3060 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value); 3061 3062 // ELF dependent libraries may have introduced new input files after LTO has 3063 // completed. This is an error if the files haven't already been parsed, since 3064 // changing the symbol table could break the semantic assumptions of LTO. 3065 auto newInputFiles = ArrayRef(ctx.driver.files).slice(numInputFilesBeforeLTO); 3066 if (!newInputFiles.empty()) { 3067 DenseSet<StringRef> oldFilenames; 3068 for (auto &f : ArrayRef(ctx.driver.files).slice(0, numInputFilesBeforeLTO)) 3069 oldFilenames.insert(f->getName()); 3070 for (auto &newFile : newInputFiles) 3071 if (!oldFilenames.contains(newFile->getName())) 3072 Err(ctx) << "input file '" << newFile->getName() << "' added after LTO"; 3073 } 3074 3075 // Handle --exclude-libs again because lto.tmp may reference additional 3076 // libcalls symbols defined in an excluded archive. This may override 3077 // versionId set by scanVersionScript() and isExported. 3078 if (args.hasArg(OPT_exclude_libs)) 3079 excludeLibs(ctx, args); 3080 3081 // Record [__acle_se_<sym>, <sym>] pairs for later processing. 3082 processArmCmseSymbols(ctx); 3083 3084 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 3085 redirectSymbols(ctx, wrapped); 3086 3087 // Replace common symbols with regular symbols. 3088 replaceCommonSymbols(ctx); 3089 3090 { 3091 llvm::TimeTraceScope timeScope("Aggregate sections"); 3092 // Now that we have a complete list of input files. 3093 // Beyond this point, no new files are added. 3094 // Aggregate all input sections into one place. 3095 for (InputFile *f : ctx.objectFiles) { 3096 for (InputSectionBase *s : f->getSections()) { 3097 if (!s || s == &InputSection::discarded) 3098 continue; 3099 if (LLVM_UNLIKELY(isa<EhInputSection>(s))) 3100 ctx.ehInputSections.push_back(cast<EhInputSection>(s)); 3101 else 3102 ctx.inputSections.push_back(s); 3103 } 3104 } 3105 for (BinaryFile *f : ctx.binaryFiles) 3106 for (InputSectionBase *s : f->getSections()) 3107 ctx.inputSections.push_back(cast<InputSection>(s)); 3108 } 3109 3110 { 3111 llvm::TimeTraceScope timeScope("Strip sections"); 3112 if (ctx.hasSympart.load(std::memory_order_relaxed)) { 3113 llvm::erase_if(ctx.inputSections, [&ctx = ctx](InputSectionBase *s) { 3114 if (s->type != SHT_LLVM_SYMPART) 3115 return false; 3116 readSymbolPartitionSection<ELFT>(ctx, s); 3117 return true; 3118 }); 3119 } 3120 // We do not want to emit debug sections if --strip-all 3121 // or --strip-debug are given. 3122 if (ctx.arg.strip != StripPolicy::None) { 3123 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 3124 if (isDebugSection(*s)) 3125 return true; 3126 if (auto *isec = dyn_cast<InputSection>(s)) 3127 if (InputSectionBase *rel = isec->getRelocatedSection()) 3128 if (isDebugSection(*rel)) 3129 return true; 3130 3131 return false; 3132 }); 3133 } 3134 } 3135 3136 // Since we now have a complete set of input files, we can create 3137 // a .d file to record build dependencies. 3138 if (!ctx.arg.dependencyFile.empty()) 3139 writeDependencyFile(ctx); 3140 3141 // Now that the number of partitions is fixed, save a pointer to the main 3142 // partition. 3143 ctx.mainPart = &ctx.partitions[0]; 3144 3145 // Read .note.gnu.property sections from input object files which 3146 // contain a hint to tweak linker's and loader's behaviors. 3147 readSecurityNotes(ctx); 3148 3149 // The Target instance handles target-specific stuff, such as applying 3150 // relocations or writing a PLT section. It also contains target-dependent 3151 // values such as a default image base address. 3152 setTarget(ctx); 3153 3154 ctx.arg.eflags = ctx.target->calcEFlags(); 3155 // maxPageSize (sometimes called abi page size) is the maximum page size that 3156 // the output can be run on. For example if the OS can use 4k or 64k page 3157 // sizes then maxPageSize must be 64k for the output to be useable on both. 3158 // All important alignment decisions must use this value. 3159 ctx.arg.maxPageSize = getMaxPageSize(ctx, args); 3160 // commonPageSize is the most common page size that the output will be run on. 3161 // For example if an OS can use 4k or 64k page sizes and 4k is more common 3162 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 3163 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 3164 // is limited to writing trap instructions on the last executable segment. 3165 ctx.arg.commonPageSize = getCommonPageSize(ctx, args); 3166 3167 ctx.arg.imageBase = getImageBase(ctx, args); 3168 3169 // This adds a .comment section containing a version string. 3170 if (!ctx.arg.relocatable) 3171 ctx.inputSections.push_back(createCommentSection(ctx)); 3172 3173 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 3174 splitSections<ELFT>(ctx); 3175 3176 // Garbage collection and removal of shared symbols from unused shared objects. 3177 markLive<ELFT>(ctx); 3178 3179 // Make copies of any input sections that need to be copied into each 3180 // partition. 3181 copySectionsIntoPartitions(ctx); 3182 3183 if (canHaveMemtagGlobals(ctx)) { 3184 llvm::TimeTraceScope timeScope("Process memory tagged symbols"); 3185 createTaggedSymbols(ctx); 3186 } 3187 3188 // Create synthesized sections such as .got and .plt. This is called before 3189 // processSectionCommands() so that they can be placed by SECTIONS commands. 3190 createSyntheticSections<ELFT>(ctx); 3191 3192 // Some input sections that are used for exception handling need to be moved 3193 // into synthetic sections. Do that now so that they aren't assigned to 3194 // output sections in the usual way. 3195 if (!ctx.arg.relocatable) 3196 combineEhSections(ctx); 3197 3198 // Merge .riscv.attributes sections. 3199 if (ctx.arg.emachine == EM_RISCV) 3200 mergeRISCVAttributesSections(ctx); 3201 3202 { 3203 llvm::TimeTraceScope timeScope("Assign sections"); 3204 3205 // Create output sections described by SECTIONS commands. 3206 ctx.script->processSectionCommands(); 3207 3208 // Linker scripts control how input sections are assigned to output 3209 // sections. Input sections that were not handled by scripts are called 3210 // "orphans", and they are assigned to output sections by the default rule. 3211 // Process that. 3212 ctx.script->addOrphanSections(); 3213 } 3214 3215 { 3216 llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 3217 3218 // Migrate InputSectionDescription::sectionBases to sections. This includes 3219 // merging MergeInputSections into a single MergeSyntheticSection. From this 3220 // point onwards InputSectionDescription::sections should be used instead of 3221 // sectionBases. 3222 for (SectionCommand *cmd : ctx.script->sectionCommands) 3223 if (auto *osd = dyn_cast<OutputDesc>(cmd)) 3224 osd->osec.finalizeInputSections(); 3225 } 3226 3227 // Two input sections with different output sections should not be folded. 3228 // ICF runs after processSectionCommands() so that we know the output sections. 3229 if (ctx.arg.icf != ICFLevel::None) { 3230 findKeepUniqueSections<ELFT>(ctx, args); 3231 doIcf<ELFT>(ctx); 3232 } 3233 3234 // Read the callgraph now that we know what was gced or icfed 3235 if (ctx.arg.callGraphProfileSort != CGProfileSortKind::None) { 3236 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 3237 if (std::optional<MemoryBufferRef> buffer = 3238 readFile(ctx, arg->getValue())) 3239 readCallGraph(ctx, *buffer); 3240 } else 3241 readCallGraphsFromObjectFiles<ELFT>(ctx); 3242 } 3243 3244 // Write the result to the file. 3245 writeResult<ELFT>(ctx); 3246 } 3247