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