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