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