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 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 "LinkerScript.h" 31 #include "MarkLive.h" 32 #include "OutputSections.h" 33 #include "ScriptParser.h" 34 #include "SymbolTable.h" 35 #include "Symbols.h" 36 #include "SyntheticSections.h" 37 #include "Target.h" 38 #include "Writer.h" 39 #include "lld/Common/Args.h" 40 #include "lld/Common/Driver.h" 41 #include "lld/Common/ErrorHandler.h" 42 #include "lld/Common/Filesystem.h" 43 #include "lld/Common/Memory.h" 44 #include "lld/Common/Strings.h" 45 #include "lld/Common/TargetOptionsCommandFlags.h" 46 #include "lld/Common/Version.h" 47 #include "llvm/ADT/SetVector.h" 48 #include "llvm/ADT/StringExtras.h" 49 #include "llvm/ADT/StringSwitch.h" 50 #include "llvm/Config/llvm-config.h" 51 #include "llvm/LTO/LTO.h" 52 #include "llvm/Remarks/HotnessThresholdParser.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Compression.h" 55 #include "llvm/Support/GlobPattern.h" 56 #include "llvm/Support/LEB128.h" 57 #include "llvm/Support/Parallel.h" 58 #include "llvm/Support/Path.h" 59 #include "llvm/Support/TarWriter.h" 60 #include "llvm/Support/TargetSelect.h" 61 #include "llvm/Support/TimeProfiler.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <cstdlib> 64 #include <utility> 65 66 using namespace llvm; 67 using namespace llvm::ELF; 68 using namespace llvm::object; 69 using namespace llvm::sys; 70 using namespace llvm::support; 71 using namespace lld; 72 using namespace lld::elf; 73 74 std::unique_ptr<Configuration> elf::config; 75 std::unique_ptr<LinkerDriver> elf::driver; 76 77 static void setConfigs(opt::InputArgList &args); 78 static void readConfigs(opt::InputArgList &args); 79 80 bool elf::link(ArrayRef<const char *> args, bool canExitEarly, 81 raw_ostream &stdoutOS, raw_ostream &stderrOS) { 82 lld::stdoutOS = &stdoutOS; 83 lld::stderrOS = &stderrOS; 84 85 errorHandler().cleanupCallback = []() { 86 freeArena(); 87 88 inputSections.clear(); 89 outputSections.clear(); 90 memoryBuffers.clear(); 91 archiveFiles.clear(); 92 binaryFiles.clear(); 93 bitcodeFiles.clear(); 94 lazyBitcodeFiles.clear(); 95 objectFiles.clear(); 96 sharedFiles.clear(); 97 backwardReferences.clear(); 98 whyExtract.clear(); 99 symAux.clear(); 100 101 tar = nullptr; 102 in.reset(); 103 104 partitions.clear(); 105 partitions.emplace_back(); 106 107 SharedFile::vernauxNum = 0; 108 }; 109 110 errorHandler().logName = args::getFilenameWithoutExe(args[0]); 111 errorHandler().errorLimitExceededMsg = 112 "too many errors emitted, stopping now (use " 113 "-error-limit=0 to see all errors)"; 114 errorHandler().exitEarly = canExitEarly; 115 stderrOS.enable_colors(stderrOS.has_colors()); 116 117 config = std::make_unique<Configuration>(); 118 driver = std::make_unique<LinkerDriver>(); 119 script = std::make_unique<LinkerScript>(); 120 symtab = std::make_unique<SymbolTable>(); 121 122 partitions.clear(); 123 partitions.emplace_back(); 124 125 config->progName = args[0]; 126 127 driver->linkerMain(args); 128 129 // Exit immediately if we don't need to return to the caller. 130 // This saves time because the overhead of calling destructors 131 // for all globally-allocated objects is not negligible. 132 if (canExitEarly) 133 exitLld(errorCount() ? 1 : 0); 134 135 bool ret = errorCount() == 0; 136 if (!canExitEarly) 137 errorHandler().reset(); 138 return ret; 139 } 140 141 // Parses a linker -m option. 142 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 143 uint8_t osabi = 0; 144 StringRef s = emul; 145 if (s.endswith("_fbsd")) { 146 s = s.drop_back(5); 147 osabi = ELFOSABI_FREEBSD; 148 } 149 150 std::pair<ELFKind, uint16_t> ret = 151 StringSwitch<std::pair<ELFKind, uint16_t>>(s) 152 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 153 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 154 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 155 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 156 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 157 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 158 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 159 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 160 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 161 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 162 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 163 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 164 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 165 .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 166 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 167 .Case("elf_i386", {ELF32LEKind, EM_386}) 168 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 169 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 170 .Case("msp430elf", {ELF32LEKind, EM_MSP430}) 171 .Default({ELFNoneKind, EM_NONE}); 172 173 if (ret.first == ELFNoneKind) 174 error("unknown emulation: " + emul); 175 if (ret.second == EM_MSP430) 176 osabi = ELFOSABI_STANDALONE; 177 return std::make_tuple(ret.first, ret.second, osabi); 178 } 179 180 // Returns slices of MB by parsing MB as an archive file. 181 // Each slice consists of a member file in the archive. 182 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 183 MemoryBufferRef mb) { 184 std::unique_ptr<Archive> file = 185 CHECK(Archive::create(mb), 186 mb.getBufferIdentifier() + ": failed to parse archive"); 187 188 std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 189 Error err = Error::success(); 190 bool addToTar = file->isThin() && tar; 191 for (const Archive::Child &c : file->children(err)) { 192 MemoryBufferRef mbref = 193 CHECK(c.getMemoryBufferRef(), 194 mb.getBufferIdentifier() + 195 ": could not get the buffer for a child of the archive"); 196 if (addToTar) 197 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 198 v.push_back(std::make_pair(mbref, c.getChildOffset())); 199 } 200 if (err) 201 fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 202 toString(std::move(err))); 203 204 // Take ownership of memory buffers created for members of thin archives. 205 for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers()) 206 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); 207 208 return v; 209 } 210 211 // Opens a file and create a file object. Path has to be resolved already. 212 void LinkerDriver::addFile(StringRef path, bool withLOption) { 213 using namespace sys::fs; 214 215 Optional<MemoryBufferRef> buffer = readFile(path); 216 if (!buffer.hasValue()) 217 return; 218 MemoryBufferRef mbref = *buffer; 219 220 if (config->formatBinary) { 221 files.push_back(make<BinaryFile>(mbref)); 222 return; 223 } 224 225 switch (identify_magic(mbref.getBuffer())) { 226 case file_magic::unknown: 227 readLinkerScript(mbref); 228 return; 229 case file_magic::archive: { 230 if (inWholeArchive) { 231 for (const auto &p : getArchiveMembers(mbref)) 232 files.push_back(createObjectFile(p.first, path, p.second)); 233 return; 234 } 235 236 std::unique_ptr<Archive> file = 237 CHECK(Archive::create(mbref), path + ": failed to parse archive"); 238 239 // If an archive file has no symbol table, it is likely that a user 240 // is attempting LTO and using a default ar command that doesn't 241 // understand the LLVM bitcode file. It is a pretty common error, so 242 // we'll handle it as if it had a symbol table. 243 if (!file->isEmpty() && !file->hasSymbolTable()) { 244 // Check if all members are bitcode files. If not, ignore, which is the 245 // default action without the LTO hack described above. 246 for (const std::pair<MemoryBufferRef, uint64_t> &p : 247 getArchiveMembers(mbref)) 248 if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) { 249 error(path + ": archive has no index; run ranlib to add one"); 250 return; 251 } 252 253 for (const std::pair<MemoryBufferRef, uint64_t> &p : 254 getArchiveMembers(mbref)) 255 files.push_back(createLazyFile(p.first, path, p.second)); 256 return; 257 } 258 259 // Handle the regular case. 260 files.push_back(make<ArchiveFile>(std::move(file))); 261 return; 262 } 263 case file_magic::elf_shared_object: 264 if (config->isStatic || config->relocatable) { 265 error("attempted static link of dynamic object " + path); 266 return; 267 } 268 269 // Shared objects are identified by soname. soname is (if specified) 270 // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 271 // the directory part is ignored. Note that path may be a temporary and 272 // cannot be stored into SharedFile::soName. 273 path = mbref.getBufferIdentifier(); 274 files.push_back( 275 make<SharedFile>(mbref, withLOption ? path::filename(path) : path)); 276 return; 277 case file_magic::bitcode: 278 case file_magic::elf_relocatable: 279 if (inLib) 280 files.push_back(createLazyFile(mbref, "", 0)); 281 else 282 files.push_back(createObjectFile(mbref)); 283 break; 284 default: 285 error(path + ": unknown file type"); 286 } 287 } 288 289 // Add a given library by searching it from input search paths. 290 void LinkerDriver::addLibrary(StringRef name) { 291 if (Optional<std::string> path = searchLibrary(name)) 292 addFile(*path, /*withLOption=*/true); 293 else 294 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name}); 295 } 296 297 // This function is called on startup. We need this for LTO since 298 // LTO calls LLVM functions to compile bitcode files to native code. 299 // Technically this can be delayed until we read bitcode files, but 300 // we don't bother to do lazily because the initialization is fast. 301 static void initLLVM() { 302 InitializeAllTargets(); 303 InitializeAllTargetMCs(); 304 InitializeAllAsmPrinters(); 305 InitializeAllAsmParsers(); 306 } 307 308 // Some command line options or some combinations of them are not allowed. 309 // This function checks for such errors. 310 static void checkOptions() { 311 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 312 // table which is a relatively new feature. 313 if (config->emachine == EM_MIPS && config->gnuHash) 314 error("the .gnu.hash section is not compatible with the MIPS target"); 315 316 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 317 error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 318 319 if (config->fixCortexA8 && config->emachine != EM_ARM) 320 error("--fix-cortex-a8 is only supported on ARM targets"); 321 322 if (config->tocOptimize && config->emachine != EM_PPC64) 323 error("--toc-optimize is only supported on PowerPC64 targets"); 324 325 if (config->pcRelOptimize && config->emachine != EM_PPC64) 326 error("--pcrel-optimize is only supported on PowerPC64 targets"); 327 328 if (config->pie && config->shared) 329 error("-shared and -pie may not be used together"); 330 331 if (!config->shared && !config->filterList.empty()) 332 error("-F may not be used without -shared"); 333 334 if (!config->shared && !config->auxiliaryList.empty()) 335 error("-f may not be used without -shared"); 336 337 if (!config->relocatable && !config->defineCommon) 338 error("-no-define-common not supported in non relocatable output"); 339 340 if (config->strip == StripPolicy::All && config->emitRelocs) 341 error("--strip-all and --emit-relocs may not be used together"); 342 343 if (config->zText && config->zIfuncNoplt) 344 error("-z text and -z ifunc-noplt may not be used together"); 345 346 if (config->relocatable) { 347 if (config->shared) 348 error("-r and -shared may not be used together"); 349 if (config->gdbIndex) 350 error("-r and --gdb-index may not be used together"); 351 if (config->icf != ICFLevel::None) 352 error("-r and --icf may not be used together"); 353 if (config->pie) 354 error("-r and -pie may not be used together"); 355 if (config->exportDynamic) 356 error("-r and --export-dynamic may not be used together"); 357 } 358 359 if (config->executeOnly) { 360 if (config->emachine != EM_AARCH64) 361 error("--execute-only is only supported on AArch64 targets"); 362 363 if (config->singleRoRx && !script->hasSectionsCommand) 364 error("--execute-only and --no-rosegment cannot be used together"); 365 } 366 367 if (config->zRetpolineplt && config->zForceIbt) 368 error("-z force-ibt may not be used with -z retpolineplt"); 369 370 if (config->emachine != EM_AARCH64) { 371 if (config->zPacPlt) 372 error("-z pac-plt only supported on AArch64"); 373 if (config->zForceBti) 374 error("-z force-bti only supported on AArch64"); 375 if (config->zBtiReport != "none") 376 error("-z bti-report only supported on AArch64"); 377 } 378 379 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 380 config->zCetReport != "none") 381 error("-z cet-report only supported on X86 and X86_64"); 382 } 383 384 static const char *getReproduceOption(opt::InputArgList &args) { 385 if (auto *arg = args.getLastArg(OPT_reproduce)) 386 return arg->getValue(); 387 return getenv("LLD_REPRODUCE"); 388 } 389 390 static bool hasZOption(opt::InputArgList &args, StringRef key) { 391 for (auto *arg : args.filtered(OPT_z)) 392 if (key == arg->getValue()) 393 return true; 394 return false; 395 } 396 397 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 398 bool Default) { 399 for (auto *arg : args.filtered_reverse(OPT_z)) { 400 if (k1 == arg->getValue()) 401 return true; 402 if (k2 == arg->getValue()) 403 return false; 404 } 405 return Default; 406 } 407 408 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 409 for (auto *arg : args.filtered_reverse(OPT_z)) { 410 StringRef v = arg->getValue(); 411 if (v == "noseparate-code") 412 return SeparateSegmentKind::None; 413 if (v == "separate-code") 414 return SeparateSegmentKind::Code; 415 if (v == "separate-loadable-segments") 416 return SeparateSegmentKind::Loadable; 417 } 418 return SeparateSegmentKind::None; 419 } 420 421 static GnuStackKind getZGnuStack(opt::InputArgList &args) { 422 for (auto *arg : args.filtered_reverse(OPT_z)) { 423 if (StringRef("execstack") == arg->getValue()) 424 return GnuStackKind::Exec; 425 if (StringRef("noexecstack") == arg->getValue()) 426 return GnuStackKind::NoExec; 427 if (StringRef("nognustack") == arg->getValue()) 428 return GnuStackKind::None; 429 } 430 431 return GnuStackKind::NoExec; 432 } 433 434 static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 435 for (auto *arg : args.filtered_reverse(OPT_z)) { 436 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 437 if (kv.first == "start-stop-visibility") { 438 if (kv.second == "default") 439 return STV_DEFAULT; 440 else if (kv.second == "internal") 441 return STV_INTERNAL; 442 else if (kv.second == "hidden") 443 return STV_HIDDEN; 444 else if (kv.second == "protected") 445 return STV_PROTECTED; 446 error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 447 } 448 } 449 return STV_PROTECTED; 450 } 451 452 static bool isKnownZFlag(StringRef s) { 453 return s == "combreloc" || s == "copyreloc" || s == "defs" || 454 s == "execstack" || s == "force-bti" || s == "force-ibt" || 455 s == "global" || s == "hazardplt" || s == "ifunc-noplt" || 456 s == "initfirst" || s == "interpose" || 457 s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" || 458 s == "separate-code" || s == "separate-loadable-segments" || 459 s == "start-stop-gc" || s == "nocombreloc" || s == "nocopyreloc" || 460 s == "nodefaultlib" || s == "nodelete" || s == "nodlopen" || 461 s == "noexecstack" || s == "nognustack" || 462 s == "nokeep-text-section-prefix" || s == "norelro" || 463 s == "noseparate-code" || s == "nostart-stop-gc" || s == "notext" || 464 s == "now" || s == "origin" || s == "pac-plt" || s == "rel" || 465 s == "rela" || s == "relro" || s == "retpolineplt" || 466 s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" || 467 s == "wxneeded" || s.startswith("common-page-size=") || 468 s.startswith("bti-report=") || s.startswith("cet-report=") || 469 s.startswith("dead-reloc-in-nonalloc=") || 470 s.startswith("max-page-size=") || s.startswith("stack-size=") || 471 s.startswith("start-stop-visibility="); 472 } 473 474 // Report a warning for an unknown -z option. 475 static void checkZOptions(opt::InputArgList &args) { 476 for (auto *arg : args.filtered(OPT_z)) 477 if (!isKnownZFlag(arg->getValue())) 478 warn("unknown -z value: " + StringRef(arg->getValue())); 479 } 480 481 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 482 ELFOptTable parser; 483 opt::InputArgList args = parser.parse(argsArr.slice(1)); 484 485 // Interpret the flags early because error()/warn() depend on them. 486 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 487 errorHandler().fatalWarnings = 488 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 489 checkZOptions(args); 490 491 // Handle -help 492 if (args.hasArg(OPT_help)) { 493 printHelp(); 494 return; 495 } 496 497 // Handle -v or -version. 498 // 499 // A note about "compatible with GNU linkers" message: this is a hack for 500 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 501 // a GNU compatible linker. See 502 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 503 // 504 // This is somewhat ugly hack, but in reality, we had no choice other 505 // than doing this. Considering the very long release cycle of Libtool, 506 // it is not easy to improve it to recognize LLD as a GNU compatible 507 // linker in a timely manner. Even if we can make it, there are still a 508 // lot of "configure" scripts out there that are generated by old version 509 // of Libtool. We cannot convince every software developer to migrate to 510 // the latest version and re-generate scripts. So we have this hack. 511 if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 512 message(getLLDVersion() + " (compatible with GNU linkers)"); 513 514 if (const char *path = getReproduceOption(args)) { 515 // Note that --reproduce is a debug option so you can ignore it 516 // if you are trying to understand the whole picture of the code. 517 Expected<std::unique_ptr<TarWriter>> errOrWriter = 518 TarWriter::create(path, path::stem(path)); 519 if (errOrWriter) { 520 tar = std::move(*errOrWriter); 521 tar->append("response.txt", createResponseFile(args)); 522 tar->append("version.txt", getLLDVersion() + "\n"); 523 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 524 if (!ltoSampleProfile.empty()) 525 readFile(ltoSampleProfile); 526 } else { 527 error("--reproduce: " + toString(errOrWriter.takeError())); 528 } 529 } 530 531 readConfigs(args); 532 533 // The behavior of -v or --version is a bit strange, but this is 534 // needed for compatibility with GNU linkers. 535 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 536 return; 537 if (args.hasArg(OPT_version)) 538 return; 539 540 // Initialize time trace profiler. 541 if (config->timeTraceEnabled) 542 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 543 544 { 545 llvm::TimeTraceScope timeScope("ExecuteLinker"); 546 547 initLLVM(); 548 createFiles(args); 549 if (errorCount()) 550 return; 551 552 inferMachineType(); 553 setConfigs(args); 554 checkOptions(); 555 if (errorCount()) 556 return; 557 558 // The Target instance handles target-specific stuff, such as applying 559 // relocations or writing a PLT section. It also contains target-dependent 560 // values such as a default image base address. 561 target = getTarget(); 562 563 switch (config->ekind) { 564 case ELF32LEKind: 565 link<ELF32LE>(args); 566 break; 567 case ELF32BEKind: 568 link<ELF32BE>(args); 569 break; 570 case ELF64LEKind: 571 link<ELF64LE>(args); 572 break; 573 case ELF64BEKind: 574 link<ELF64BE>(args); 575 break; 576 default: 577 llvm_unreachable("unknown Config->EKind"); 578 } 579 } 580 581 if (config->timeTraceEnabled) { 582 checkError(timeTraceProfilerWrite( 583 args.getLastArgValue(OPT_time_trace_file_eq).str(), 584 config->outputFile)); 585 timeTraceProfilerCleanup(); 586 } 587 } 588 589 static std::string getRpath(opt::InputArgList &args) { 590 std::vector<StringRef> v = args::getStrings(args, OPT_rpath); 591 return llvm::join(v.begin(), v.end(), ":"); 592 } 593 594 // Determines what we should do if there are remaining unresolved 595 // symbols after the name resolution. 596 static void setUnresolvedSymbolPolicy(opt::InputArgList &args) { 597 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 598 OPT_warn_unresolved_symbols, true) 599 ? UnresolvedPolicy::ReportError 600 : UnresolvedPolicy::Warn; 601 // -shared implies --unresolved-symbols=ignore-all because missing 602 // symbols are likely to be resolved at runtime. 603 bool diagRegular = !config->shared, diagShlib = !config->shared; 604 605 for (const opt::Arg *arg : args) { 606 switch (arg->getOption().getID()) { 607 case OPT_unresolved_symbols: { 608 StringRef s = arg->getValue(); 609 if (s == "ignore-all") { 610 diagRegular = false; 611 diagShlib = false; 612 } else if (s == "ignore-in-object-files") { 613 diagRegular = false; 614 diagShlib = true; 615 } else if (s == "ignore-in-shared-libs") { 616 diagRegular = true; 617 diagShlib = false; 618 } else if (s == "report-all") { 619 diagRegular = true; 620 diagShlib = true; 621 } else { 622 error("unknown --unresolved-symbols value: " + s); 623 } 624 break; 625 } 626 case OPT_no_undefined: 627 diagRegular = true; 628 break; 629 case OPT_z: 630 if (StringRef(arg->getValue()) == "defs") 631 diagRegular = true; 632 else if (StringRef(arg->getValue()) == "undefs") 633 diagRegular = false; 634 break; 635 case OPT_allow_shlib_undefined: 636 diagShlib = false; 637 break; 638 case OPT_no_allow_shlib_undefined: 639 diagShlib = true; 640 break; 641 } 642 } 643 644 config->unresolvedSymbols = 645 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 646 config->unresolvedSymbolsInShlib = 647 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 648 } 649 650 static Target2Policy getTarget2(opt::InputArgList &args) { 651 StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 652 if (s == "rel") 653 return Target2Policy::Rel; 654 if (s == "abs") 655 return Target2Policy::Abs; 656 if (s == "got-rel") 657 return Target2Policy::GotRel; 658 error("unknown --target2 option: " + s); 659 return Target2Policy::GotRel; 660 } 661 662 static bool isOutputFormatBinary(opt::InputArgList &args) { 663 StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 664 if (s == "binary") 665 return true; 666 if (!s.startswith("elf")) 667 error("unknown --oformat value: " + s); 668 return false; 669 } 670 671 static DiscardPolicy getDiscard(opt::InputArgList &args) { 672 auto *arg = 673 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 674 if (!arg) 675 return DiscardPolicy::Default; 676 if (arg->getOption().getID() == OPT_discard_all) 677 return DiscardPolicy::All; 678 if (arg->getOption().getID() == OPT_discard_locals) 679 return DiscardPolicy::Locals; 680 return DiscardPolicy::None; 681 } 682 683 static StringRef getDynamicLinker(opt::InputArgList &args) { 684 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 685 if (!arg) 686 return ""; 687 if (arg->getOption().getID() == OPT_no_dynamic_linker) { 688 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 689 config->noDynamicLinker = true; 690 return ""; 691 } 692 return arg->getValue(); 693 } 694 695 static ICFLevel getICF(opt::InputArgList &args) { 696 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 697 if (!arg || arg->getOption().getID() == OPT_icf_none) 698 return ICFLevel::None; 699 if (arg->getOption().getID() == OPT_icf_safe) 700 return ICFLevel::Safe; 701 return ICFLevel::All; 702 } 703 704 static StripPolicy getStrip(opt::InputArgList &args) { 705 if (args.hasArg(OPT_relocatable)) 706 return StripPolicy::None; 707 708 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 709 if (!arg) 710 return StripPolicy::None; 711 if (arg->getOption().getID() == OPT_strip_all) 712 return StripPolicy::All; 713 return StripPolicy::Debug; 714 } 715 716 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 717 const opt::Arg &arg) { 718 uint64_t va = 0; 719 if (s.startswith("0x")) 720 s = s.drop_front(2); 721 if (!to_integer(s, va, 16)) 722 error("invalid argument: " + arg.getAsString(args)); 723 return va; 724 } 725 726 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 727 StringMap<uint64_t> ret; 728 for (auto *arg : args.filtered(OPT_section_start)) { 729 StringRef name; 730 StringRef addr; 731 std::tie(name, addr) = StringRef(arg->getValue()).split('='); 732 ret[name] = parseSectionAddress(addr, args, *arg); 733 } 734 735 if (auto *arg = args.getLastArg(OPT_Ttext)) 736 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 737 if (auto *arg = args.getLastArg(OPT_Tdata)) 738 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 739 if (auto *arg = args.getLastArg(OPT_Tbss)) 740 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 741 return ret; 742 } 743 744 static SortSectionPolicy getSortSection(opt::InputArgList &args) { 745 StringRef s = args.getLastArgValue(OPT_sort_section); 746 if (s == "alignment") 747 return SortSectionPolicy::Alignment; 748 if (s == "name") 749 return SortSectionPolicy::Name; 750 if (!s.empty()) 751 error("unknown --sort-section rule: " + s); 752 return SortSectionPolicy::Default; 753 } 754 755 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 756 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 757 if (s == "warn") 758 return OrphanHandlingPolicy::Warn; 759 if (s == "error") 760 return OrphanHandlingPolicy::Error; 761 if (s != "place") 762 error("unknown --orphan-handling mode: " + s); 763 return OrphanHandlingPolicy::Place; 764 } 765 766 // Parse --build-id or --build-id=<style>. We handle "tree" as a 767 // synonym for "sha1" because all our hash functions including 768 // --build-id=sha1 are actually tree hashes for performance reasons. 769 static std::pair<BuildIdKind, std::vector<uint8_t>> 770 getBuildId(opt::InputArgList &args) { 771 auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq); 772 if (!arg) 773 return {BuildIdKind::None, {}}; 774 775 if (arg->getOption().getID() == OPT_build_id) 776 return {BuildIdKind::Fast, {}}; 777 778 StringRef s = arg->getValue(); 779 if (s == "fast") 780 return {BuildIdKind::Fast, {}}; 781 if (s == "md5") 782 return {BuildIdKind::Md5, {}}; 783 if (s == "sha1" || s == "tree") 784 return {BuildIdKind::Sha1, {}}; 785 if (s == "uuid") 786 return {BuildIdKind::Uuid, {}}; 787 if (s.startswith("0x")) 788 return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 789 790 if (s != "none") 791 error("unknown --build-id style: " + s); 792 return {BuildIdKind::None, {}}; 793 } 794 795 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 796 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 797 if (s == "android") 798 return {true, false}; 799 if (s == "relr") 800 return {false, true}; 801 if (s == "android+relr") 802 return {true, true}; 803 804 if (s != "none") 805 error("unknown --pack-dyn-relocs format: " + s); 806 return {false, false}; 807 } 808 809 static void readCallGraph(MemoryBufferRef mb) { 810 // Build a map from symbol name to section 811 DenseMap<StringRef, Symbol *> map; 812 for (ELFFileBase *file : objectFiles) 813 for (Symbol *sym : file->getSymbols()) 814 map[sym->getName()] = sym; 815 816 auto findSection = [&](StringRef name) -> InputSectionBase * { 817 Symbol *sym = map.lookup(name); 818 if (!sym) { 819 if (config->warnSymbolOrdering) 820 warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 821 return nullptr; 822 } 823 maybeWarnUnorderableSymbol(sym); 824 825 if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 826 return dyn_cast_or_null<InputSectionBase>(dr->section); 827 return nullptr; 828 }; 829 830 for (StringRef line : args::getLines(mb)) { 831 SmallVector<StringRef, 3> fields; 832 line.split(fields, ' '); 833 uint64_t count; 834 835 if (fields.size() != 3 || !to_integer(fields[2], count)) { 836 error(mb.getBufferIdentifier() + ": parse error"); 837 return; 838 } 839 840 if (InputSectionBase *from = findSection(fields[0])) 841 if (InputSectionBase *to = findSection(fields[1])) 842 config->callGraphProfile[std::make_pair(from, to)] += count; 843 } 844 } 845 846 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 847 // true and populates cgProfile and symbolIndices. 848 template <class ELFT> 849 static bool 850 processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices, 851 ArrayRef<typename ELFT::CGProfile> &cgProfile, 852 ObjFile<ELFT> *inputObj) { 853 if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 854 return false; 855 856 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 857 inputObj->template getELFShdrs<ELFT>(); 858 symbolIndices.clear(); 859 const ELFFile<ELFT> &obj = inputObj->getObj(); 860 cgProfile = 861 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 862 objSections[inputObj->cgProfileSectionIndex])); 863 864 for (size_t i = 0, e = objSections.size(); i < e; ++i) { 865 const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 866 if (sec.sh_info == inputObj->cgProfileSectionIndex) { 867 if (sec.sh_type == SHT_RELA) { 868 ArrayRef<typename ELFT::Rela> relas = 869 CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 870 for (const typename ELFT::Rela &rel : relas) 871 symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 872 break; 873 } 874 if (sec.sh_type == SHT_REL) { 875 ArrayRef<typename ELFT::Rel> rels = 876 CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 877 for (const typename ELFT::Rel &rel : rels) 878 symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 879 break; 880 } 881 } 882 } 883 if (symbolIndices.empty()) 884 warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"); 885 return !symbolIndices.empty(); 886 } 887 888 template <class ELFT> static void readCallGraphsFromObjectFiles() { 889 SmallVector<uint32_t, 32> symbolIndices; 890 ArrayRef<typename ELFT::CGProfile> cgProfile; 891 for (auto file : objectFiles) { 892 auto *obj = cast<ObjFile<ELFT>>(file); 893 if (!processCallGraphRelocations(symbolIndices, cgProfile, obj)) 894 continue; 895 896 if (symbolIndices.size() != cgProfile.size() * 2) 897 fatal("number of relocations doesn't match Weights"); 898 899 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 900 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 901 uint32_t fromIndex = symbolIndices[i * 2]; 902 uint32_t toIndex = symbolIndices[i * 2 + 1]; 903 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 904 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 905 if (!fromSym || !toSym) 906 continue; 907 908 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 909 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 910 if (from && to) 911 config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 912 } 913 } 914 } 915 916 static bool getCompressDebugSections(opt::InputArgList &args) { 917 StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none"); 918 if (s == "none") 919 return false; 920 if (s != "zlib") 921 error("unknown --compress-debug-sections value: " + s); 922 if (!zlib::isAvailable()) 923 error("--compress-debug-sections: zlib is not available"); 924 return true; 925 } 926 927 static StringRef getAliasSpelling(opt::Arg *arg) { 928 if (const opt::Arg *alias = arg->getAlias()) 929 return alias->getSpelling(); 930 return arg->getSpelling(); 931 } 932 933 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 934 unsigned id) { 935 auto *arg = args.getLastArg(id); 936 if (!arg) 937 return {"", ""}; 938 939 StringRef s = arg->getValue(); 940 std::pair<StringRef, StringRef> ret = s.split(';'); 941 if (ret.second.empty()) 942 error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 943 return ret; 944 } 945 946 // Parse the symbol ordering file and warn for any duplicate entries. 947 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) { 948 SetVector<StringRef> names; 949 for (StringRef s : args::getLines(mb)) 950 if (!names.insert(s) && config->warnSymbolOrdering) 951 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 952 953 return names.takeVector(); 954 } 955 956 static bool getIsRela(opt::InputArgList &args) { 957 // If -z rel or -z rela is specified, use the last option. 958 for (auto *arg : args.filtered_reverse(OPT_z)) { 959 StringRef s(arg->getValue()); 960 if (s == "rel") 961 return false; 962 if (s == "rela") 963 return true; 964 } 965 966 // Otherwise use the psABI defined relocation entry format. 967 uint16_t m = config->emachine; 968 return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC || 969 m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64; 970 } 971 972 static void parseClangOption(StringRef opt, const Twine &msg) { 973 std::string err; 974 raw_string_ostream os(err); 975 976 const char *argv[] = {config->progName.data(), opt.data()}; 977 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 978 return; 979 os.flush(); 980 error(msg + ": " + StringRef(err).trim()); 981 } 982 983 // Checks the parameter of the bti-report and cet-report options. 984 static bool isValidReportString(StringRef arg) { 985 return arg == "none" || arg == "warning" || arg == "error"; 986 } 987 988 // Initializes Config members by the command line options. 989 static void readConfigs(opt::InputArgList &args) { 990 errorHandler().verbose = args.hasArg(OPT_verbose); 991 errorHandler().vsDiagnostics = 992 args.hasArg(OPT_visual_studio_diagnostics_format, false); 993 994 config->allowMultipleDefinition = 995 args.hasFlag(OPT_allow_multiple_definition, 996 OPT_no_allow_multiple_definition, false) || 997 hasZOption(args, "muldefs"); 998 config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 999 if (opt::Arg *arg = 1000 args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 1001 OPT_Bsymbolic_functions, OPT_Bsymbolic)) { 1002 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 1003 config->bsymbolic = BsymbolicKind::NonWeakFunctions; 1004 else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 1005 config->bsymbolic = BsymbolicKind::Functions; 1006 else if (arg->getOption().matches(OPT_Bsymbolic)) 1007 config->bsymbolic = BsymbolicKind::All; 1008 } 1009 config->checkSections = 1010 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 1011 config->chroot = args.getLastArgValue(OPT_chroot); 1012 config->compressDebugSections = getCompressDebugSections(args); 1013 config->cref = args.hasArg(OPT_cref); 1014 config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common, 1015 !args.hasArg(OPT_relocatable)); 1016 config->optimizeBBJumps = 1017 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 1018 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1019 config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 1020 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 1021 config->disableVerify = args.hasArg(OPT_disable_verify); 1022 config->discard = getDiscard(args); 1023 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 1024 config->dynamicLinker = getDynamicLinker(args); 1025 config->ehFrameHdr = 1026 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 1027 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 1028 config->emitRelocs = args.hasArg(OPT_emit_relocs); 1029 config->callGraphProfileSort = args.hasFlag( 1030 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 1031 config->enableNewDtags = 1032 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 1033 config->entry = args.getLastArgValue(OPT_entry); 1034 1035 errorHandler().errorHandlingScript = 1036 args.getLastArgValue(OPT_error_handling_script); 1037 1038 config->executeOnly = 1039 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 1040 config->exportDynamic = 1041 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 1042 config->filterList = args::getStrings(args, OPT_filter); 1043 config->fini = args.getLastArgValue(OPT_fini, "_fini"); 1044 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 1045 !args.hasArg(OPT_relocatable); 1046 config->fixCortexA8 = 1047 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1048 config->fortranCommon = 1049 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, true); 1050 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 1051 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 1052 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 1053 config->icf = getICF(args); 1054 config->ignoreDataAddressEquality = 1055 args.hasArg(OPT_ignore_data_address_equality); 1056 config->ignoreFunctionAddressEquality = 1057 args.hasArg(OPT_ignore_function_address_equality); 1058 config->init = args.getLastArgValue(OPT_init, "_init"); 1059 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 1060 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1061 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1062 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1063 OPT_no_lto_pgo_warn_mismatch, true); 1064 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 1065 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 1066 config->ltoNewPassManager = 1067 args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager, 1068 LLVM_ENABLE_NEW_PASS_MANAGER); 1069 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 1070 config->ltoWholeProgramVisibility = 1071 args.hasFlag(OPT_lto_whole_program_visibility, 1072 OPT_no_lto_whole_program_visibility, false); 1073 config->ltoo = args::getInteger(args, OPT_lto_O, 2); 1074 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 1075 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 1076 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 1077 config->ltoBasicBlockSections = 1078 args.getLastArgValue(OPT_lto_basic_block_sections); 1079 config->ltoUniqueBasicBlockSectionNames = 1080 args.hasFlag(OPT_lto_unique_basic_block_section_names, 1081 OPT_no_lto_unique_basic_block_section_names, false); 1082 config->mapFile = args.getLastArgValue(OPT_Map); 1083 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 1084 config->mergeArmExidx = 1085 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1086 config->mmapOutputFile = 1087 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 1088 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 1089 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 1090 config->nostdlib = args.hasArg(OPT_nostdlib); 1091 config->oFormatBinary = isOutputFormatBinary(args); 1092 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 1093 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 1094 1095 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1096 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1097 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1098 if (!resultOrErr) 1099 error(arg->getSpelling() + ": invalid argument '" + arg->getValue() + 1100 "', only integer or 'auto' is supported"); 1101 else 1102 config->optRemarksHotnessThreshold = *resultOrErr; 1103 } 1104 1105 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 1106 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 1107 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 1108 config->optimize = args::getInteger(args, OPT_O, 1); 1109 config->orphanHandling = getOrphanHandling(args); 1110 config->outputFile = args.getLastArgValue(OPT_o); 1111 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 1112 config->printIcfSections = 1113 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 1114 config->printGcSections = 1115 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1116 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 1117 config->printSymbolOrder = 1118 args.getLastArgValue(OPT_print_symbol_order); 1119 config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 1120 config->rpath = getRpath(args); 1121 config->relocatable = args.hasArg(OPT_relocatable); 1122 config->saveTemps = args.hasArg(OPT_save_temps); 1123 config->searchPaths = args::getStrings(args, OPT_library_path); 1124 config->sectionStartMap = getSectionStartMap(args); 1125 config->shared = args.hasArg(OPT_shared); 1126 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 1127 config->soName = args.getLastArgValue(OPT_soname); 1128 config->sortSection = getSortSection(args); 1129 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 1130 config->strip = getStrip(args); 1131 config->sysroot = args.getLastArgValue(OPT_sysroot); 1132 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 1133 config->target2 = getTarget2(args); 1134 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 1135 config->thinLTOCachePolicy = CHECK( 1136 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 1137 "--thinlto-cache-policy: invalid cache policy"); 1138 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1139 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1140 args.hasArg(OPT_thinlto_index_only_eq); 1141 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 1142 config->thinLTOObjectSuffixReplace = 1143 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 1144 config->thinLTOPrefixReplace = 1145 getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 1146 config->thinLTOModulesToCompile = 1147 args::getStrings(args, OPT_thinlto_single_module_eq); 1148 config->timeTraceEnabled = args.hasArg(OPT_time_trace); 1149 config->timeTraceGranularity = 1150 args::getInteger(args, OPT_time_trace_granularity, 500); 1151 config->trace = args.hasArg(OPT_trace); 1152 config->undefined = args::getStrings(args, OPT_undefined); 1153 config->undefinedVersion = 1154 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 1155 config->unique = args.hasArg(OPT_unique); 1156 config->useAndroidRelrTags = args.hasFlag( 1157 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 1158 config->warnBackrefs = 1159 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 1160 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 1161 config->warnSymbolOrdering = 1162 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1163 config->whyExtract = args.getLastArgValue(OPT_why_extract); 1164 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 1165 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1166 config->zForceBti = hasZOption(args, "force-bti"); 1167 config->zForceIbt = hasZOption(args, "force-ibt"); 1168 config->zGlobal = hasZOption(args, "global"); 1169 config->zGnustack = getZGnuStack(args); 1170 config->zHazardplt = hasZOption(args, "hazardplt"); 1171 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 1172 config->zInitfirst = hasZOption(args, "initfirst"); 1173 config->zInterpose = hasZOption(args, "interpose"); 1174 config->zKeepTextSectionPrefix = getZFlag( 1175 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 1176 config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 1177 config->zNodelete = hasZOption(args, "nodelete"); 1178 config->zNodlopen = hasZOption(args, "nodlopen"); 1179 config->zNow = getZFlag(args, "now", "lazy", false); 1180 config->zOrigin = hasZOption(args, "origin"); 1181 config->zPacPlt = hasZOption(args, "pac-plt"); 1182 config->zRelro = getZFlag(args, "relro", "norelro", true); 1183 config->zRetpolineplt = hasZOption(args, "retpolineplt"); 1184 config->zRodynamic = hasZOption(args, "rodynamic"); 1185 config->zSeparate = getZSeparate(args); 1186 config->zShstk = hasZOption(args, "shstk"); 1187 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1188 config->zStartStopGC = 1189 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 1190 config->zStartStopVisibility = getZStartStopVisibility(args); 1191 config->zText = getZFlag(args, "text", "notext", true); 1192 config->zWxneeded = hasZOption(args, "wxneeded"); 1193 setUnresolvedSymbolPolicy(args); 1194 config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1195 1196 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1197 if (arg->getOption().matches(OPT_eb)) 1198 config->optEB = true; 1199 else 1200 config->optEL = true; 1201 } 1202 1203 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1204 constexpr StringRef errPrefix = "--shuffle-sections=: "; 1205 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1206 if (kv.first.empty() || kv.second.empty()) { 1207 error(errPrefix + "expected <section_glob>=<seed>, but got '" + 1208 arg->getValue() + "'"); 1209 continue; 1210 } 1211 // Signed so that <section_glob>=-1 is allowed. 1212 int64_t v; 1213 if (!to_integer(kv.second, v)) 1214 error(errPrefix + "expected an integer, but got '" + kv.second + "'"); 1215 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1216 config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1217 else 1218 error(errPrefix + toString(pat.takeError())); 1219 } 1220 1221 auto reports = {std::make_pair("bti-report", &config->zBtiReport), 1222 std::make_pair("cet-report", &config->zCetReport)}; 1223 for (opt::Arg *arg : args.filtered(OPT_z)) { 1224 std::pair<StringRef, StringRef> option = 1225 StringRef(arg->getValue()).split('='); 1226 for (auto reportArg : reports) { 1227 if (option.first != reportArg.first) 1228 continue; 1229 if (!isValidReportString(option.second)) { 1230 error(Twine("-z ") + reportArg.first + "= parameter " + option.second + 1231 " is not recognized"); 1232 continue; 1233 } 1234 *reportArg.second = option.second; 1235 } 1236 } 1237 1238 for (opt::Arg *arg : args.filtered(OPT_z)) { 1239 std::pair<StringRef, StringRef> option = 1240 StringRef(arg->getValue()).split('='); 1241 if (option.first != "dead-reloc-in-nonalloc") 1242 continue; 1243 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1244 std::pair<StringRef, StringRef> kv = option.second.split('='); 1245 if (kv.first.empty() || kv.second.empty()) { 1246 error(errPrefix + "expected <section_glob>=<value>"); 1247 continue; 1248 } 1249 uint64_t v; 1250 if (!to_integer(kv.second, v)) 1251 error(errPrefix + "expected a non-negative integer, but got '" + 1252 kv.second + "'"); 1253 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1254 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1255 else 1256 error(errPrefix + toString(pat.takeError())); 1257 } 1258 1259 cl::ResetAllOptionOccurrences(); 1260 1261 // Parse LTO options. 1262 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 1263 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 1264 arg->getSpelling()); 1265 1266 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1267 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 1268 1269 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1270 // relative path. Just ignore. If not ended with "lto-wrapper", consider it an 1271 // unsupported LLVMgold.so option and error. 1272 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) 1273 if (!StringRef(arg->getValue()).endswith("lto-wrapper")) 1274 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 1275 "'"); 1276 1277 // Parse -mllvm options. 1278 for (auto *arg : args.filtered(OPT_mllvm)) 1279 parseClangOption(arg->getValue(), arg->getSpelling()); 1280 1281 // --threads= takes a positive integer and provides the default value for 1282 // --thinlto-jobs=. 1283 if (auto *arg = args.getLastArg(OPT_threads)) { 1284 StringRef v(arg->getValue()); 1285 unsigned threads = 0; 1286 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1287 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1288 arg->getValue() + "'"); 1289 parallel::strategy = hardware_concurrency(threads); 1290 config->thinLTOJobs = v; 1291 } 1292 if (auto *arg = args.getLastArg(OPT_thinlto_jobs)) 1293 config->thinLTOJobs = arg->getValue(); 1294 1295 if (config->ltoo > 3) 1296 error("invalid optimization level for LTO: " + Twine(config->ltoo)); 1297 if (config->ltoPartitions == 0) 1298 error("--lto-partitions: number of threads must be > 0"); 1299 if (!get_threadpool_strategy(config->thinLTOJobs)) 1300 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 1301 1302 if (config->splitStackAdjustSize < 0) 1303 error("--split-stack-adjust-size: size must be >= 0"); 1304 1305 // The text segment is traditionally the first segment, whose address equals 1306 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1307 // is an old-fashioned option that does not play well with lld's layout. 1308 // Suggest --image-base as a likely alternative. 1309 if (args.hasArg(OPT_Ttext_segment)) 1310 error("-Ttext-segment is not supported. Use --image-base if you " 1311 "intend to set the base address"); 1312 1313 // Parse ELF{32,64}{LE,BE} and CPU type. 1314 if (auto *arg = args.getLastArg(OPT_m)) { 1315 StringRef s = arg->getValue(); 1316 std::tie(config->ekind, config->emachine, config->osabi) = 1317 parseEmulation(s); 1318 config->mipsN32Abi = 1319 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 1320 config->emulation = s; 1321 } 1322 1323 // Parse --hash-style={sysv,gnu,both}. 1324 if (auto *arg = args.getLastArg(OPT_hash_style)) { 1325 StringRef s = arg->getValue(); 1326 if (s == "sysv") 1327 config->sysvHash = true; 1328 else if (s == "gnu") 1329 config->gnuHash = true; 1330 else if (s == "both") 1331 config->sysvHash = config->gnuHash = true; 1332 else 1333 error("unknown --hash-style: " + s); 1334 } 1335 1336 if (args.hasArg(OPT_print_map)) 1337 config->mapFile = "-"; 1338 1339 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 1340 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1341 // it. 1342 if (config->nmagic || config->omagic) 1343 config->zRelro = false; 1344 1345 std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 1346 1347 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 1348 getPackDynRelocs(args); 1349 1350 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 1351 if (args.hasArg(OPT_call_graph_ordering_file)) 1352 error("--symbol-ordering-file and --call-graph-order-file " 1353 "may not be used together"); 1354 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){ 1355 config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 1356 // Also need to disable CallGraphProfileSort to prevent 1357 // LLD order symbols with CGProfile 1358 config->callGraphProfileSort = false; 1359 } 1360 } 1361 1362 assert(config->versionDefinitions.empty()); 1363 config->versionDefinitions.push_back( 1364 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 1365 config->versionDefinitions.push_back( 1366 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 1367 1368 // If --retain-symbol-file is used, we'll keep only the symbols listed in 1369 // the file and discard all others. 1370 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 1371 config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 1372 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1373 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1374 for (StringRef s : args::getLines(*buffer)) 1375 config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 1376 {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 1377 } 1378 1379 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1380 StringRef pattern(arg->getValue()); 1381 if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1382 config->warnBackrefsExclude.push_back(std::move(*pat)); 1383 else 1384 error(arg->getSpelling() + ": " + toString(pat.takeError())); 1385 } 1386 1387 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1388 // which should be exported. For -shared, references to matched non-local 1389 // STV_DEFAULT symbols are not bound to definitions within the shared object, 1390 // even if other options express a symbolic intention: -Bsymbolic, 1391 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 1392 for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 1393 config->dynamicList.push_back( 1394 {arg->getValue(), /*isExternCpp=*/false, 1395 /*hasWildcard=*/hasWildcard(arg->getValue())}); 1396 1397 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1398 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1399 // like semantics. 1400 config->symbolic = 1401 config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1402 for (auto *arg : 1403 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1404 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1405 readDynamicList(*buffer); 1406 1407 for (auto *arg : args.filtered(OPT_version_script)) 1408 if (Optional<std::string> path = searchScript(arg->getValue())) { 1409 if (Optional<MemoryBufferRef> buffer = readFile(*path)) 1410 readVersionScript(*buffer); 1411 } else { 1412 error(Twine("cannot find version script ") + arg->getValue()); 1413 } 1414 } 1415 1416 // Some Config members do not directly correspond to any particular 1417 // command line options, but computed based on other Config values. 1418 // This function initialize such members. See Config.h for the details 1419 // of these values. 1420 static void setConfigs(opt::InputArgList &args) { 1421 ELFKind k = config->ekind; 1422 uint16_t m = config->emachine; 1423 1424 config->copyRelocs = (config->relocatable || config->emitRelocs); 1425 config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 1426 config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 1427 config->endianness = config->isLE ? endianness::little : endianness::big; 1428 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 1429 config->isPic = config->pie || config->shared; 1430 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 1431 config->wordsize = config->is64 ? 8 : 4; 1432 1433 // ELF defines two different ways to store relocation addends as shown below: 1434 // 1435 // Rel: Addends are stored to the location where relocations are applied. It 1436 // cannot pack the full range of addend values for all relocation types, but 1437 // this only affects relocation types that we don't support emitting as 1438 // dynamic relocations (see getDynRel). 1439 // Rela: Addends are stored as part of relocation entry. 1440 // 1441 // In other words, Rela makes it easy to read addends at the price of extra 1442 // 4 or 8 byte for each relocation entry. 1443 // 1444 // We pick the format for dynamic relocations according to the psABI for each 1445 // processor, but a contrary choice can be made if the dynamic loader 1446 // supports. 1447 config->isRela = getIsRela(args); 1448 1449 // If the output uses REL relocations we must store the dynamic relocation 1450 // addends to the output sections. We also store addends for RELA relocations 1451 // if --apply-dynamic-relocs is used. 1452 // We default to not writing the addends when using RELA relocations since 1453 // any standard conforming tool can find it in r_addend. 1454 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 1455 OPT_no_apply_dynamic_relocs, false) || 1456 !config->isRela; 1457 // Validation of dynamic relocation addends is on by default for assertions 1458 // builds (for supported targets) and disabled otherwise. Ideally we would 1459 // enable the debug checks for all targets, but currently not all targets 1460 // have support for reading Elf_Rel addends, so we only enable for a subset. 1461 #ifndef NDEBUG 1462 bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS || 1463 m == EM_X86_64 || m == EM_RISCV; 1464 #else 1465 bool checkDynamicRelocsDefault = false; 1466 #endif 1467 config->checkDynamicRelocs = 1468 args.hasFlag(OPT_check_dynamic_relocations, 1469 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 1470 config->tocOptimize = 1471 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1472 config->pcRelOptimize = 1473 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 1474 } 1475 1476 static bool isFormatBinary(StringRef s) { 1477 if (s == "binary") 1478 return true; 1479 if (s == "elf" || s == "default") 1480 return false; 1481 error("unknown --format value: " + s + 1482 " (supported formats: elf, default, binary)"); 1483 return false; 1484 } 1485 1486 void LinkerDriver::createFiles(opt::InputArgList &args) { 1487 llvm::TimeTraceScope timeScope("Load input files"); 1488 // For --{push,pop}-state. 1489 std::vector<std::tuple<bool, bool, bool>> stack; 1490 1491 // Iterate over argv to process input files and positional arguments. 1492 InputFile::isInGroup = false; 1493 for (auto *arg : args) { 1494 switch (arg->getOption().getID()) { 1495 case OPT_library: 1496 addLibrary(arg->getValue()); 1497 break; 1498 case OPT_INPUT: 1499 addFile(arg->getValue(), /*withLOption=*/false); 1500 break; 1501 case OPT_defsym: { 1502 StringRef from; 1503 StringRef to; 1504 std::tie(from, to) = StringRef(arg->getValue()).split('='); 1505 if (from.empty() || to.empty()) 1506 error("--defsym: syntax error: " + StringRef(arg->getValue())); 1507 else 1508 readDefsym(from, MemoryBufferRef(to, "--defsym")); 1509 break; 1510 } 1511 case OPT_script: 1512 if (Optional<std::string> path = searchScript(arg->getValue())) { 1513 if (Optional<MemoryBufferRef> mb = readFile(*path)) 1514 readLinkerScript(*mb); 1515 break; 1516 } 1517 error(Twine("cannot find linker script ") + arg->getValue()); 1518 break; 1519 case OPT_as_needed: 1520 config->asNeeded = true; 1521 break; 1522 case OPT_format: 1523 config->formatBinary = isFormatBinary(arg->getValue()); 1524 break; 1525 case OPT_no_as_needed: 1526 config->asNeeded = false; 1527 break; 1528 case OPT_Bstatic: 1529 case OPT_omagic: 1530 case OPT_nmagic: 1531 config->isStatic = true; 1532 break; 1533 case OPT_Bdynamic: 1534 config->isStatic = false; 1535 break; 1536 case OPT_whole_archive: 1537 inWholeArchive = true; 1538 break; 1539 case OPT_no_whole_archive: 1540 inWholeArchive = false; 1541 break; 1542 case OPT_just_symbols: 1543 if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1544 files.push_back(createObjectFile(*mb)); 1545 files.back()->justSymbols = true; 1546 } 1547 break; 1548 case OPT_start_group: 1549 if (InputFile::isInGroup) 1550 error("nested --start-group"); 1551 InputFile::isInGroup = true; 1552 break; 1553 case OPT_end_group: 1554 if (!InputFile::isInGroup) 1555 error("stray --end-group"); 1556 InputFile::isInGroup = false; 1557 ++InputFile::nextGroupId; 1558 break; 1559 case OPT_start_lib: 1560 if (inLib) 1561 error("nested --start-lib"); 1562 if (InputFile::isInGroup) 1563 error("may not nest --start-lib in --start-group"); 1564 inLib = true; 1565 InputFile::isInGroup = true; 1566 break; 1567 case OPT_end_lib: 1568 if (!inLib) 1569 error("stray --end-lib"); 1570 inLib = false; 1571 InputFile::isInGroup = false; 1572 ++InputFile::nextGroupId; 1573 break; 1574 case OPT_push_state: 1575 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 1576 break; 1577 case OPT_pop_state: 1578 if (stack.empty()) { 1579 error("unbalanced --push-state/--pop-state"); 1580 break; 1581 } 1582 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 1583 stack.pop_back(); 1584 break; 1585 } 1586 } 1587 1588 if (files.empty() && errorCount() == 0) 1589 error("no input files"); 1590 } 1591 1592 // If -m <machine_type> was not given, infer it from object files. 1593 void LinkerDriver::inferMachineType() { 1594 if (config->ekind != ELFNoneKind) 1595 return; 1596 1597 for (InputFile *f : files) { 1598 if (f->ekind == ELFNoneKind) 1599 continue; 1600 config->ekind = f->ekind; 1601 config->emachine = f->emachine; 1602 config->osabi = f->osabi; 1603 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 1604 return; 1605 } 1606 error("target emulation unknown: -m or at least one .o file required"); 1607 } 1608 1609 // Parse -z max-page-size=<value>. The default value is defined by 1610 // each target. 1611 static uint64_t getMaxPageSize(opt::InputArgList &args) { 1612 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 1613 target->defaultMaxPageSize); 1614 if (!isPowerOf2_64(val)) 1615 error("max-page-size: value isn't a power of 2"); 1616 if (config->nmagic || config->omagic) { 1617 if (val != target->defaultMaxPageSize) 1618 warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 1619 return 1; 1620 } 1621 return val; 1622 } 1623 1624 // Parse -z common-page-size=<value>. The default value is defined by 1625 // each target. 1626 static uint64_t getCommonPageSize(opt::InputArgList &args) { 1627 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 1628 target->defaultCommonPageSize); 1629 if (!isPowerOf2_64(val)) 1630 error("common-page-size: value isn't a power of 2"); 1631 if (config->nmagic || config->omagic) { 1632 if (val != target->defaultCommonPageSize) 1633 warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 1634 return 1; 1635 } 1636 // commonPageSize can't be larger than maxPageSize. 1637 if (val > config->maxPageSize) 1638 val = config->maxPageSize; 1639 return val; 1640 } 1641 1642 // Parses --image-base option. 1643 static Optional<uint64_t> getImageBase(opt::InputArgList &args) { 1644 // Because we are using "Config->maxPageSize" here, this function has to be 1645 // called after the variable is initialized. 1646 auto *arg = args.getLastArg(OPT_image_base); 1647 if (!arg) 1648 return None; 1649 1650 StringRef s = arg->getValue(); 1651 uint64_t v; 1652 if (!to_integer(s, v)) { 1653 error("--image-base: number expected, but got " + s); 1654 return 0; 1655 } 1656 if ((v % config->maxPageSize) != 0) 1657 warn("--image-base: address isn't multiple of page size: " + s); 1658 return v; 1659 } 1660 1661 // Parses `--exclude-libs=lib,lib,...`. 1662 // The library names may be delimited by commas or colons. 1663 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 1664 DenseSet<StringRef> ret; 1665 for (auto *arg : args.filtered(OPT_exclude_libs)) { 1666 StringRef s = arg->getValue(); 1667 for (;;) { 1668 size_t pos = s.find_first_of(",:"); 1669 if (pos == StringRef::npos) 1670 break; 1671 ret.insert(s.substr(0, pos)); 1672 s = s.substr(pos + 1); 1673 } 1674 ret.insert(s); 1675 } 1676 return ret; 1677 } 1678 1679 // Handles the --exclude-libs option. If a static library file is specified 1680 // by the --exclude-libs option, all public symbols from the archive become 1681 // private unless otherwise specified by version scripts or something. 1682 // A special library name "ALL" means all archive files. 1683 // 1684 // This is not a popular option, but some programs such as bionic libc use it. 1685 static void excludeLibs(opt::InputArgList &args) { 1686 DenseSet<StringRef> libs = getExcludeLibs(args); 1687 bool all = libs.count("ALL"); 1688 1689 auto visit = [&](InputFile *file) { 1690 if (!file->archiveName.empty()) 1691 if (all || libs.count(path::filename(file->archiveName))) 1692 for (Symbol *sym : file->getSymbols()) 1693 if (!sym->isUndefined() && !sym->isLocal() && sym->file == file) 1694 sym->versionId = VER_NDX_LOCAL; 1695 }; 1696 1697 for (ELFFileBase *file : objectFiles) 1698 visit(file); 1699 1700 for (BitcodeFile *file : bitcodeFiles) 1701 visit(file); 1702 } 1703 1704 // Force Sym to be entered in the output. 1705 static void handleUndefined(Symbol *sym, const char *option) { 1706 // Since a symbol may not be used inside the program, LTO may 1707 // eliminate it. Mark the symbol as "used" to prevent it. 1708 sym->isUsedInRegularObj = true; 1709 1710 if (!sym->isLazy()) 1711 return; 1712 sym->extract(); 1713 if (!config->whyExtract.empty()) 1714 whyExtract.emplace_back(option, sym->file, *sym); 1715 } 1716 1717 // As an extension to GNU linkers, lld supports a variant of `-u` 1718 // which accepts wildcard patterns. All symbols that match a given 1719 // pattern are handled as if they were given by `-u`. 1720 static void handleUndefinedGlob(StringRef arg) { 1721 Expected<GlobPattern> pat = GlobPattern::create(arg); 1722 if (!pat) { 1723 error("--undefined-glob: " + toString(pat.takeError())); 1724 return; 1725 } 1726 1727 // Calling sym->extract() in the loop is not safe because it may add new 1728 // symbols to the symbol table, invalidating the current iterator. 1729 std::vector<Symbol *> syms; 1730 for (Symbol *sym : symtab->symbols()) 1731 if (!sym->isPlaceholder() && pat->match(sym->getName())) 1732 syms.push_back(sym); 1733 1734 for (Symbol *sym : syms) 1735 handleUndefined(sym, "--undefined-glob"); 1736 } 1737 1738 static void handleLibcall(StringRef name) { 1739 Symbol *sym = symtab->find(name); 1740 if (!sym || !sym->isLazy()) 1741 return; 1742 1743 MemoryBufferRef mb; 1744 if (auto *lo = dyn_cast<LazyObject>(sym)) 1745 mb = lo->file->mb; 1746 else 1747 mb = cast<LazyArchive>(sym)->getMemberBuffer(); 1748 1749 if (isBitcode(mb)) 1750 sym->extract(); 1751 } 1752 1753 // Handle --dependency-file=<path>. If that option is given, lld creates a 1754 // file at a given path with the following contents: 1755 // 1756 // <output-file>: <input-file> ... 1757 // 1758 // <input-file>: 1759 // 1760 // where <output-file> is a pathname of an output file and <input-file> 1761 // ... is a list of pathnames of all input files. `make` command can read a 1762 // file in the above format and interpret it as a dependency info. We write 1763 // phony targets for every <input-file> to avoid an error when that file is 1764 // removed. 1765 // 1766 // This option is useful if you want to make your final executable to depend 1767 // on all input files including system libraries. Here is why. 1768 // 1769 // When you write a Makefile, you usually write it so that the final 1770 // executable depends on all user-generated object files. Normally, you 1771 // don't make your executable to depend on system libraries (such as libc) 1772 // because you don't know the exact paths of libraries, even though system 1773 // libraries that are linked to your executable statically are technically a 1774 // part of your program. By using --dependency-file option, you can make 1775 // lld to dump dependency info so that you can maintain exact dependencies 1776 // easily. 1777 static void writeDependencyFile() { 1778 std::error_code ec; 1779 raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None); 1780 if (ec) { 1781 error("cannot open " + config->dependencyFile + ": " + ec.message()); 1782 return; 1783 } 1784 1785 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 1786 // * A space is escaped by a backslash which itself must be escaped. 1787 // * A hash sign is escaped by a single backslash. 1788 // * $ is escapes as $$. 1789 auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 1790 llvm::SmallString<256> nativePath; 1791 llvm::sys::path::native(filename.str(), nativePath); 1792 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 1793 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 1794 if (nativePath[i] == '#') { 1795 os << '\\'; 1796 } else if (nativePath[i] == ' ') { 1797 os << '\\'; 1798 unsigned j = i; 1799 while (j > 0 && nativePath[--j] == '\\') 1800 os << '\\'; 1801 } else if (nativePath[i] == '$') { 1802 os << '$'; 1803 } 1804 os << nativePath[i]; 1805 } 1806 }; 1807 1808 os << config->outputFile << ":"; 1809 for (StringRef path : config->dependencyFiles) { 1810 os << " \\\n "; 1811 printFilename(os, path); 1812 } 1813 os << "\n"; 1814 1815 for (StringRef path : config->dependencyFiles) { 1816 os << "\n"; 1817 printFilename(os, path); 1818 os << ":\n"; 1819 } 1820 } 1821 1822 // Replaces common symbols with defined symbols reside in .bss sections. 1823 // This function is called after all symbol names are resolved. As a 1824 // result, the passes after the symbol resolution won't see any 1825 // symbols of type CommonSymbol. 1826 static void replaceCommonSymbols() { 1827 llvm::TimeTraceScope timeScope("Replace common symbols"); 1828 for (ELFFileBase *file : objectFiles) { 1829 if (!file->hasCommonSyms) 1830 continue; 1831 for (Symbol *sym : file->getGlobalSymbols()) { 1832 auto *s = dyn_cast<CommonSymbol>(sym); 1833 if (!s) 1834 continue; 1835 1836 auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 1837 bss->file = s->file; 1838 bss->markDead(); 1839 inputSections.push_back(bss); 1840 s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type, 1841 /*value=*/0, s->size, bss}); 1842 } 1843 } 1844 } 1845 1846 // If all references to a DSO happen to be weak, the DSO is not added 1847 // to DT_NEEDED. If that happens, we need to eliminate shared symbols 1848 // created from the DSO. Otherwise, they become dangling references 1849 // that point to a non-existent DSO. 1850 static void demoteSharedSymbols() { 1851 llvm::TimeTraceScope timeScope("Demote shared symbols"); 1852 for (Symbol *sym : symtab->symbols()) { 1853 auto *s = dyn_cast<SharedSymbol>(sym); 1854 if (!(s && !s->getFile().isNeeded) && !sym->isLazy()) 1855 continue; 1856 1857 bool used = sym->used; 1858 sym->replace( 1859 Undefined{nullptr, sym->getName(), STB_WEAK, sym->stOther, sym->type}); 1860 sym->used = used; 1861 sym->versionId = VER_NDX_GLOBAL; 1862 } 1863 } 1864 1865 // The section referred to by `s` is considered address-significant. Set the 1866 // keepUnique flag on the section if appropriate. 1867 static void markAddrsig(Symbol *s) { 1868 if (auto *d = dyn_cast_or_null<Defined>(s)) 1869 if (d->section) 1870 // We don't need to keep text sections unique under --icf=all even if they 1871 // are address-significant. 1872 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 1873 d->section->keepUnique = true; 1874 } 1875 1876 // Record sections that define symbols mentioned in --keep-unique <symbol> 1877 // and symbols referred to by address-significance tables. These sections are 1878 // ineligible for ICF. 1879 template <class ELFT> 1880 static void findKeepUniqueSections(opt::InputArgList &args) { 1881 for (auto *arg : args.filtered(OPT_keep_unique)) { 1882 StringRef name = arg->getValue(); 1883 auto *d = dyn_cast_or_null<Defined>(symtab->find(name)); 1884 if (!d || !d->section) { 1885 warn("could not find symbol " + name + " to keep unique"); 1886 continue; 1887 } 1888 d->section->keepUnique = true; 1889 } 1890 1891 // --icf=all --ignore-data-address-equality means that we can ignore 1892 // the dynsym and address-significance tables entirely. 1893 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 1894 return; 1895 1896 // Symbols in the dynsym could be address-significant in other executables 1897 // or DSOs, so we conservatively mark them as address-significant. 1898 for (Symbol *sym : symtab->symbols()) 1899 if (sym->includeInDynsym()) 1900 markAddrsig(sym); 1901 1902 // Visit the address-significance table in each object file and mark each 1903 // referenced symbol as address-significant. 1904 for (InputFile *f : objectFiles) { 1905 auto *obj = cast<ObjFile<ELFT>>(f); 1906 ArrayRef<Symbol *> syms = obj->getSymbols(); 1907 if (obj->addrsigSec) { 1908 ArrayRef<uint8_t> contents = 1909 check(obj->getObj().getSectionContents(*obj->addrsigSec)); 1910 const uint8_t *cur = contents.begin(); 1911 while (cur != contents.end()) { 1912 unsigned size; 1913 const char *err; 1914 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1915 if (err) 1916 fatal(toString(f) + ": could not decode addrsig section: " + err); 1917 markAddrsig(syms[symIndex]); 1918 cur += size; 1919 } 1920 } else { 1921 // If an object file does not have an address-significance table, 1922 // conservatively mark all of its symbols as address-significant. 1923 for (Symbol *s : syms) 1924 markAddrsig(s); 1925 } 1926 } 1927 } 1928 1929 // This function reads a symbol partition specification section. These sections 1930 // are used to control which partition a symbol is allocated to. See 1931 // https://lld.llvm.org/Partitions.html for more details on partitions. 1932 template <typename ELFT> 1933 static void readSymbolPartitionSection(InputSectionBase *s) { 1934 // Read the relocation that refers to the partition's entry point symbol. 1935 Symbol *sym; 1936 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 1937 if (rels.areRelocsRel()) 1938 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]); 1939 else 1940 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]); 1941 if (!isa<Defined>(sym) || !sym->includeInDynsym()) 1942 return; 1943 1944 StringRef partName = reinterpret_cast<const char *>(s->data().data()); 1945 for (Partition &part : partitions) { 1946 if (part.name == partName) { 1947 sym->partition = part.getNumber(); 1948 return; 1949 } 1950 } 1951 1952 // Forbid partitions from being used on incompatible targets, and forbid them 1953 // from being used together with various linker features that assume a single 1954 // set of output sections. 1955 if (script->hasSectionsCommand) 1956 error(toString(s->file) + 1957 ": partitions cannot be used with the SECTIONS command"); 1958 if (script->hasPhdrsCommands()) 1959 error(toString(s->file) + 1960 ": partitions cannot be used with the PHDRS command"); 1961 if (!config->sectionStartMap.empty()) 1962 error(toString(s->file) + ": partitions cannot be used with " 1963 "--section-start, -Ttext, -Tdata or -Tbss"); 1964 if (config->emachine == EM_MIPS) 1965 error(toString(s->file) + ": partitions cannot be used on this target"); 1966 1967 // Impose a limit of no more than 254 partitions. This limit comes from the 1968 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 1969 // the amount of space devoted to the partition number in RankFlags. 1970 if (partitions.size() == 254) 1971 fatal("may not have more than 254 partitions"); 1972 1973 partitions.emplace_back(); 1974 Partition &newPart = partitions.back(); 1975 newPart.name = partName; 1976 sym->partition = newPart.getNumber(); 1977 } 1978 1979 static Symbol *addUndefined(StringRef name) { 1980 return symtab->addSymbol( 1981 Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}); 1982 } 1983 1984 static Symbol *addUnusedUndefined(StringRef name, 1985 uint8_t binding = STB_GLOBAL) { 1986 Undefined sym{nullptr, name, binding, STV_DEFAULT, 0}; 1987 sym.isUsedInRegularObj = false; 1988 return symtab->addSymbol(sym); 1989 } 1990 1991 static void markBuffersAsDontNeed(bool skipLinkedOutput) { 1992 // With --thinlto-index-only, all buffers are nearly unused from now on 1993 // (except symbol/section names used by infrequent passes). Mark input file 1994 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 1995 // thin link, saving memory. 1996 if (skipLinkedOutput) { 1997 for (MemoryBuffer &mb : llvm::make_pointee_range(memoryBuffers)) 1998 mb.dontNeedIfMmap(); 1999 return; 2000 } 2001 2002 // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 2003 DenseSet<const char *> bufs; 2004 for (BitcodeFile *file : bitcodeFiles) 2005 bufs.insert(file->mb.getBufferStart()); 2006 for (BitcodeFile *file : lazyBitcodeFiles) 2007 bufs.insert(file->mb.getBufferStart()); 2008 for (MemoryBuffer &mb : llvm::make_pointee_range(memoryBuffers)) 2009 if (bufs.count(mb.getBufferStart())) 2010 mb.dontNeedIfMmap(); 2011 } 2012 2013 // This function is where all the optimizations of link-time 2014 // optimization takes place. When LTO is in use, some input files are 2015 // not in native object file format but in the LLVM bitcode format. 2016 // This function compiles bitcode files into a few big native files 2017 // using LLVM functions and replaces bitcode symbols with the results. 2018 // Because all bitcode files that the program consists of are passed to 2019 // the compiler at once, it can do a whole-program optimization. 2020 template <class ELFT> 2021 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 2022 llvm::TimeTraceScope timeScope("LTO"); 2023 // Compile bitcode files and replace bitcode symbols. 2024 lto.reset(new BitcodeCompiler); 2025 for (BitcodeFile *file : bitcodeFiles) 2026 lto->add(*file); 2027 2028 if (!bitcodeFiles.empty()) 2029 markBuffersAsDontNeed(skipLinkedOutput); 2030 2031 for (InputFile *file : lto->compile()) { 2032 auto *obj = cast<ObjFile<ELFT>>(file); 2033 obj->parse(/*ignoreComdats=*/true); 2034 2035 // Parse '@' in symbol names for non-relocatable output. 2036 if (!config->relocatable) 2037 for (Symbol *sym : obj->getGlobalSymbols()) 2038 if (sym->hasVersionSuffix) 2039 sym->parseSymbolVersion(); 2040 objectFiles.push_back(obj); 2041 } 2042 } 2043 2044 // The --wrap option is a feature to rename symbols so that you can write 2045 // wrappers for existing functions. If you pass `--wrap=foo`, all 2046 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2047 // expected to write `__wrap_foo` function as a wrapper). The original 2048 // symbol becomes accessible as `__real_foo`, so you can call that from your 2049 // wrapper. 2050 // 2051 // This data structure is instantiated for each --wrap option. 2052 struct WrappedSymbol { 2053 Symbol *sym; 2054 Symbol *real; 2055 Symbol *wrap; 2056 }; 2057 2058 // Handles --wrap option. 2059 // 2060 // This function instantiates wrapper symbols. At this point, they seem 2061 // like they are not being used at all, so we explicitly set some flags so 2062 // that LTO won't eliminate them. 2063 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 2064 std::vector<WrappedSymbol> v; 2065 DenseSet<StringRef> seen; 2066 2067 for (auto *arg : args.filtered(OPT_wrap)) { 2068 StringRef name = arg->getValue(); 2069 if (!seen.insert(name).second) 2070 continue; 2071 2072 Symbol *sym = symtab->find(name); 2073 if (!sym) 2074 continue; 2075 2076 Symbol *real = addUnusedUndefined(saver.save("__real_" + name)); 2077 Symbol *wrap = 2078 addUnusedUndefined(saver.save("__wrap_" + name), sym->binding); 2079 v.push_back({sym, real, wrap}); 2080 2081 // We want to tell LTO not to inline symbols to be overwritten 2082 // because LTO doesn't know the final symbol contents after renaming. 2083 real->canInline = false; 2084 sym->canInline = false; 2085 2086 // Tell LTO not to eliminate these symbols. 2087 sym->isUsedInRegularObj = true; 2088 // If sym is referenced in any object file, bitcode file or shared object, 2089 // retain wrap which is the redirection target of sym. If the object file 2090 // defining sym has sym references, we cannot easily distinguish the case 2091 // from cases where sym is not referenced. Retain wrap because we choose to 2092 // wrap sym references regardless of whether sym is defined 2093 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 2094 if (sym->referenced || sym->isDefined()) 2095 wrap->isUsedInRegularObj = true; 2096 } 2097 return v; 2098 } 2099 2100 // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 2101 // 2102 // When this function is executed, only InputFiles and symbol table 2103 // contain pointers to symbol objects. We visit them to replace pointers, 2104 // so that wrapped symbols are swapped as instructed by the command line. 2105 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) { 2106 llvm::TimeTraceScope timeScope("Redirect symbols"); 2107 DenseMap<Symbol *, Symbol *> map; 2108 for (const WrappedSymbol &w : wrapped) { 2109 map[w.sym] = w.wrap; 2110 map[w.real] = w.sym; 2111 } 2112 for (Symbol *sym : symtab->symbols()) { 2113 // Enumerate symbols with a non-default version (foo@v1). hasVersionSuffix 2114 // filters out most symbols but is not sufficient. 2115 if (!sym->hasVersionSuffix) 2116 continue; 2117 const char *suffix1 = sym->getVersionSuffix(); 2118 if (suffix1[0] != '@' || suffix1[1] == '@') 2119 continue; 2120 2121 // Check the existing symbol foo. We have two special cases to handle: 2122 // 2123 // * There is a definition of foo@v1 and foo@@v1. 2124 // * There is a definition of foo@v1 and foo. 2125 Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(sym->getName())); 2126 if (!sym2) 2127 continue; 2128 const char *suffix2 = sym2->getVersionSuffix(); 2129 if (suffix2[0] == '@' && suffix2[1] == '@' && 2130 strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2131 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 2132 map.try_emplace(sym, sym2); 2133 // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate 2134 // definition error. 2135 sym2->resolve(*sym); 2136 // Eliminate foo@v1 from the symbol table. 2137 sym->symbolKind = Symbol::PlaceholderKind; 2138 sym->isUsedInRegularObj = false; 2139 } else if (auto *sym1 = dyn_cast<Defined>(sym)) { 2140 if (sym2->versionId > VER_NDX_GLOBAL 2141 ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1 2142 : sym1->section == sym2->section && sym1->value == sym2->value) { 2143 // Due to an assembler design flaw, if foo is defined, .symver foo, 2144 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2145 // different version, GNU ld makes foo@v1 canonical and eliminates foo. 2146 // Emulate its behavior, otherwise we would have foo or foo@@v1 beside 2147 // foo@v1. foo@v1 and foo combining does not apply if they are not 2148 // defined in the same place. 2149 map.try_emplace(sym2, sym); 2150 sym2->symbolKind = Symbol::PlaceholderKind; 2151 sym2->isUsedInRegularObj = false; 2152 } 2153 } 2154 } 2155 2156 if (map.empty()) 2157 return; 2158 2159 // Update pointers in input files. 2160 parallelForEach(objectFiles, [&](ELFFileBase *file) { 2161 for (Symbol *&sym : file->getMutableGlobalSymbols()) 2162 if (Symbol *s = map.lookup(sym)) 2163 sym = s; 2164 }); 2165 2166 // Update pointers in the symbol table. 2167 for (const WrappedSymbol &w : wrapped) 2168 symtab->wrap(w.sym, w.real, w.wrap); 2169 } 2170 2171 static void checkAndReportMissingFeature(StringRef config, uint32_t features, 2172 uint32_t mask, const Twine &report) { 2173 if (!(features & mask)) { 2174 if (config == "error") 2175 error(report); 2176 else if (config == "warning") 2177 warn(report); 2178 } 2179 } 2180 2181 // To enable CET (x86's hardware-assited control flow enforcement), each 2182 // source file must be compiled with -fcf-protection. Object files compiled 2183 // with the flag contain feature flags indicating that they are compatible 2184 // with CET. We enable the feature only when all object files are compatible 2185 // with CET. 2186 // 2187 // This is also the case with AARCH64's BTI and PAC which use the similar 2188 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 2189 template <class ELFT> static uint32_t getAndFeatures() { 2190 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 2191 config->emachine != EM_AARCH64) 2192 return 0; 2193 2194 uint32_t ret = -1; 2195 for (InputFile *f : objectFiles) { 2196 uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures; 2197 2198 checkAndReportMissingFeature( 2199 config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 2200 toString(f) + ": -z bti-report: file does not have " 2201 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2202 2203 checkAndReportMissingFeature( 2204 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT, 2205 toString(f) + ": -z cet-report: file does not have " 2206 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2207 2208 checkAndReportMissingFeature( 2209 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK, 2210 toString(f) + ": -z cet-report: file does not have " 2211 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"); 2212 2213 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 2214 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 2215 if (config->zBtiReport == "none") 2216 warn(toString(f) + ": -z force-bti: file does not have " 2217 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2218 } else if (config->zForceIbt && 2219 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 2220 if (config->zCetReport == "none") 2221 warn(toString(f) + ": -z force-ibt: file does not have " 2222 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2223 features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2224 } 2225 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 2226 warn(toString(f) + ": -z pac-plt: file does not have " 2227 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 2228 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 2229 } 2230 ret &= features; 2231 } 2232 2233 // Force enable Shadow Stack. 2234 if (config->zShstk) 2235 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 2236 2237 return ret; 2238 } 2239 2240 // Do actual linking. Note that when this function is called, 2241 // all linker scripts have already been parsed. 2242 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) { 2243 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2244 // If a --hash-style option was not given, set to a default value, 2245 // which varies depending on the target. 2246 if (!args.hasArg(OPT_hash_style)) { 2247 if (config->emachine == EM_MIPS) 2248 config->sysvHash = true; 2249 else 2250 config->sysvHash = config->gnuHash = true; 2251 } 2252 2253 // Default output filename is "a.out" by the Unix tradition. 2254 if (config->outputFile.empty()) 2255 config->outputFile = "a.out"; 2256 2257 // Fail early if the output file or map file is not writable. If a user has a 2258 // long link, e.g. due to a large LTO link, they do not wish to run it and 2259 // find that it failed because there was a mistake in their command-line. 2260 { 2261 llvm::TimeTraceScope timeScope("Create output files"); 2262 if (auto e = tryCreateFile(config->outputFile)) 2263 error("cannot open output file " + config->outputFile + ": " + 2264 e.message()); 2265 if (auto e = tryCreateFile(config->mapFile)) 2266 error("cannot open map file " + config->mapFile + ": " + e.message()); 2267 if (auto e = tryCreateFile(config->whyExtract)) 2268 error("cannot open --why-extract= file " + config->whyExtract + ": " + 2269 e.message()); 2270 } 2271 if (errorCount()) 2272 return; 2273 2274 // Use default entry point name if no name was given via the command 2275 // line nor linker scripts. For some reason, MIPS entry point name is 2276 // different from others. 2277 config->warnMissingEntry = 2278 (!config->entry.empty() || (!config->shared && !config->relocatable)); 2279 if (config->entry.empty() && !config->relocatable) 2280 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 2281 2282 // Handle --trace-symbol. 2283 for (auto *arg : args.filtered(OPT_trace_symbol)) 2284 symtab->insert(arg->getValue())->traced = true; 2285 2286 // Handle -u/--undefined before input files. If both a.a and b.so define foo, 2287 // -u foo a.a b.so will extract a.a. 2288 for (StringRef name : config->undefined) 2289 addUnusedUndefined(name)->referenced = true; 2290 2291 // Add all files to the symbol table. This will add almost all 2292 // symbols that we need to the symbol table. This process might 2293 // add files to the link, via autolinking, these files are always 2294 // appended to the Files vector. 2295 { 2296 llvm::TimeTraceScope timeScope("Parse input files"); 2297 for (size_t i = 0; i < files.size(); ++i) { 2298 llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName()); 2299 parseFile(files[i]); 2300 } 2301 } 2302 2303 // Now that we have every file, we can decide if we will need a 2304 // dynamic symbol table. 2305 // We need one if we were asked to export dynamic symbols or if we are 2306 // producing a shared library. 2307 // We also need one if any shared libraries are used and for pie executables 2308 // (probably because the dynamic linker needs it). 2309 config->hasDynSymTab = 2310 !sharedFiles.empty() || config->isPic || config->exportDynamic; 2311 2312 // Some symbols (such as __ehdr_start) are defined lazily only when there 2313 // are undefined symbols for them, so we add these to trigger that logic. 2314 for (StringRef name : script->referencedSymbols) 2315 addUndefined(name); 2316 2317 // Prevent LTO from removing any definition referenced by -u. 2318 for (StringRef name : config->undefined) 2319 if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name))) 2320 sym->isUsedInRegularObj = true; 2321 2322 // If an entry symbol is in a static archive, pull out that file now. 2323 if (Symbol *sym = symtab->find(config->entry)) 2324 handleUndefined(sym, "--entry"); 2325 2326 // Handle the `--undefined-glob <pattern>` options. 2327 for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 2328 handleUndefinedGlob(pat); 2329 2330 // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2331 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init))) 2332 sym->isUsedInRegularObj = true; 2333 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini))) 2334 sym->isUsedInRegularObj = true; 2335 2336 // If any of our inputs are bitcode files, the LTO code generator may create 2337 // references to certain library functions that might not be explicit in the 2338 // bitcode file's symbol table. If any of those library functions are defined 2339 // in a bitcode file in an archive member, we need to arrange to use LTO to 2340 // compile those archive members by adding them to the link beforehand. 2341 // 2342 // However, adding all libcall symbols to the link can have undesired 2343 // consequences. For example, the libgcc implementation of 2344 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 2345 // that aborts the program if the Linux kernel does not support 64-bit 2346 // atomics, which would prevent the program from running even if it does not 2347 // use 64-bit atomics. 2348 // 2349 // Therefore, we only add libcall symbols to the link before LTO if we have 2350 // to, i.e. if the symbol's definition is in bitcode. Any other required 2351 // libcall symbols will be added to the link after LTO when we add the LTO 2352 // object file to the link. 2353 if (!bitcodeFiles.empty()) 2354 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2355 handleLibcall(s); 2356 2357 // Return if there were name resolution errors. 2358 if (errorCount()) 2359 return; 2360 2361 // We want to declare linker script's symbols early, 2362 // so that we can version them. 2363 // They also might be exported if referenced by DSOs. 2364 script->declareSymbols(); 2365 2366 // Handle --exclude-libs. This is before scanVersionScript() due to a 2367 // workaround for Android ndk: for a defined versioned symbol in an archive 2368 // without a version node in the version script, Android does not expect a 2369 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2370 // GNU ld errors in this case. 2371 if (args.hasArg(OPT_exclude_libs)) 2372 excludeLibs(args); 2373 2374 // Create elfHeader early. We need a dummy section in 2375 // addReservedSymbols to mark the created symbols as not absolute. 2376 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 2377 2378 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2379 2380 // We need to create some reserved symbols such as _end. Create them. 2381 if (!config->relocatable) 2382 addReservedSymbols(); 2383 2384 // Apply version scripts. 2385 // 2386 // For a relocatable output, version scripts don't make sense, and 2387 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 2388 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2389 if (!config->relocatable) { 2390 llvm::TimeTraceScope timeScope("Process symbol versions"); 2391 symtab->scanVersionScript(); 2392 } 2393 2394 // Skip the normal linked output if some LTO options are specified. 2395 // 2396 // For --thinlto-index-only, index file creation is performed in 2397 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 2398 // --plugin-opt=emit-asm create output files in bitcode or assembly code, 2399 // respectively. When only certain thinLTO modules are specified for 2400 // compilation, the intermediate object file are the expected output. 2401 const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM || 2402 config->ltoEmitAsm || 2403 !config->thinLTOModulesToCompile.empty(); 2404 2405 // Do link-time optimization if given files are LLVM bitcode files. 2406 // This compiles bitcode files into real object files. 2407 // 2408 // With this the symbol table should be complete. After this, no new names 2409 // except a few linker-synthesized ones will be added to the symbol table. 2410 compileBitcodeFiles<ELFT>(skipLinkedOutput); 2411 2412 // Symbol resolution finished. Report backward reference problems. 2413 reportBackrefs(); 2414 if (errorCount()) 2415 return; 2416 2417 // Bail out if normal linked output is skipped due to LTO. 2418 if (skipLinkedOutput) 2419 return; 2420 2421 // Handle --exclude-libs again because lto.tmp may reference additional 2422 // libcalls symbols defined in an excluded archive. This may override 2423 // versionId set by scanVersionScript(). 2424 if (args.hasArg(OPT_exclude_libs)) 2425 excludeLibs(args); 2426 2427 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 2428 redirectSymbols(wrapped); 2429 2430 // Replace common symbols with regular symbols. 2431 replaceCommonSymbols(); 2432 2433 { 2434 llvm::TimeTraceScope timeScope("Aggregate sections"); 2435 // Now that we have a complete list of input files. 2436 // Beyond this point, no new files are added. 2437 // Aggregate all input sections into one place. 2438 for (InputFile *f : objectFiles) 2439 for (InputSectionBase *s : f->getSections()) 2440 if (s && s != &InputSection::discarded) 2441 inputSections.push_back(s); 2442 for (BinaryFile *f : binaryFiles) 2443 for (InputSectionBase *s : f->getSections()) 2444 inputSections.push_back(cast<InputSection>(s)); 2445 } 2446 2447 { 2448 llvm::TimeTraceScope timeScope("Strip sections"); 2449 llvm::erase_if(inputSections, [](InputSectionBase *s) { 2450 if (s->type == SHT_LLVM_SYMPART) { 2451 readSymbolPartitionSection<ELFT>(s); 2452 return true; 2453 } 2454 2455 // We do not want to emit debug sections if --strip-all 2456 // or --strip-debug are given. 2457 if (config->strip == StripPolicy::None) 2458 return false; 2459 2460 if (isDebugSection(*s)) 2461 return true; 2462 if (auto *isec = dyn_cast<InputSection>(s)) 2463 if (InputSectionBase *rel = isec->getRelocatedSection()) 2464 if (isDebugSection(*rel)) 2465 return true; 2466 2467 return false; 2468 }); 2469 } 2470 2471 // Since we now have a complete set of input files, we can create 2472 // a .d file to record build dependencies. 2473 if (!config->dependencyFile.empty()) 2474 writeDependencyFile(); 2475 2476 // Now that the number of partitions is fixed, save a pointer to the main 2477 // partition. 2478 mainPart = &partitions[0]; 2479 2480 // Read .note.gnu.property sections from input object files which 2481 // contain a hint to tweak linker's and loader's behaviors. 2482 config->andFeatures = getAndFeatures<ELFT>(); 2483 2484 // The Target instance handles target-specific stuff, such as applying 2485 // relocations or writing a PLT section. It also contains target-dependent 2486 // values such as a default image base address. 2487 target = getTarget(); 2488 2489 config->eflags = target->calcEFlags(); 2490 // maxPageSize (sometimes called abi page size) is the maximum page size that 2491 // the output can be run on. For example if the OS can use 4k or 64k page 2492 // sizes then maxPageSize must be 64k for the output to be useable on both. 2493 // All important alignment decisions must use this value. 2494 config->maxPageSize = getMaxPageSize(args); 2495 // commonPageSize is the most common page size that the output will be run on. 2496 // For example if an OS can use 4k or 64k page sizes and 4k is more common 2497 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 2498 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 2499 // is limited to writing trap instructions on the last executable segment. 2500 config->commonPageSize = getCommonPageSize(args); 2501 2502 config->imageBase = getImageBase(args); 2503 2504 if (config->emachine == EM_ARM) { 2505 // FIXME: These warnings can be removed when lld only uses these features 2506 // when the input objects have been compiled with an architecture that 2507 // supports them. 2508 if (config->armHasBlx == false) 2509 warn("lld uses blx instruction, no object with architecture supporting " 2510 "feature detected"); 2511 } 2512 2513 // This adds a .comment section containing a version string. 2514 if (!config->relocatable) 2515 inputSections.push_back(createCommentSection()); 2516 2517 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 2518 splitSections<ELFT>(); 2519 2520 // Garbage collection and removal of shared symbols from unused shared objects. 2521 markLive<ELFT>(); 2522 demoteSharedSymbols(); 2523 2524 // Make copies of any input sections that need to be copied into each 2525 // partition. 2526 copySectionsIntoPartitions(); 2527 2528 // Create synthesized sections such as .got and .plt. This is called before 2529 // processSectionCommands() so that they can be placed by SECTIONS commands. 2530 createSyntheticSections<ELFT>(); 2531 2532 // Some input sections that are used for exception handling need to be moved 2533 // into synthetic sections. Do that now so that they aren't assigned to 2534 // output sections in the usual way. 2535 if (!config->relocatable) 2536 combineEhSections(); 2537 2538 { 2539 llvm::TimeTraceScope timeScope("Assign sections"); 2540 2541 // Create output sections described by SECTIONS commands. 2542 script->processSectionCommands(); 2543 2544 // Linker scripts control how input sections are assigned to output 2545 // sections. Input sections that were not handled by scripts are called 2546 // "orphans", and they are assigned to output sections by the default rule. 2547 // Process that. 2548 script->addOrphanSections(); 2549 } 2550 2551 { 2552 llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 2553 2554 // Migrate InputSectionDescription::sectionBases to sections. This includes 2555 // merging MergeInputSections into a single MergeSyntheticSection. From this 2556 // point onwards InputSectionDescription::sections should be used instead of 2557 // sectionBases. 2558 for (SectionCommand *cmd : script->sectionCommands) 2559 if (auto *sec = dyn_cast<OutputSection>(cmd)) 2560 sec->finalizeInputSections(); 2561 llvm::erase_if(inputSections, [](InputSectionBase *s) { 2562 return isa<MergeInputSection>(s); 2563 }); 2564 } 2565 2566 // Two input sections with different output sections should not be folded. 2567 // ICF runs after processSectionCommands() so that we know the output sections. 2568 if (config->icf != ICFLevel::None) { 2569 findKeepUniqueSections<ELFT>(args); 2570 doIcf<ELFT>(); 2571 } 2572 2573 // Read the callgraph now that we know what was gced or icfed 2574 if (config->callGraphProfileSort) { 2575 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 2576 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 2577 readCallGraph(*buffer); 2578 readCallGraphsFromObjectFiles<ELFT>(); 2579 } 2580 2581 // Write the result to the file. 2582 writeResult<ELFT>(); 2583 } 2584