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