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