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