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