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