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