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