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