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