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 #include "Driver.h" 11 #include "Config.h" 12 #include "Error.h" 13 #include "ICF.h" 14 #include "InputFiles.h" 15 #include "InputSection.h" 16 #include "LinkerScript.h" 17 #include "Strings.h" 18 #include "SymbolListFile.h" 19 #include "SymbolTable.h" 20 #include "Target.h" 21 #include "Writer.h" 22 #include "lld/Driver/Driver.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/Support/TargetSelect.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <cstdlib> 28 #include <utility> 29 30 using namespace llvm; 31 using namespace llvm::ELF; 32 using namespace llvm::object; 33 using namespace llvm::sys; 34 35 using namespace lld; 36 using namespace lld::elf; 37 38 Configuration *elf::Config; 39 LinkerDriver *elf::Driver; 40 41 bool elf::link(ArrayRef<const char *> Args, raw_ostream &Error) { 42 HasError = false; 43 ErrorOS = &Error; 44 45 Configuration C; 46 LinkerDriver D; 47 ScriptConfiguration SC; 48 Config = &C; 49 Driver = &D; 50 ScriptConfig = &SC; 51 52 Driver->main(Args); 53 return !HasError; 54 } 55 56 // Parses a linker -m option. 57 static std::pair<ELFKind, uint16_t> parseEmulation(StringRef S) { 58 if (S.endswith("_fbsd")) 59 S = S.drop_back(5); 60 61 std::pair<ELFKind, uint16_t> Ret = 62 StringSwitch<std::pair<ELFKind, uint16_t>>(S) 63 .Case("aarch64linux", {ELF64LEKind, EM_AARCH64}) 64 .Case("armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 65 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 66 .Case("elf32btsmip", {ELF32BEKind, EM_MIPS}) 67 .Case("elf32ltsmip", {ELF32LEKind, EM_MIPS}) 68 .Case("elf32ppc", {ELF32BEKind, EM_PPC}) 69 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 70 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 71 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 72 .Case("elf_i386", {ELF32LEKind, EM_386}) 73 .Case("elf_x86_64", {ELF64LEKind, EM_X86_64}) 74 .Default({ELFNoneKind, EM_NONE}); 75 76 if (Ret.first == ELFNoneKind) { 77 if (S == "i386pe" || S == "i386pep" || S == "thumb2pe") 78 error("Windows targets are not supported on the ELF frontend: " + S); 79 else 80 error("unknown emulation: " + S); 81 } 82 return Ret; 83 } 84 85 // Returns slices of MB by parsing MB as an archive file. 86 // Each slice consists of a member file in the archive. 87 std::vector<MemoryBufferRef> 88 LinkerDriver::getArchiveMembers(MemoryBufferRef MB) { 89 std::unique_ptr<Archive> File = 90 check(Archive::create(MB), "failed to parse archive"); 91 92 std::vector<MemoryBufferRef> V; 93 Error Err; 94 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 95 Archive::Child C = check(COrErr, "could not get the child of the archive " + 96 File->getFileName()); 97 MemoryBufferRef MBRef = 98 check(C.getMemoryBufferRef(), 99 "could not get the buffer for a child of the archive " + 100 File->getFileName()); 101 V.push_back(MBRef); 102 } 103 if (Err) 104 Error(Err); 105 106 // Take ownership of memory buffers created for members of thin archives. 107 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers()) 108 OwningMBs.push_back(std::move(MB)); 109 110 return V; 111 } 112 113 // Opens and parses a file. Path has to be resolved already. 114 // Newly created memory buffers are owned by this driver. 115 void LinkerDriver::addFile(StringRef Path) { 116 using namespace sys::fs; 117 if (Config->Verbose) 118 outs() << Path << "\n"; 119 120 Optional<MemoryBufferRef> Buffer = readFile(Path); 121 if (!Buffer.hasValue()) 122 return; 123 MemoryBufferRef MBRef = *Buffer; 124 125 switch (identify_magic(MBRef.getBuffer())) { 126 case file_magic::unknown: 127 readLinkerScript(MBRef); 128 return; 129 case file_magic::archive: 130 if (WholeArchive) { 131 for (MemoryBufferRef MB : getArchiveMembers(MBRef)) 132 Files.push_back(createObjectFile(MB, Path)); 133 return; 134 } 135 Files.push_back(make_unique<ArchiveFile>(MBRef)); 136 return; 137 case file_magic::elf_shared_object: 138 if (Config->Relocatable) { 139 error("attempted static link of dynamic object " + Path); 140 return; 141 } 142 Files.push_back(createSharedFile(MBRef)); 143 return; 144 default: 145 if (InLib) 146 Files.push_back(make_unique<LazyObjectFile>(MBRef)); 147 else 148 Files.push_back(createObjectFile(MBRef)); 149 } 150 } 151 152 Optional<MemoryBufferRef> LinkerDriver::readFile(StringRef Path) { 153 auto MBOrErr = MemoryBuffer::getFile(Path); 154 if (auto EC = MBOrErr.getError()) { 155 error(EC, "cannot open " + Path); 156 return None; 157 } 158 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr; 159 MemoryBufferRef MBRef = MB->getMemBufferRef(); 160 OwningMBs.push_back(std::move(MB)); // take MB ownership 161 162 if (Cpio) 163 Cpio->append(relativeToRoot(Path), MBRef.getBuffer()); 164 165 return MBRef; 166 } 167 168 // Add a given library by searching it from input search paths. 169 void LinkerDriver::addLibrary(StringRef Name) { 170 std::string Path = searchLibrary(Name); 171 if (Path.empty()) 172 error("unable to find library -l" + Name); 173 else 174 addFile(Path); 175 } 176 177 // This function is called on startup. We need this for LTO since 178 // LTO calls LLVM functions to compile bitcode files to native code. 179 // Technically this can be delayed until we read bitcode files, but 180 // we don't bother to do lazily because the initialization is fast. 181 static void initLLVM(opt::InputArgList &Args) { 182 InitializeAllTargets(); 183 InitializeAllTargetMCs(); 184 InitializeAllAsmPrinters(); 185 InitializeAllAsmParsers(); 186 187 // This is a flag to discard all but GlobalValue names. 188 // We want to enable it by default because it saves memory. 189 // Disable it only when a developer option (-save-temps) is given. 190 Driver->Context.setDiscardValueNames(!Config->SaveTemps); 191 Driver->Context.enableDebugTypeODRUniquing(); 192 193 // Parse and evaluate -mllvm options. 194 std::vector<const char *> V; 195 V.push_back("lld (LLVM option parsing)"); 196 for (auto *Arg : Args.filtered(OPT_mllvm)) 197 V.push_back(Arg->getValue()); 198 cl::ParseCommandLineOptions(V.size(), V.data()); 199 } 200 201 // Some command line options or some combinations of them are not allowed. 202 // This function checks for such errors. 203 static void checkOptions(opt::InputArgList &Args) { 204 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 205 // table which is a relatively new feature. 206 if (Config->EMachine == EM_MIPS && Config->GnuHash) 207 error("the .gnu.hash section is not compatible with the MIPS target."); 208 209 if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty()) 210 error("-e option is not valid for AMDGPU."); 211 212 if (Config->Pie && Config->Shared) 213 error("-shared and -pie may not be used together"); 214 215 if (Config->Relocatable) { 216 if (Config->Shared) 217 error("-r and -shared may not be used together"); 218 if (Config->GcSections) 219 error("-r and --gc-sections may not be used together"); 220 if (Config->ICF) 221 error("-r and --icf may not be used together"); 222 if (Config->Pie) 223 error("-r and -pie may not be used together"); 224 } 225 } 226 227 static StringRef 228 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") { 229 if (auto *Arg = Args.getLastArg(Key)) 230 return Arg->getValue(); 231 return Default; 232 } 233 234 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) { 235 int V = Default; 236 if (auto *Arg = Args.getLastArg(Key)) { 237 StringRef S = Arg->getValue(); 238 if (S.getAsInteger(10, V)) 239 error(Arg->getSpelling() + ": number expected, but got " + S); 240 } 241 return V; 242 } 243 244 static const char *getReproduceOption(opt::InputArgList &Args) { 245 if (auto *Arg = Args.getLastArg(OPT_reproduce)) 246 return Arg->getValue(); 247 return getenv("LLD_REPRODUCE"); 248 } 249 250 static bool hasZOption(opt::InputArgList &Args, StringRef Key) { 251 for (auto *Arg : Args.filtered(OPT_z)) 252 if (Key == Arg->getValue()) 253 return true; 254 return false; 255 } 256 257 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) { 258 ELFOptTable Parser; 259 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1)); 260 if (Args.hasArg(OPT_help)) { 261 printHelp(ArgsArr[0]); 262 return; 263 } 264 if (Args.hasArg(OPT_version)) { 265 outs() << getVersionString(); 266 return; 267 } 268 269 if (const char *Path = getReproduceOption(Args)) { 270 // Note that --reproduce is a debug option so you can ignore it 271 // if you are trying to understand the whole picture of the code. 272 Cpio.reset(CpioFile::create(Path)); 273 if (Cpio) { 274 Cpio->append("response.txt", createResponseFile(Args)); 275 Cpio->append("version.txt", getVersionString()); 276 } 277 } 278 279 readConfigs(Args); 280 initLLVM(Args); 281 createFiles(Args); 282 checkOptions(Args); 283 if (HasError) 284 return; 285 286 switch (Config->EKind) { 287 case ELF32LEKind: 288 link<ELF32LE>(Args); 289 return; 290 case ELF32BEKind: 291 link<ELF32BE>(Args); 292 return; 293 case ELF64LEKind: 294 link<ELF64LE>(Args); 295 return; 296 case ELF64BEKind: 297 link<ELF64BE>(Args); 298 return; 299 default: 300 error("-m or at least a .o file required"); 301 } 302 } 303 304 static UnresolvedPolicy getUnresolvedSymbolOption(opt::InputArgList &Args) { 305 if (Args.hasArg(OPT_noinhibit_exec)) 306 return UnresolvedPolicy::Warn; 307 if (Args.hasArg(OPT_no_undefined) || hasZOption(Args, "defs")) 308 return UnresolvedPolicy::NoUndef; 309 if (Config->Relocatable) 310 return UnresolvedPolicy::Ignore; 311 312 if (auto *Arg = Args.getLastArg(OPT_unresolved_symbols)) { 313 StringRef S = Arg->getValue(); 314 if (S == "ignore-all" || S == "ignore-in-object-files") 315 return UnresolvedPolicy::Ignore; 316 if (S == "ignore-in-shared-libs" || S == "report-all") 317 return UnresolvedPolicy::Error; 318 error("unknown --unresolved-symbols value: " + S); 319 } 320 return UnresolvedPolicy::Error; 321 } 322 323 // Initializes Config members by the command line options. 324 void LinkerDriver::readConfigs(opt::InputArgList &Args) { 325 for (auto *Arg : Args.filtered(OPT_L)) 326 Config->SearchPaths.push_back(Arg->getValue()); 327 328 std::vector<StringRef> RPaths; 329 for (auto *Arg : Args.filtered(OPT_rpath)) 330 RPaths.push_back(Arg->getValue()); 331 if (!RPaths.empty()) 332 Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":"); 333 334 if (auto *Arg = Args.getLastArg(OPT_m)) { 335 // Parse ELF{32,64}{LE,BE} and CPU type. 336 StringRef S = Arg->getValue(); 337 std::tie(Config->EKind, Config->EMachine) = parseEmulation(S); 338 Config->Emulation = S; 339 } 340 341 Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition); 342 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic); 343 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions); 344 Config->Demangle = !Args.hasArg(OPT_no_demangle); 345 Config->DisableVerify = Args.hasArg(OPT_disable_verify); 346 Config->DiscardAll = Args.hasArg(OPT_discard_all); 347 Config->DiscardLocals = Args.hasArg(OPT_discard_locals); 348 Config->DiscardNone = Args.hasArg(OPT_discard_none); 349 Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr); 350 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags); 351 Config->ExportDynamic = Args.hasArg(OPT_export_dynamic); 352 Config->FatalWarnings = Args.hasArg(OPT_fatal_warnings); 353 Config->GcSections = Args.hasArg(OPT_gc_sections); 354 Config->ICF = Args.hasArg(OPT_icf); 355 Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique); 356 Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version); 357 Config->Pie = Args.hasArg(OPT_pie); 358 Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections); 359 Config->Relocatable = Args.hasArg(OPT_relocatable); 360 Config->SaveTemps = Args.hasArg(OPT_save_temps); 361 Config->Shared = Args.hasArg(OPT_shared); 362 Config->StripAll = Args.hasArg(OPT_strip_all); 363 Config->StripDebug = Args.hasArg(OPT_strip_debug); 364 Config->Threads = Args.hasArg(OPT_threads); 365 Config->Trace = Args.hasArg(OPT_trace); 366 Config->Verbose = Args.hasArg(OPT_verbose); 367 Config->WarnCommon = Args.hasArg(OPT_warn_common); 368 369 Config->DynamicLinker = getString(Args, OPT_dynamic_linker); 370 Config->Entry = getString(Args, OPT_entry); 371 Config->Fini = getString(Args, OPT_fini, "_fini"); 372 Config->Init = getString(Args, OPT_init, "_init"); 373 Config->LtoAAPipeline = getString(Args, OPT_lto_aa_pipeline); 374 Config->LtoNewPmPasses = getString(Args, OPT_lto_newpm_passes); 375 Config->OutputFile = getString(Args, OPT_o); 376 Config->SoName = getString(Args, OPT_soname); 377 Config->Sysroot = getString(Args, OPT_sysroot); 378 379 Config->Optimize = getInteger(Args, OPT_O, 1); 380 Config->LtoO = getInteger(Args, OPT_lto_O, 2); 381 if (Config->LtoO > 3) 382 error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O)); 383 Config->LtoJobs = getInteger(Args, OPT_lto_jobs, 1); 384 if (Config->LtoJobs == 0) 385 error("number of threads must be > 0"); 386 387 Config->ZCombreloc = !hasZOption(Args, "nocombreloc"); 388 Config->ZExecStack = hasZOption(Args, "execstack"); 389 Config->ZNodelete = hasZOption(Args, "nodelete"); 390 Config->ZNow = hasZOption(Args, "now"); 391 Config->ZOrigin = hasZOption(Args, "origin"); 392 Config->ZRelro = !hasZOption(Args, "norelro"); 393 394 if (Config->Relocatable) 395 Config->StripAll = false; 396 397 // --strip-all implies --strip-debug. 398 if (Config->StripAll) 399 Config->StripDebug = true; 400 401 // Config->Pic is true if we are generating position-independent code. 402 Config->Pic = Config->Pie || Config->Shared; 403 404 if (auto *Arg = Args.getLastArg(OPT_hash_style)) { 405 StringRef S = Arg->getValue(); 406 if (S == "gnu") { 407 Config->GnuHash = true; 408 Config->SysvHash = false; 409 } else if (S == "both") { 410 Config->GnuHash = true; 411 } else if (S != "sysv") 412 error("unknown hash style: " + S); 413 } 414 415 // Parse --build-id or --build-id=<style>. 416 if (Args.hasArg(OPT_build_id)) 417 Config->BuildId = BuildIdKind::Fnv1; 418 if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) { 419 StringRef S = Arg->getValue(); 420 if (S == "md5") { 421 Config->BuildId = BuildIdKind::Md5; 422 } else if (S == "sha1") { 423 Config->BuildId = BuildIdKind::Sha1; 424 } else if (S == "none") { 425 Config->BuildId = BuildIdKind::None; 426 } else if (S.startswith("0x")) { 427 Config->BuildId = BuildIdKind::Hexstring; 428 Config->BuildIdVector = parseHex(S.substr(2)); 429 } else { 430 error("unknown --build-id style: " + S); 431 } 432 } 433 434 for (auto *Arg : Args.filtered(OPT_undefined)) 435 Config->Undefined.push_back(Arg->getValue()); 436 437 Config->UnresolvedSymbols = getUnresolvedSymbolOption(Args); 438 439 if (auto *Arg = Args.getLastArg(OPT_dynamic_list)) 440 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 441 parseDynamicList(*Buffer); 442 443 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 444 Config->DynamicList.push_back(Arg->getValue()); 445 446 if (auto *Arg = Args.getLastArg(OPT_version_script)) 447 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 448 parseVersionScript(*Buffer); 449 } 450 451 void LinkerDriver::createFiles(opt::InputArgList &Args) { 452 for (auto *Arg : Args) { 453 switch (Arg->getOption().getID()) { 454 case OPT_l: 455 addLibrary(Arg->getValue()); 456 break; 457 case OPT_alias_script_T: 458 case OPT_INPUT: 459 case OPT_script: 460 addFile(Arg->getValue()); 461 break; 462 case OPT_as_needed: 463 Config->AsNeeded = true; 464 break; 465 case OPT_no_as_needed: 466 Config->AsNeeded = false; 467 break; 468 case OPT_Bstatic: 469 Config->Static = true; 470 break; 471 case OPT_Bdynamic: 472 Config->Static = false; 473 break; 474 case OPT_whole_archive: 475 WholeArchive = true; 476 break; 477 case OPT_no_whole_archive: 478 WholeArchive = false; 479 break; 480 case OPT_start_lib: 481 InLib = true; 482 break; 483 case OPT_end_lib: 484 InLib = false; 485 break; 486 } 487 } 488 489 if (Files.empty() && !HasError) 490 error("no input files."); 491 492 // If -m <machine_type> was not given, infer it from object files. 493 if (Config->EKind == ELFNoneKind) { 494 for (std::unique_ptr<InputFile> &F : Files) { 495 if (F->EKind == ELFNoneKind) 496 continue; 497 Config->EKind = F->EKind; 498 Config->EMachine = F->EMachine; 499 break; 500 } 501 } 502 } 503 504 // Do actual linking. Note that when this function is called, 505 // all linker scripts have already been parsed. 506 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) { 507 SymbolTable<ELFT> Symtab; 508 elf::Symtab<ELFT>::X = &Symtab; 509 510 std::unique_ptr<TargetInfo> TI(createTarget()); 511 Target = TI.get(); 512 LinkerScript<ELFT> LS; 513 Script<ELFT>::X = &LS; 514 515 Config->Rela = ELFT::Is64Bits || Config->EMachine == EM_X86_64; 516 Config->Mips64EL = 517 (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind); 518 519 // Add entry symbol. Note that AMDGPU binaries have no entry points. 520 if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable && 521 Config->EMachine != EM_AMDGPU) 522 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; 523 524 // Default output filename is "a.out" by the Unix tradition. 525 if (Config->OutputFile.empty()) 526 Config->OutputFile = "a.out"; 527 528 // Handle --trace-symbol. 529 for (auto *Arg : Args.filtered(OPT_trace_symbol)) 530 Symtab.trace(Arg->getValue()); 531 532 // Set either EntryAddr (if S is a number) or EntrySym (otherwise). 533 if (!Config->Entry.empty()) { 534 StringRef S = Config->Entry; 535 if (S.getAsInteger(0, Config->EntryAddr)) 536 Config->EntrySym = Symtab.addUndefined(S); 537 } 538 539 // Initialize Config->ImageBase. 540 if (auto *Arg = Args.getLastArg(OPT_image_base)) { 541 StringRef S = Arg->getValue(); 542 if (S.getAsInteger(0, Config->ImageBase)) 543 error(Arg->getSpelling() + ": number expected, but got " + S); 544 else if ((Config->ImageBase % Target->PageSize) != 0) 545 warning(Arg->getSpelling() + ": address isn't multiple of page size"); 546 } else { 547 Config->ImageBase = Config->Pic ? 0 : Target->DefaultImageBase; 548 } 549 550 for (std::unique_ptr<InputFile> &F : Files) 551 Symtab.addFile(std::move(F)); 552 if (HasError) 553 return; // There were duplicate symbols or incompatible files 554 555 Symtab.scanUndefinedFlags(); 556 Symtab.scanShlibUndefined(); 557 Symtab.scanDynamicList(); 558 Symtab.scanVersionScript(); 559 Symtab.scanSymbolVersions(); 560 561 Symtab.addCombinedLtoObject(); 562 if (HasError) 563 return; 564 565 for (auto *Arg : Args.filtered(OPT_wrap)) 566 Symtab.wrap(Arg->getValue()); 567 568 // Write the result to the file. 569 if (Config->GcSections) 570 markLive<ELFT>(); 571 if (Config->ICF) 572 doIcf<ELFT>(); 573 574 // MergeInputSection::splitIntoPieces needs to be called before 575 // any call of MergeInputSection::getOffset. Do that. 576 for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F : 577 Symtab.getObjectFiles()) 578 for (InputSectionBase<ELFT> *S : F->getSections()) { 579 if (!S || S == &InputSection<ELFT>::Discarded || !S->Live) 580 continue; 581 if (S->Compressed) 582 S->uncompress(); 583 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S)) 584 MS->splitIntoPieces(); 585 } 586 587 writeResult<ELFT>(&Symtab); 588 } 589