1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The driver drives the entire linking process. It is responsible for 11 // parsing command line options and doing whatever it is instructed to do. 12 // 13 // One notable thing in the LLD's driver when compared to other linkers is 14 // that the LLD's driver is agnostic on the host operating system. 15 // Other linkers usually have implicit default values (such as a dynamic 16 // linker path or library paths) for each host OS. 17 // 18 // I don't think implicit default values are useful because they are 19 // usually explicitly specified by the compiler driver. They can even 20 // be harmful when you are doing cross-linking. Therefore, in LLD, we 21 // simply trust the compiler driver to pass all required options and 22 // don't try to make effort on our side. 23 // 24 //===----------------------------------------------------------------------===// 25 26 #include "Driver.h" 27 #include "Config.h" 28 #include "Filesystem.h" 29 #include "ICF.h" 30 #include "InputFiles.h" 31 #include "InputSection.h" 32 #include "LinkerScript.h" 33 #include "MarkLive.h" 34 #include "OutputSections.h" 35 #include "ScriptParser.h" 36 #include "SymbolTable.h" 37 #include "Symbols.h" 38 #include "SyntheticSections.h" 39 #include "Target.h" 40 #include "Writer.h" 41 #include "lld/Common/Args.h" 42 #include "lld/Common/Driver.h" 43 #include "lld/Common/ErrorHandler.h" 44 #include "lld/Common/Memory.h" 45 #include "lld/Common/Strings.h" 46 #include "lld/Common/TargetOptionsCommandFlags.h" 47 #include "lld/Common/Threads.h" 48 #include "lld/Common/Version.h" 49 #include "llvm/ADT/SetVector.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/ADT/StringSwitch.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Compression.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 66 using namespace lld; 67 using namespace lld::elf; 68 69 Configuration *elf::Config; 70 LinkerDriver *elf::Driver; 71 72 static void setConfigs(opt::InputArgList &Args); 73 74 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly, 75 raw_ostream &Error) { 76 errorHandler().LogName = Args[0]; 77 errorHandler().ErrorLimitExceededMsg = 78 "too many errors emitted, stopping now (use " 79 "-error-limit=0 to see all errors)"; 80 errorHandler().ErrorOS = &Error; 81 errorHandler().ExitEarly = CanExitEarly; 82 errorHandler().ColorDiagnostics = Error.has_colors(); 83 84 InputSections.clear(); 85 OutputSections.clear(); 86 Tar = nullptr; 87 BinaryFiles.clear(); 88 BitcodeFiles.clear(); 89 ObjectFiles.clear(); 90 SharedFiles.clear(); 91 92 Config = make<Configuration>(); 93 Driver = make<LinkerDriver>(); 94 Script = make<LinkerScript>(); 95 Symtab = make<SymbolTable>(); 96 Config->ProgName = Args[0]; 97 98 Driver->main(Args); 99 100 // Exit immediately if we don't need to return to the caller. 101 // This saves time because the overhead of calling destructors 102 // for all globally-allocated objects is not negligible. 103 if (CanExitEarly) 104 exitLld(errorCount() ? 1 : 0); 105 106 freeArena(); 107 return !errorCount(); 108 } 109 110 // Parses a linker -m option. 111 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) { 112 uint8_t OSABI = 0; 113 StringRef S = Emul; 114 if (S.endswith("_fbsd")) { 115 S = S.drop_back(5); 116 OSABI = ELFOSABI_FREEBSD; 117 } 118 119 std::pair<ELFKind, uint16_t> Ret = 120 StringSwitch<std::pair<ELFKind, uint16_t>>(S) 121 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec", 122 {ELF64LEKind, EM_AARCH64}) 123 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 124 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 125 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 126 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 127 .Case("elf32ppc", {ELF32BEKind, EM_PPC}) 128 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 129 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 130 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 131 .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 132 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 133 .Case("elf_i386", {ELF32LEKind, EM_386}) 134 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 135 .Default({ELFNoneKind, EM_NONE}); 136 137 if (Ret.first == ELFNoneKind) 138 error("unknown emulation: " + Emul); 139 return std::make_tuple(Ret.first, Ret.second, OSABI); 140 } 141 142 // Returns slices of MB by parsing MB as an archive file. 143 // Each slice consists of a member file in the archive. 144 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 145 MemoryBufferRef MB) { 146 std::unique_ptr<Archive> File = 147 CHECK(Archive::create(MB), 148 MB.getBufferIdentifier() + ": failed to parse archive"); 149 150 std::vector<std::pair<MemoryBufferRef, uint64_t>> V; 151 Error Err = Error::success(); 152 bool AddToTar = File->isThin() && Tar; 153 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 154 Archive::Child C = 155 CHECK(COrErr, MB.getBufferIdentifier() + 156 ": could not get the child of the archive"); 157 MemoryBufferRef MBRef = 158 CHECK(C.getMemoryBufferRef(), 159 MB.getBufferIdentifier() + 160 ": could not get the buffer for a child of the archive"); 161 if (AddToTar) 162 Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer()); 163 V.push_back(std::make_pair(MBRef, C.getChildOffset())); 164 } 165 if (Err) 166 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " + 167 toString(std::move(Err))); 168 169 // Take ownership of memory buffers created for members of thin archives. 170 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers()) 171 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); 172 173 return V; 174 } 175 176 // Opens a file and create a file object. Path has to be resolved already. 177 void LinkerDriver::addFile(StringRef Path, bool WithLOption) { 178 using namespace sys::fs; 179 180 Optional<MemoryBufferRef> Buffer = readFile(Path); 181 if (!Buffer.hasValue()) 182 return; 183 MemoryBufferRef MBRef = *Buffer; 184 185 if (InBinary) { 186 Files.push_back(make<BinaryFile>(MBRef)); 187 return; 188 } 189 190 switch (identify_magic(MBRef.getBuffer())) { 191 case file_magic::unknown: 192 readLinkerScript(MBRef); 193 return; 194 case file_magic::archive: { 195 // Handle -whole-archive. 196 if (InWholeArchive) { 197 for (const auto &P : getArchiveMembers(MBRef)) 198 Files.push_back(createObjectFile(P.first, Path, P.second)); 199 return; 200 } 201 202 std::unique_ptr<Archive> File = 203 CHECK(Archive::create(MBRef), Path + ": failed to parse archive"); 204 205 // If an archive file has no symbol table, it is likely that a user 206 // is attempting LTO and using a default ar command that doesn't 207 // understand the LLVM bitcode file. It is a pretty common error, so 208 // we'll handle it as if it had a symbol table. 209 if (!File->isEmpty() && !File->hasSymbolTable()) { 210 for (const auto &P : getArchiveMembers(MBRef)) 211 Files.push_back(make<LazyObjFile>(P.first, Path, P.second)); 212 return; 213 } 214 215 // Handle the regular case. 216 Files.push_back(make<ArchiveFile>(std::move(File))); 217 return; 218 } 219 case file_magic::elf_shared_object: 220 if (Config->Relocatable) { 221 error("attempted static link of dynamic object " + Path); 222 return; 223 } 224 225 // DSOs usually have DT_SONAME tags in their ELF headers, and the 226 // sonames are used to identify DSOs. But if they are missing, 227 // they are identified by filenames. We don't know whether the new 228 // file has a DT_SONAME or not because we haven't parsed it yet. 229 // Here, we set the default soname for the file because we might 230 // need it later. 231 // 232 // If a file was specified by -lfoo, the directory part is not 233 // significant, as a user did not specify it. This behavior is 234 // compatible with GNU. 235 Files.push_back( 236 createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path)); 237 return; 238 case file_magic::bitcode: 239 case file_magic::elf_relocatable: 240 if (InLib) 241 Files.push_back(make<LazyObjFile>(MBRef, "", 0)); 242 else 243 Files.push_back(createObjectFile(MBRef)); 244 break; 245 default: 246 error(Path + ": unknown file type"); 247 } 248 } 249 250 // Add a given library by searching it from input search paths. 251 void LinkerDriver::addLibrary(StringRef Name) { 252 if (Optional<std::string> Path = searchLibrary(Name)) 253 addFile(*Path, /*WithLOption=*/true); 254 else 255 error("unable to find library -l" + Name); 256 } 257 258 // This function is called on startup. We need this for LTO since 259 // LTO calls LLVM functions to compile bitcode files to native code. 260 // Technically this can be delayed until we read bitcode files, but 261 // we don't bother to do lazily because the initialization is fast. 262 static void initLLVM() { 263 InitializeAllTargets(); 264 InitializeAllTargetMCs(); 265 InitializeAllAsmPrinters(); 266 InitializeAllAsmParsers(); 267 } 268 269 // Some command line options or some combinations of them are not allowed. 270 // This function checks for such errors. 271 static void checkOptions(opt::InputArgList &Args) { 272 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 273 // table which is a relatively new feature. 274 if (Config->EMachine == EM_MIPS && Config->GnuHash) 275 error("the .gnu.hash section is not compatible with the MIPS target."); 276 277 if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64) 278 error("--fix-cortex-a53-843419 is only supported on AArch64 targets."); 279 280 if (Config->Pie && Config->Shared) 281 error("-shared and -pie may not be used together"); 282 283 if (!Config->Shared && !Config->FilterList.empty()) 284 error("-F may not be used without -shared"); 285 286 if (!Config->Shared && !Config->AuxiliaryList.empty()) 287 error("-f may not be used without -shared"); 288 289 if (!Config->Relocatable && !Config->DefineCommon) 290 error("-no-define-common not supported in non relocatable output"); 291 292 if (Config->Relocatable) { 293 if (Config->Shared) 294 error("-r and -shared may not be used together"); 295 if (Config->GcSections) 296 error("-r and --gc-sections may not be used together"); 297 if (Config->ICF) 298 error("-r and --icf may not be used together"); 299 if (Config->Pie) 300 error("-r and -pie may not be used together"); 301 } 302 } 303 304 static const char *getReproduceOption(opt::InputArgList &Args) { 305 if (auto *Arg = Args.getLastArg(OPT_reproduce)) 306 return Arg->getValue(); 307 return getenv("LLD_REPRODUCE"); 308 } 309 310 static bool hasZOption(opt::InputArgList &Args, StringRef Key) { 311 for (auto *Arg : Args.filtered(OPT_z)) 312 if (Key == Arg->getValue()) 313 return true; 314 return false; 315 } 316 317 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2, 318 bool Default) { 319 for (auto *Arg : Args.filtered_reverse(OPT_z)) { 320 if (K1 == Arg->getValue()) 321 return true; 322 if (K2 == Arg->getValue()) 323 return false; 324 } 325 return Default; 326 } 327 328 static bool isKnown(StringRef S) { 329 return S == "combreloc" || S == "copyreloc" || S == "defs" || 330 S == "execstack" || S == "hazardplt" || S == "initfirst" || 331 S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" || 332 S == "nocombreloc" || S == "nocopyreloc" || S == "nodelete" || 333 S == "nodlopen" || S == "noexecstack" || 334 S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" || 335 S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" || 336 S == "rodynamic" || S == "text" || S == "wxneeded" || 337 S.startswith("max-page-size=") || S.startswith("stack-size="); 338 } 339 340 // Report an error for an unknown -z option. 341 static void checkZOptions(opt::InputArgList &Args) { 342 for (auto *Arg : Args.filtered(OPT_z)) 343 if (!isKnown(Arg->getValue())) 344 error("unknown -z value: " + StringRef(Arg->getValue())); 345 } 346 347 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) { 348 ELFOptTable Parser; 349 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1)); 350 351 // Interpret this flag early because error() depends on them. 352 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20); 353 354 // Handle -help 355 if (Args.hasArg(OPT_help)) { 356 printHelp(); 357 return; 358 } 359 360 // Handle -v or -version. 361 // 362 // A note about "compatible with GNU linkers" message: this is a hack for 363 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and 364 // still the newest version in March 2017) or earlier to recognize LLD as 365 // a GNU compatible linker. As long as an output for the -v option 366 // contains "GNU" or "with BFD", they recognize us as GNU-compatible. 367 // 368 // This is somewhat ugly hack, but in reality, we had no choice other 369 // than doing this. Considering the very long release cycle of Libtool, 370 // it is not easy to improve it to recognize LLD as a GNU compatible 371 // linker in a timely manner. Even if we can make it, there are still a 372 // lot of "configure" scripts out there that are generated by old version 373 // of Libtool. We cannot convince every software developer to migrate to 374 // the latest version and re-generate scripts. So we have this hack. 375 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version)) 376 message(getLLDVersion() + " (compatible with GNU linkers)"); 377 378 // The behavior of -v or --version is a bit strange, but this is 379 // needed for compatibility with GNU linkers. 380 if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT)) 381 return; 382 if (Args.hasArg(OPT_version)) 383 return; 384 385 if (const char *Path = getReproduceOption(Args)) { 386 // Note that --reproduce is a debug option so you can ignore it 387 // if you are trying to understand the whole picture of the code. 388 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 389 TarWriter::create(Path, path::stem(Path)); 390 if (ErrOrWriter) { 391 Tar = ErrOrWriter->get(); 392 Tar->append("response.txt", createResponseFile(Args)); 393 Tar->append("version.txt", getLLDVersion() + "\n"); 394 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter)); 395 } else { 396 error(Twine("--reproduce: failed to open ") + Path + ": " + 397 toString(ErrOrWriter.takeError())); 398 } 399 } 400 401 readConfigs(Args); 402 checkZOptions(Args); 403 initLLVM(); 404 createFiles(Args); 405 if (errorCount()) 406 return; 407 408 inferMachineType(); 409 setConfigs(Args); 410 checkOptions(Args); 411 if (errorCount()) 412 return; 413 414 switch (Config->EKind) { 415 case ELF32LEKind: 416 link<ELF32LE>(Args); 417 return; 418 case ELF32BEKind: 419 link<ELF32BE>(Args); 420 return; 421 case ELF64LEKind: 422 link<ELF64LE>(Args); 423 return; 424 case ELF64BEKind: 425 link<ELF64BE>(Args); 426 return; 427 default: 428 llvm_unreachable("unknown Config->EKind"); 429 } 430 } 431 432 static std::string getRpath(opt::InputArgList &Args) { 433 std::vector<StringRef> V = args::getStrings(Args, OPT_rpath); 434 return llvm::join(V.begin(), V.end(), ":"); 435 } 436 437 // Determines what we should do if there are remaining unresolved 438 // symbols after the name resolution. 439 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) { 440 if (Args.hasArg(OPT_relocatable)) 441 return UnresolvedPolicy::IgnoreAll; 442 443 UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols, 444 OPT_warn_unresolved_symbols, true) 445 ? UnresolvedPolicy::ReportError 446 : UnresolvedPolicy::Warn; 447 448 // Process the last of -unresolved-symbols, -no-undefined or -z defs. 449 for (auto *Arg : llvm::reverse(Args)) { 450 switch (Arg->getOption().getID()) { 451 case OPT_unresolved_symbols: { 452 StringRef S = Arg->getValue(); 453 if (S == "ignore-all" || S == "ignore-in-object-files") 454 return UnresolvedPolicy::Ignore; 455 if (S == "ignore-in-shared-libs" || S == "report-all") 456 return ErrorOrWarn; 457 error("unknown --unresolved-symbols value: " + S); 458 continue; 459 } 460 case OPT_no_undefined: 461 return ErrorOrWarn; 462 case OPT_z: 463 if (StringRef(Arg->getValue()) == "defs") 464 return ErrorOrWarn; 465 continue; 466 } 467 } 468 469 // -shared implies -unresolved-symbols=ignore-all because missing 470 // symbols are likely to be resolved at runtime using other DSOs. 471 if (Config->Shared) 472 return UnresolvedPolicy::Ignore; 473 return ErrorOrWarn; 474 } 475 476 static Target2Policy getTarget2(opt::InputArgList &Args) { 477 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel"); 478 if (S == "rel") 479 return Target2Policy::Rel; 480 if (S == "abs") 481 return Target2Policy::Abs; 482 if (S == "got-rel") 483 return Target2Policy::GotRel; 484 error("unknown --target2 option: " + S); 485 return Target2Policy::GotRel; 486 } 487 488 static bool isOutputFormatBinary(opt::InputArgList &Args) { 489 if (auto *Arg = Args.getLastArg(OPT_oformat)) { 490 StringRef S = Arg->getValue(); 491 if (S == "binary") 492 return true; 493 error("unknown --oformat value: " + S); 494 } 495 return false; 496 } 497 498 static DiscardPolicy getDiscard(opt::InputArgList &Args) { 499 if (Args.hasArg(OPT_relocatable)) 500 return DiscardPolicy::None; 501 502 auto *Arg = 503 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 504 if (!Arg) 505 return DiscardPolicy::Default; 506 if (Arg->getOption().getID() == OPT_discard_all) 507 return DiscardPolicy::All; 508 if (Arg->getOption().getID() == OPT_discard_locals) 509 return DiscardPolicy::Locals; 510 return DiscardPolicy::None; 511 } 512 513 static StringRef getDynamicLinker(opt::InputArgList &Args) { 514 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 515 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker) 516 return ""; 517 return Arg->getValue(); 518 } 519 520 static StripPolicy getStrip(opt::InputArgList &Args) { 521 if (Args.hasArg(OPT_relocatable)) 522 return StripPolicy::None; 523 524 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug); 525 if (!Arg) 526 return StripPolicy::None; 527 if (Arg->getOption().getID() == OPT_strip_all) 528 return StripPolicy::All; 529 return StripPolicy::Debug; 530 } 531 532 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) { 533 uint64_t VA = 0; 534 if (S.startswith("0x")) 535 S = S.drop_front(2); 536 if (!to_integer(S, VA, 16)) 537 error("invalid argument: " + toString(Arg)); 538 return VA; 539 } 540 541 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) { 542 StringMap<uint64_t> Ret; 543 for (auto *Arg : Args.filtered(OPT_section_start)) { 544 StringRef Name; 545 StringRef Addr; 546 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('='); 547 Ret[Name] = parseSectionAddress(Addr, *Arg); 548 } 549 550 if (auto *Arg = Args.getLastArg(OPT_Ttext)) 551 Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg); 552 if (auto *Arg = Args.getLastArg(OPT_Tdata)) 553 Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg); 554 if (auto *Arg = Args.getLastArg(OPT_Tbss)) 555 Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg); 556 return Ret; 557 } 558 559 static SortSectionPolicy getSortSection(opt::InputArgList &Args) { 560 StringRef S = Args.getLastArgValue(OPT_sort_section); 561 if (S == "alignment") 562 return SortSectionPolicy::Alignment; 563 if (S == "name") 564 return SortSectionPolicy::Name; 565 if (!S.empty()) 566 error("unknown --sort-section rule: " + S); 567 return SortSectionPolicy::Default; 568 } 569 570 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) { 571 StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place"); 572 if (S == "warn") 573 return OrphanHandlingPolicy::Warn; 574 if (S == "error") 575 return OrphanHandlingPolicy::Error; 576 if (S != "place") 577 error("unknown --orphan-handling mode: " + S); 578 return OrphanHandlingPolicy::Place; 579 } 580 581 // Parse --build-id or --build-id=<style>. We handle "tree" as a 582 // synonym for "sha1" because all our hash functions including 583 // -build-id=sha1 are actually tree hashes for performance reasons. 584 static std::pair<BuildIdKind, std::vector<uint8_t>> 585 getBuildId(opt::InputArgList &Args) { 586 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq); 587 if (!Arg) 588 return {BuildIdKind::None, {}}; 589 590 if (Arg->getOption().getID() == OPT_build_id) 591 return {BuildIdKind::Fast, {}}; 592 593 StringRef S = Arg->getValue(); 594 if (S == "fast") 595 return {BuildIdKind::Fast, {}}; 596 if (S == "md5") 597 return {BuildIdKind::Md5, {}}; 598 if (S == "sha1" || S == "tree") 599 return {BuildIdKind::Sha1, {}}; 600 if (S == "uuid") 601 return {BuildIdKind::Uuid, {}}; 602 if (S.startswith("0x")) 603 return {BuildIdKind::Hexstring, parseHex(S.substr(2))}; 604 605 if (S != "none") 606 error("unknown --build-id style: " + S); 607 return {BuildIdKind::None, {}}; 608 } 609 610 static void readCallGraph(MemoryBufferRef MB) { 611 // Build a map from symbol name to section 612 DenseMap<StringRef, const Symbol *> SymbolNameToSymbol; 613 for (InputFile *File : ObjectFiles) 614 for (Symbol *Sym : File->getSymbols()) 615 SymbolNameToSymbol[Sym->getName()] = Sym; 616 617 for (StringRef L : args::getLines(MB)) { 618 SmallVector<StringRef, 3> Fields; 619 L.split(Fields, ' '); 620 if (Fields.size() != 3) 621 fatal("parse error"); 622 uint64_t Count; 623 if (!to_integer(Fields[2], Count)) 624 fatal("parse error"); 625 const Symbol *FromSym = SymbolNameToSymbol.lookup(Fields[0]); 626 const Symbol *ToSym = SymbolNameToSymbol.lookup(Fields[1]); 627 if (Config->WarnSymbolOrdering) { 628 if (!FromSym) 629 warn("call graph file: no such symbol: " + Fields[0]); 630 if (!ToSym) 631 warn("call graph file: no such symbol: " + Fields[1]); 632 } 633 if (!FromSym || !ToSym || Count == 0) 634 continue; 635 warnUnorderableSymbol(FromSym); 636 warnUnorderableSymbol(ToSym); 637 const Defined *FromSymD = dyn_cast<Defined>(FromSym); 638 const Defined *ToSymD = dyn_cast<Defined>(ToSym); 639 if (!FromSymD || !ToSymD) 640 continue; 641 const auto *FromSB = dyn_cast_or_null<InputSectionBase>(FromSymD->Section); 642 const auto *ToSB = dyn_cast_or_null<InputSectionBase>(ToSymD->Section); 643 if (!FromSB || !ToSB) 644 continue; 645 Config->CallGraphProfile[std::make_pair(FromSB, ToSB)] += Count; 646 } 647 } 648 649 static bool getCompressDebugSections(opt::InputArgList &Args) { 650 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none"); 651 if (S == "none") 652 return false; 653 if (S != "zlib") 654 error("unknown --compress-debug-sections value: " + S); 655 if (!zlib::isAvailable()) 656 error("--compress-debug-sections: zlib is not available"); 657 return true; 658 } 659 660 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args, 661 unsigned Id) { 662 auto *Arg = Args.getLastArg(Id); 663 if (!Arg) 664 return {"", ""}; 665 666 StringRef S = Arg->getValue(); 667 std::pair<StringRef, StringRef> Ret = S.split(';'); 668 if (Ret.second.empty()) 669 error(Arg->getSpelling() + " expects 'old;new' format, but got " + S); 670 return Ret; 671 } 672 673 // Parse the symbol ordering file and warn for any duplicate entries. 674 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) { 675 SetVector<StringRef> Names; 676 for (StringRef S : args::getLines(MB)) 677 if (!Names.insert(S) && Config->WarnSymbolOrdering) 678 warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S); 679 680 return Names.takeVector(); 681 } 682 683 static void parseClangOption(StringRef Opt, const Twine &Msg) { 684 std::string Err; 685 raw_string_ostream OS(Err); 686 687 const char *Argv[] = {Config->ProgName.data(), Opt.data()}; 688 if (cl::ParseCommandLineOptions(2, Argv, "", &OS)) 689 return; 690 OS.flush(); 691 error(Msg + ": " + StringRef(Err).trim()); 692 } 693 694 // Initializes Config members by the command line options. 695 void LinkerDriver::readConfigs(opt::InputArgList &Args) { 696 errorHandler().Verbose = Args.hasArg(OPT_verbose); 697 errorHandler().FatalWarnings = 698 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 699 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true); 700 701 Config->AllowMultipleDefinition = 702 Args.hasFlag(OPT_allow_multiple_definition, 703 OPT_no_allow_multiple_definition, false) || 704 hasZOption(Args, "muldefs"); 705 Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary); 706 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic); 707 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions); 708 Config->CheckSections = 709 Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 710 Config->Chroot = Args.getLastArgValue(OPT_chroot); 711 Config->CompressDebugSections = getCompressDebugSections(Args); 712 Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false); 713 Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common, 714 !Args.hasArg(OPT_relocatable)); 715 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true); 716 Config->DisableVerify = Args.hasArg(OPT_disable_verify); 717 Config->Discard = getDiscard(Args); 718 Config->DynamicLinker = getDynamicLinker(Args); 719 Config->EhFrameHdr = 720 Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 721 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs); 722 Config->EnableNewDtags = 723 Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 724 Config->Entry = Args.getLastArgValue(OPT_entry); 725 Config->ExportDynamic = 726 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 727 Config->FilterList = args::getStrings(Args, OPT_filter); 728 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini"); 729 Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419); 730 Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 731 Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 732 Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 733 Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false); 734 Config->IgnoreDataAddressEquality = 735 Args.hasArg(OPT_ignore_data_address_equality); 736 Config->IgnoreFunctionAddressEquality = 737 Args.hasArg(OPT_ignore_function_address_equality); 738 Config->Init = Args.getLastArgValue(OPT_init, "_init"); 739 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline); 740 Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager); 741 Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager); 742 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes); 743 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2); 744 Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq); 745 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1); 746 Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile); 747 Config->MapFile = Args.getLastArgValue(OPT_Map); 748 Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0); 749 Config->MergeArmExidx = 750 Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 751 Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec); 752 Config->Nostdlib = Args.hasArg(OPT_nostdlib); 753 Config->OFormatBinary = isOutputFormatBinary(Args); 754 Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false); 755 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename); 756 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness); 757 Config->Optimize = args::getInteger(Args, OPT_O, 1); 758 Config->OrphanHandling = getOrphanHandling(Args); 759 Config->OutputFile = Args.getLastArgValue(OPT_o); 760 Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false); 761 Config->PrintIcfSections = 762 Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 763 Config->PrintGcSections = 764 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 765 Config->Rpath = getRpath(Args); 766 Config->Relocatable = Args.hasArg(OPT_relocatable); 767 Config->SaveTemps = Args.hasArg(OPT_save_temps); 768 Config->SearchPaths = args::getStrings(Args, OPT_library_path); 769 Config->SectionStartMap = getSectionStartMap(Args); 770 Config->Shared = Args.hasArg(OPT_shared); 771 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment); 772 Config->SoName = Args.getLastArgValue(OPT_soname); 773 Config->SortSection = getSortSection(Args); 774 Config->Strip = getStrip(Args); 775 Config->Sysroot = Args.getLastArgValue(OPT_sysroot); 776 Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 777 Config->Target2 = getTarget2(Args); 778 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir); 779 Config->ThinLTOCachePolicy = CHECK( 780 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)), 781 "--thinlto-cache-policy: invalid cache policy"); 782 Config->ThinLTOEmitImportsFiles = 783 Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files); 784 Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) || 785 Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq); 786 Config->ThinLTOIndexOnlyArg = 787 Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq); 788 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u); 789 Config->ThinLTOObjectSuffixReplace = 790 getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq); 791 Config->ThinLTOPrefixReplace = 792 getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq); 793 Config->Trace = Args.hasArg(OPT_trace); 794 Config->Undefined = args::getStrings(Args, OPT_undefined); 795 Config->UndefinedVersion = 796 Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 797 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args); 798 Config->WarnBackrefs = 799 Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 800 Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 801 Config->WarnSymbolOrdering = 802 Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 803 Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true); 804 Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true); 805 Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false); 806 Config->ZHazardplt = hasZOption(Args, "hazardplt"); 807 Config->ZInitfirst = hasZOption(Args, "initfirst"); 808 Config->ZKeepTextSectionPrefix = getZFlag( 809 Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 810 Config->ZNodelete = hasZOption(Args, "nodelete"); 811 Config->ZNodlopen = hasZOption(Args, "nodlopen"); 812 Config->ZNow = getZFlag(Args, "now", "lazy", false); 813 Config->ZOrigin = hasZOption(Args, "origin"); 814 Config->ZRelro = getZFlag(Args, "relro", "norelro", true); 815 Config->ZRetpolineplt = hasZOption(Args, "retpolineplt"); 816 Config->ZRodynamic = hasZOption(Args, "rodynamic"); 817 Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0); 818 Config->ZText = getZFlag(Args, "text", "notext", true); 819 Config->ZWxneeded = hasZOption(Args, "wxneeded"); 820 821 // Parse LTO options. 822 if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq)) 823 parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())), 824 Arg->getSpelling()); 825 826 for (auto *Arg : Args.filtered(OPT_plugin_opt)) 827 parseClangOption(Arg->getValue(), Arg->getSpelling()); 828 829 // Parse -mllvm options. 830 for (auto *Arg : Args.filtered(OPT_mllvm)) 831 parseClangOption(Arg->getValue(), Arg->getSpelling()); 832 833 if (Config->LTOO > 3) 834 error("invalid optimization level for LTO: " + Twine(Config->LTOO)); 835 if (Config->LTOPartitions == 0) 836 error("--lto-partitions: number of threads must be > 0"); 837 if (Config->ThinLTOJobs == 0) 838 error("--thinlto-jobs: number of threads must be > 0"); 839 840 // Parse ELF{32,64}{LE,BE} and CPU type. 841 if (auto *Arg = Args.getLastArg(OPT_m)) { 842 StringRef S = Arg->getValue(); 843 std::tie(Config->EKind, Config->EMachine, Config->OSABI) = 844 parseEmulation(S); 845 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32"); 846 Config->Emulation = S; 847 } 848 849 // Parse -hash-style={sysv,gnu,both}. 850 if (auto *Arg = Args.getLastArg(OPT_hash_style)) { 851 StringRef S = Arg->getValue(); 852 if (S == "sysv") 853 Config->SysvHash = true; 854 else if (S == "gnu") 855 Config->GnuHash = true; 856 else if (S == "both") 857 Config->SysvHash = Config->GnuHash = true; 858 else 859 error("unknown -hash-style: " + S); 860 } 861 862 if (Args.hasArg(OPT_print_map)) 863 Config->MapFile = "-"; 864 865 // --omagic is an option to create old-fashioned executables in which 866 // .text segments are writable. Today, the option is still in use to 867 // create special-purpose programs such as boot loaders. It doesn't 868 // make sense to create PT_GNU_RELRO for such executables. 869 if (Config->Omagic) 870 Config->ZRelro = false; 871 872 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args); 873 874 if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs)) { 875 StringRef S = Arg->getValue(); 876 if (S == "android") 877 Config->AndroidPackDynRelocs = true; 878 else if (S != "none") 879 error("unknown -pack-dyn-relocs format: " + S); 880 } 881 882 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file)) 883 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 884 Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer); 885 886 // If --retain-symbol-file is used, we'll keep only the symbols listed in 887 // the file and discard all others. 888 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) { 889 Config->DefaultSymbolVersion = VER_NDX_LOCAL; 890 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 891 for (StringRef S : args::getLines(*Buffer)) 892 Config->VersionScriptGlobals.push_back( 893 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false}); 894 } 895 896 bool HasExportDynamic = 897 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 898 899 // Parses -dynamic-list and -export-dynamic-symbol. They make some 900 // symbols private. Note that -export-dynamic takes precedence over them 901 // as it says all symbols should be exported. 902 if (!HasExportDynamic) { 903 for (auto *Arg : Args.filtered(OPT_dynamic_list)) 904 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 905 readDynamicList(*Buffer); 906 907 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 908 Config->DynamicList.push_back( 909 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false}); 910 } 911 912 // If --export-dynamic-symbol=foo is given and symbol foo is defined in 913 // an object file in an archive file, that object file should be pulled 914 // out and linked. (It doesn't have to behave like that from technical 915 // point of view, but this is needed for compatibility with GNU.) 916 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 917 Config->Undefined.push_back(Arg->getValue()); 918 919 for (auto *Arg : Args.filtered(OPT_version_script)) 920 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 921 readVersionScript(*Buffer); 922 } 923 924 // Some Config members do not directly correspond to any particular 925 // command line options, but computed based on other Config values. 926 // This function initialize such members. See Config.h for the details 927 // of these values. 928 static void setConfigs(opt::InputArgList &Args) { 929 ELFKind Kind = Config->EKind; 930 uint16_t Machine = Config->EMachine; 931 932 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs); 933 Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind); 934 Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind); 935 Config->Endianness = 936 Config->IsLE ? support::endianness::little : support::endianness::big; 937 Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS); 938 Config->Pic = Config->Pie || Config->Shared; 939 Config->Wordsize = Config->Is64 ? 8 : 4; 940 941 // There is an ILP32 ABI for x86-64, although it's not very popular. 942 // It is called the x32 ABI. 943 bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64); 944 945 // ELF defines two different ways to store relocation addends as shown below: 946 // 947 // Rel: Addends are stored to the location where relocations are applied. 948 // Rela: Addends are stored as part of relocation entry. 949 // 950 // In other words, Rela makes it easy to read addends at the price of extra 951 // 4 or 8 byte for each relocation entry. We don't know why ELF defined two 952 // different mechanisms in the first place, but this is how the spec is 953 // defined. 954 // 955 // You cannot choose which one, Rel or Rela, you want to use. Instead each 956 // ABI defines which one you need to use. The following expression expresses 957 // that. 958 Config->IsRela = 959 (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS; 960 961 // If the output uses REL relocations we must store the dynamic relocation 962 // addends to the output sections. We also store addends for RELA relocations 963 // if --apply-dynamic-relocs is used. 964 // We default to not writing the addends when using RELA relocations since 965 // any standard conforming tool can find it in r_addend. 966 Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs, 967 OPT_no_apply_dynamic_relocs, false) || 968 !Config->IsRela; 969 } 970 971 // Returns a value of "-format" option. 972 static bool getBinaryOption(StringRef S) { 973 if (S == "binary") 974 return true; 975 if (S == "elf" || S == "default") 976 return false; 977 error("unknown -format value: " + S + 978 " (supported formats: elf, default, binary)"); 979 return false; 980 } 981 982 void LinkerDriver::createFiles(opt::InputArgList &Args) { 983 // For --{push,pop}-state. 984 std::vector<std::tuple<bool, bool, bool>> Stack; 985 986 // Iterate over argv to process input files and positional arguments. 987 for (auto *Arg : Args) { 988 switch (Arg->getOption().getUnaliasedOption().getID()) { 989 case OPT_library: 990 addLibrary(Arg->getValue()); 991 break; 992 case OPT_INPUT: 993 addFile(Arg->getValue(), /*WithLOption=*/false); 994 break; 995 case OPT_defsym: { 996 StringRef From; 997 StringRef To; 998 std::tie(From, To) = StringRef(Arg->getValue()).split('='); 999 readDefsym(From, MemoryBufferRef(To, "-defsym")); 1000 break; 1001 } 1002 case OPT_script: 1003 if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) { 1004 if (Optional<MemoryBufferRef> MB = readFile(*Path)) 1005 readLinkerScript(*MB); 1006 break; 1007 } 1008 error(Twine("cannot find linker script ") + Arg->getValue()); 1009 break; 1010 case OPT_as_needed: 1011 Config->AsNeeded = true; 1012 break; 1013 case OPT_format: 1014 InBinary = getBinaryOption(Arg->getValue()); 1015 break; 1016 case OPT_no_as_needed: 1017 Config->AsNeeded = false; 1018 break; 1019 case OPT_Bstatic: 1020 Config->Static = true; 1021 break; 1022 case OPT_Bdynamic: 1023 Config->Static = false; 1024 break; 1025 case OPT_whole_archive: 1026 InWholeArchive = true; 1027 break; 1028 case OPT_no_whole_archive: 1029 InWholeArchive = false; 1030 break; 1031 case OPT_just_symbols: 1032 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) { 1033 Files.push_back(createObjectFile(*MB)); 1034 Files.back()->JustSymbols = true; 1035 } 1036 break; 1037 case OPT_start_group: 1038 if (InputFile::IsInGroup) 1039 error("nested --start-group"); 1040 InputFile::IsInGroup = true; 1041 break; 1042 case OPT_end_group: 1043 if (!InputFile::IsInGroup) 1044 error("stray --end-group"); 1045 InputFile::IsInGroup = false; 1046 ++InputFile::NextGroupId; 1047 break; 1048 case OPT_start_lib: 1049 if (InLib) 1050 error("nested --start-lib"); 1051 if (InputFile::IsInGroup) 1052 error("may not nest --start-lib in --start-group"); 1053 InLib = true; 1054 InputFile::IsInGroup = true; 1055 break; 1056 case OPT_end_lib: 1057 if (!InLib) 1058 error("stray --end-lib"); 1059 InLib = false; 1060 InputFile::IsInGroup = false; 1061 ++InputFile::NextGroupId; 1062 break; 1063 case OPT_push_state: 1064 Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive); 1065 break; 1066 case OPT_pop_state: 1067 if (Stack.empty()) { 1068 error("unbalanced --push-state/--pop-state"); 1069 break; 1070 } 1071 std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back(); 1072 Stack.pop_back(); 1073 break; 1074 } 1075 } 1076 1077 if (Files.empty() && errorCount() == 0) 1078 error("no input files"); 1079 } 1080 1081 // If -m <machine_type> was not given, infer it from object files. 1082 void LinkerDriver::inferMachineType() { 1083 if (Config->EKind != ELFNoneKind) 1084 return; 1085 1086 for (InputFile *F : Files) { 1087 if (F->EKind == ELFNoneKind) 1088 continue; 1089 Config->EKind = F->EKind; 1090 Config->EMachine = F->EMachine; 1091 Config->OSABI = F->OSABI; 1092 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F); 1093 return; 1094 } 1095 error("target emulation unknown: -m or at least one .o file required"); 1096 } 1097 1098 // Parse -z max-page-size=<value>. The default value is defined by 1099 // each target. 1100 static uint64_t getMaxPageSize(opt::InputArgList &Args) { 1101 uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size", 1102 Target->DefaultMaxPageSize); 1103 if (!isPowerOf2_64(Val)) 1104 error("max-page-size: value isn't a power of 2"); 1105 return Val; 1106 } 1107 1108 // Parses -image-base option. 1109 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) { 1110 // Because we are using "Config->MaxPageSize" here, this function has to be 1111 // called after the variable is initialized. 1112 auto *Arg = Args.getLastArg(OPT_image_base); 1113 if (!Arg) 1114 return None; 1115 1116 StringRef S = Arg->getValue(); 1117 uint64_t V; 1118 if (!to_integer(S, V)) { 1119 error("-image-base: number expected, but got " + S); 1120 return 0; 1121 } 1122 if ((V % Config->MaxPageSize) != 0) 1123 warn("-image-base: address isn't multiple of page size: " + S); 1124 return V; 1125 } 1126 1127 // Parses `--exclude-libs=lib,lib,...`. 1128 // The library names may be delimited by commas or colons. 1129 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) { 1130 DenseSet<StringRef> Ret; 1131 for (auto *Arg : Args.filtered(OPT_exclude_libs)) { 1132 StringRef S = Arg->getValue(); 1133 for (;;) { 1134 size_t Pos = S.find_first_of(",:"); 1135 if (Pos == StringRef::npos) 1136 break; 1137 Ret.insert(S.substr(0, Pos)); 1138 S = S.substr(Pos + 1); 1139 } 1140 Ret.insert(S); 1141 } 1142 return Ret; 1143 } 1144 1145 // Handles the -exclude-libs option. If a static library file is specified 1146 // by the -exclude-libs option, all public symbols from the archive become 1147 // private unless otherwise specified by version scripts or something. 1148 // A special library name "ALL" means all archive files. 1149 // 1150 // This is not a popular option, but some programs such as bionic libc use it. 1151 template <class ELFT> 1152 static void excludeLibs(opt::InputArgList &Args) { 1153 DenseSet<StringRef> Libs = getExcludeLibs(Args); 1154 bool All = Libs.count("ALL"); 1155 1156 for (InputFile *File : ObjectFiles) 1157 if (!File->ArchiveName.empty()) 1158 if (All || Libs.count(path::filename(File->ArchiveName))) 1159 for (Symbol *Sym : File->getSymbols()) 1160 if (!Sym->isLocal() && Sym->File == File) 1161 Sym->VersionId = VER_NDX_LOCAL; 1162 } 1163 1164 // Force Sym to be entered in the output. Used for -u or equivalent. 1165 template <class ELFT> static void handleUndefined(StringRef Name) { 1166 Symbol *Sym = Symtab->find(Name); 1167 if (!Sym) 1168 return; 1169 1170 // Since symbol S may not be used inside the program, LTO may 1171 // eliminate it. Mark the symbol as "used" to prevent it. 1172 Sym->IsUsedInRegularObj = true; 1173 1174 if (Sym->isLazy()) 1175 Symtab->fetchLazy<ELFT>(Sym); 1176 } 1177 1178 template <class ELFT> static bool shouldDemote(Symbol &Sym) { 1179 // If all references to a DSO happen to be weak, the DSO is not added to 1180 // DT_NEEDED. If that happens, we need to eliminate shared symbols created 1181 // from the DSO. Otherwise, they become dangling references that point to a 1182 // non-existent DSO. 1183 if (auto *S = dyn_cast<SharedSymbol>(&Sym)) 1184 return !S->getFile<ELFT>().IsNeeded; 1185 1186 // We are done processing archives, so lazy symbols that were used but not 1187 // found can be converted to undefined. We could also just delete the other 1188 // lazy symbols, but that seems to be more work than it is worth. 1189 return Sym.isLazy() && Sym.IsUsedInRegularObj; 1190 } 1191 1192 // Some files, such as .so or files between -{start,end}-lib may be removed 1193 // after their symbols are added to the symbol table. If that happens, we 1194 // need to remove symbols that refer files that no longer exist, so that 1195 // they won't appear in the symbol table of the output file. 1196 // 1197 // We remove symbols by demoting them to undefined symbol. 1198 template <class ELFT> static void demoteSymbols() { 1199 for (Symbol *Sym : Symtab->getSymbols()) { 1200 if (shouldDemote<ELFT>(*Sym)) { 1201 bool Used = Sym->Used; 1202 replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding, 1203 Sym->StOther, Sym->Type); 1204 Sym->Used = Used; 1205 } 1206 } 1207 } 1208 1209 // Record sections that define symbols mentioned in --keep-unique <symbol> 1210 // these sections are inelligible for ICF. 1211 static void findKeepUniqueSections(opt::InputArgList &Args) { 1212 for (auto *Arg : Args.filtered(OPT_keep_unique)) { 1213 StringRef Name = Arg->getValue(); 1214 if (auto *Sym = dyn_cast_or_null<Defined>(Symtab->find(Name))) 1215 Sym->Section->KeepUnique = true; 1216 else 1217 warn("could not find symbol " + Name + " to keep unique"); 1218 } 1219 } 1220 1221 // Do actual linking. Note that when this function is called, 1222 // all linker scripts have already been parsed. 1223 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) { 1224 Target = getTarget(); 1225 1226 Config->MaxPageSize = getMaxPageSize(Args); 1227 Config->ImageBase = getImageBase(Args); 1228 1229 // If a -hash-style option was not given, set to a default value, 1230 // which varies depending on the target. 1231 if (!Args.hasArg(OPT_hash_style)) { 1232 if (Config->EMachine == EM_MIPS) 1233 Config->SysvHash = true; 1234 else 1235 Config->SysvHash = Config->GnuHash = true; 1236 } 1237 1238 // Default output filename is "a.out" by the Unix tradition. 1239 if (Config->OutputFile.empty()) 1240 Config->OutputFile = "a.out"; 1241 1242 // Fail early if the output file or map file is not writable. If a user has a 1243 // long link, e.g. due to a large LTO link, they do not wish to run it and 1244 // find that it failed because there was a mistake in their command-line. 1245 if (auto E = tryCreateFile(Config->OutputFile)) 1246 error("cannot open output file " + Config->OutputFile + ": " + E.message()); 1247 if (auto E = tryCreateFile(Config->MapFile)) 1248 error("cannot open map file " + Config->MapFile + ": " + E.message()); 1249 if (errorCount()) 1250 return; 1251 1252 // Use default entry point name if no name was given via the command 1253 // line nor linker scripts. For some reason, MIPS entry point name is 1254 // different from others. 1255 Config->WarnMissingEntry = 1256 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable)); 1257 if (Config->Entry.empty() && !Config->Relocatable) 1258 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; 1259 1260 // Handle --trace-symbol. 1261 for (auto *Arg : Args.filtered(OPT_trace_symbol)) 1262 Symtab->trace(Arg->getValue()); 1263 1264 // Add all files to the symbol table. This will add almost all 1265 // symbols that we need to the symbol table. 1266 for (InputFile *F : Files) 1267 Symtab->addFile<ELFT>(F); 1268 1269 // Now that we have every file, we can decide if we will need a 1270 // dynamic symbol table. 1271 // We need one if we were asked to export dynamic symbols or if we are 1272 // producing a shared library. 1273 // We also need one if any shared libraries are used and for pie executables 1274 // (probably because the dynamic linker needs it). 1275 Config->HasDynSymTab = 1276 !SharedFiles.empty() || Config->Pic || Config->ExportDynamic; 1277 1278 // Some symbols (such as __ehdr_start) are defined lazily only when there 1279 // are undefined symbols for them, so we add these to trigger that logic. 1280 for (StringRef Sym : Script->ReferencedSymbols) 1281 Symtab->addUndefined<ELFT>(Sym); 1282 1283 // Handle the `--undefined <sym>` options. 1284 for (StringRef S : Config->Undefined) 1285 handleUndefined<ELFT>(S); 1286 1287 // If an entry symbol is in a static archive, pull out that file now 1288 // to complete the symbol table. After this, no new names except a 1289 // few linker-synthesized ones will be added to the symbol table. 1290 handleUndefined<ELFT>(Config->Entry); 1291 1292 // Return if there were name resolution errors. 1293 if (errorCount()) 1294 return; 1295 1296 // Now when we read all script files, we want to finalize order of linker 1297 // script commands, which can be not yet final because of INSERT commands. 1298 Script->processInsertCommands(); 1299 1300 // We want to declare linker script's symbols early, 1301 // so that we can version them. 1302 // They also might be exported if referenced by DSOs. 1303 Script->declareSymbols(); 1304 1305 // Handle the -exclude-libs option. 1306 if (Args.hasArg(OPT_exclude_libs)) 1307 excludeLibs<ELFT>(Args); 1308 1309 // Create ElfHeader early. We need a dummy section in 1310 // addReservedSymbols to mark the created symbols as not absolute. 1311 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC); 1312 Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr); 1313 1314 // We need to create some reserved symbols such as _end. Create them. 1315 if (!Config->Relocatable) 1316 addReservedSymbols(); 1317 1318 // Apply version scripts. 1319 // 1320 // For a relocatable output, version scripts don't make sense, and 1321 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 1322 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 1323 if (!Config->Relocatable) 1324 Symtab->scanVersionScript(); 1325 1326 // Create wrapped symbols for -wrap option. 1327 for (auto *Arg : Args.filtered(OPT_wrap)) 1328 Symtab->addSymbolWrap<ELFT>(Arg->getValue()); 1329 1330 // Do link-time optimization if given files are LLVM bitcode files. 1331 // This compiles bitcode files into real object files. 1332 Symtab->addCombinedLTOObject<ELFT>(); 1333 if (errorCount()) 1334 return; 1335 1336 // If -thinlto-index-only is given, we should create only "index 1337 // files" and not object files. Index file creation is already done 1338 // in addCombinedLTOObject, so we are done if that's the case. 1339 if (Config->ThinLTOIndexOnly) 1340 return; 1341 1342 // Apply symbol renames for -wrap. 1343 Symtab->applySymbolWrap(); 1344 1345 // Now that we have a complete list of input files. 1346 // Beyond this point, no new files are added. 1347 // Aggregate all input sections into one place. 1348 for (InputFile *F : ObjectFiles) 1349 for (InputSectionBase *S : F->getSections()) 1350 if (S && S != &InputSection::Discarded) 1351 InputSections.push_back(S); 1352 for (BinaryFile *F : BinaryFiles) 1353 for (InputSectionBase *S : F->getSections()) 1354 InputSections.push_back(cast<InputSection>(S)); 1355 1356 // We do not want to emit debug sections if --strip-all 1357 // or -strip-debug are given. 1358 if (Config->Strip != StripPolicy::None) 1359 llvm::erase_if(InputSections, [](InputSectionBase *S) { 1360 return S->Name.startswith(".debug") || S->Name.startswith(".zdebug"); 1361 }); 1362 1363 Config->EFlags = Target->calcEFlags(); 1364 1365 if (Config->EMachine == EM_ARM) { 1366 // FIXME: These warnings can be removed when lld only uses these features 1367 // when the input objects have been compiled with an architecture that 1368 // supports them. 1369 if (Config->ARMHasBlx == false) 1370 warn("lld uses blx instruction, no object with architecture supporting " 1371 "feature detected."); 1372 if (Config->ARMJ1J2BranchEncoding == false) 1373 warn("lld uses extended branch encoding, no object with architecture " 1374 "supporting feature detected."); 1375 if (Config->ARMHasMovtMovw == false) 1376 warn("lld may use movt/movw, no object with architecture supporting " 1377 "feature detected."); 1378 } 1379 1380 // This adds a .comment section containing a version string. We have to add it 1381 // before decompressAndMergeSections because the .comment section is a 1382 // mergeable section. 1383 if (!Config->Relocatable) 1384 InputSections.push_back(createCommentSection()); 1385 1386 // Do size optimizations: garbage collection, merging of SHF_MERGE sections 1387 // and identical code folding. 1388 decompressSections(); 1389 splitSections<ELFT>(); 1390 markLive<ELFT>(); 1391 demoteSymbols<ELFT>(); 1392 mergeSections(); 1393 if (Config->ICF) { 1394 findKeepUniqueSections(Args); 1395 doIcf<ELFT>(); 1396 } 1397 1398 // Read the callgraph now that we know what was gced or icfed 1399 if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file)) 1400 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 1401 readCallGraph(*Buffer); 1402 1403 // Write the result to the file. 1404 writeResult<ELFT>(); 1405 } 1406