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