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