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