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