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