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