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