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