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