1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "InputFiles.h"
15 #include "InputSection.h"
16 #include "LinkerScript.h"
18 #include "SymbolListFile.h"
19 #include "SymbolTable.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"
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::sys;
36 using namespace lld::elf;
38 Configuration *elf::Config;
39 LinkerDriver *elf::Driver;
41 bool elf::link(ArrayRef<const char *> Args, raw_ostream &Error) {
47 ScriptConfiguration SC;
56 // Parses a linker -m option.
57 static std::pair<ELFKind, uint16_t> parseEmulation(StringRef S) {
58 if (S.endswith("_fbsd"))
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});
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);
80 error("unknown emulation: " + S);
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");
92 std::vector<MemoryBufferRef> V;
94 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
95 Archive::Child C = check(COrErr, "could not get the child of the archive " +
97 MemoryBufferRef MBRef =
98 check(C.getMemoryBufferRef(),
99 "could not get the buffer for a child of the archive " +
100 File->getFileName());
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));
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;
118 outs() << Path << "\n";
120 Optional<MemoryBufferRef> Buffer = readFile(Path);
121 if (!Buffer.hasValue())
123 MemoryBufferRef MBRef = *Buffer;
125 switch (identify_magic(MBRef.getBuffer())) {
126 case file_magic::unknown:
127 readLinkerScript(MBRef);
129 case file_magic::archive:
131 for (MemoryBufferRef MB : getArchiveMembers(MBRef))
132 Files.push_back(createObjectFile(MB, Path));
135 Files.push_back(make_unique<ArchiveFile>(MBRef));
137 case file_magic::elf_shared_object:
138 if (Config->Relocatable) {
139 error("attempted static link of dynamic object " + Path);
142 Files.push_back(createSharedFile(MBRef));
146 Files.push_back(make_unique<LazyObjectFile>(MBRef));
148 Files.push_back(createObjectFile(MBRef));
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);
158 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
159 MemoryBufferRef MBRef = MB->getMemBufferRef();
160 OwningMBs.push_back(std::move(MB)); // take MB ownership
163 Cpio->append(relativeToRoot(Path), MBRef.getBuffer());
168 // Add a given library by searching it from input search paths.
169 void LinkerDriver::addLibrary(StringRef Name) {
170 std::string Path = searchLibrary(Name);
172 error("unable to find library -l" + Name);
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();
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();
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());
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.");
209 if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
210 error("-e option is not valid for AMDGPU.");
212 if (Config->Pie && Config->Shared)
213 error("-shared and -pie may not be used together");
215 if (Config->Relocatable) {
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");
221 error("-r and --icf may not be used together");
223 error("-r and -pie may not be used together");
228 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
229 if (auto *Arg = Args.getLastArg(Key))
230 return Arg->getValue();
234 static int getInteger(opt::InputArgList &Args, unsigned Key, int 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);
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");
250 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
251 for (auto *Arg : Args.filtered(OPT_z))
252 if (Key == Arg->getValue())
257 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
259 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
260 if (Args.hasArg(OPT_help)) {
261 printHelp(ArgsArr[0]);
264 if (Args.hasArg(OPT_version)) {
265 outs() << getVersionString();
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));
274 Cpio->append("response.txt", createResponseFile(Args));
275 Cpio->append("version.txt", getVersionString());
286 switch (Config->EKind) {
300 error("-m or at least a .o file required");
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;
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);
320 return UnresolvedPolicy::Error;
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());
328 std::vector<StringRef> RPaths;
329 for (auto *Arg : Args.filtered(OPT_rpath))
330 RPaths.push_back(Arg->getValue());
332 Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
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;
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);
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);
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");
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");
394 if (Config->Relocatable)
395 Config->StripAll = false;
397 // --strip-all implies --strip-debug.
398 if (Config->StripAll)
399 Config->StripDebug = true;
401 // Config->Pic is true if we are generating position-independent code.
402 Config->Pic = Config->Pie || Config->Shared;
404 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
405 StringRef S = Arg->getValue();
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);
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();
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));
430 error("unknown --build-id style: " + S);
434 for (auto *Arg : Args.filtered(OPT_undefined))
435 Config->Undefined.push_back(Arg->getValue());
437 Config->UnresolvedSymbols = getUnresolvedSymbolOption(Args);
439 if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
440 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
441 parseDynamicList(*Buffer);
443 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
444 Config->DynamicList.push_back(Arg->getValue());
446 if (auto *Arg = Args.getLastArg(OPT_version_script))
447 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
448 parseVersionScript(*Buffer);
451 void LinkerDriver::createFiles(opt::InputArgList &Args) {
452 for (auto *Arg : Args) {
453 switch (Arg->getOption().getID()) {
455 addLibrary(Arg->getValue());
457 case OPT_alias_script_T:
460 addFile(Arg->getValue());
463 Config->AsNeeded = true;
465 case OPT_no_as_needed:
466 Config->AsNeeded = false;
469 Config->Static = true;
472 Config->Static = false;
474 case OPT_whole_archive:
477 case OPT_no_whole_archive:
478 WholeArchive = false;
489 if (Files.empty() && !HasError)
490 error("no input files.");
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)
497 Config->EKind = F->EKind;
498 Config->EMachine = F->EMachine;
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;
510 std::unique_ptr<TargetInfo> TI(createTarget());
512 LinkerScript<ELFT> LS;
513 Script<ELFT>::X = &LS;
515 Config->Rela = ELFT::Is64Bits || Config->EMachine == EM_X86_64;
517 (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind);
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";
524 // Default output filename is "a.out" by the Unix tradition.
525 if (Config->OutputFile.empty())
526 Config->OutputFile = "a.out";
528 // Handle --trace-symbol.
529 for (auto *Arg : Args.filtered(OPT_trace_symbol))
530 Symtab.trace(Arg->getValue());
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);
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");
547 Config->ImageBase = Config->Pic ? 0 : Target->DefaultImageBase;
550 for (std::unique_ptr<InputFile> &F : Files)
551 Symtab.addFile(std::move(F));
553 return; // There were duplicate symbols or incompatible files
555 Symtab.scanUndefinedFlags();
556 Symtab.scanShlibUndefined();
557 Symtab.scanDynamicList();
558 Symtab.scanVersionScript();
559 Symtab.scanSymbolVersions();
561 Symtab.addCombinedLtoObject();
565 for (auto *Arg : Args.filtered(OPT_wrap))
566 Symtab.wrap(Arg->getValue());
568 // Write the result to the file.
569 if (Config->GcSections)
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)
583 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
584 MS->splitIntoPieces();
587 writeResult<ELFT>(&Symtab);