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