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