xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision aa8dfe9f)
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/Path.h"
23 #include "llvm/Support/TargetSelect.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <utility>
26 
27 using namespace llvm;
28 using namespace llvm::ELF;
29 using namespace llvm::object;
30 using namespace llvm::sys;
31 
32 using namespace lld;
33 using namespace lld::elf;
34 
35 Configuration *elf::Config;
36 LinkerDriver *elf::Driver;
37 
38 bool elf::link(ArrayRef<const char *> Args, raw_ostream &Error) {
39   HasError = false;
40   ErrorOS = &Error;
41 
42   Configuration C;
43   LinkerDriver D;
44   ScriptConfiguration SC;
45   Config = &C;
46   Driver = &D;
47   ScriptConfig = &SC;
48 
49   Driver->main(Args);
50   return !HasError;
51 }
52 
53 static std::pair<ELFKind, uint16_t> parseEmulation(StringRef S) {
54   if (S.endswith("_fbsd"))
55     S = S.drop_back(5);
56   if (S == "elf32btsmip")
57     return {ELF32BEKind, EM_MIPS};
58   if (S == "elf32ltsmip")
59     return {ELF32LEKind, EM_MIPS};
60   if (S == "elf64btsmip")
61     return {ELF64BEKind, EM_MIPS};
62   if (S == "elf64ltsmip")
63     return {ELF64LEKind, EM_MIPS};
64   if (S == "elf32ppc")
65     return {ELF32BEKind, EM_PPC};
66   if (S == "elf64ppc")
67     return {ELF64BEKind, EM_PPC64};
68   if (S == "elf_i386")
69     return {ELF32LEKind, EM_386};
70   if (S == "elf_x86_64")
71     return {ELF64LEKind, EM_X86_64};
72   if (S == "aarch64linux")
73     return {ELF64LEKind, EM_AARCH64};
74   if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
75     error("Windows targets are not supported on the ELF frontend: " + S);
76   else
77     error("unknown emulation: " + S);
78   return {ELFNoneKind, EM_NONE};
79 }
80 
81 // Returns slices of MB by parsing MB as an archive file.
82 // Each slice consists of a member file in the archive.
83 std::vector<MemoryBufferRef>
84 LinkerDriver::getArchiveMembers(MemoryBufferRef MB) {
85   std::unique_ptr<Archive> File =
86       check(Archive::create(MB), "failed to parse archive");
87 
88   std::vector<MemoryBufferRef> V;
89   for (const ErrorOr<Archive::Child> &COrErr : File->children()) {
90     Archive::Child C = check(COrErr, "could not get the child of the archive " +
91                                          File->getFileName());
92     MemoryBufferRef MBRef =
93         check(C.getMemoryBufferRef(),
94               "could not get the buffer for a child of the archive " +
95                   File->getFileName());
96     V.push_back(MBRef);
97   }
98 
99   // Take ownership of memory buffers created for members of thin archives.
100   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
101     OwningMBs.push_back(std::move(MB));
102 
103   return V;
104 }
105 
106 // Opens and parses a file. Path has to be resolved already.
107 // Newly created memory buffers are owned by this driver.
108 void LinkerDriver::addFile(StringRef Path) {
109   using namespace llvm::sys::fs;
110   if (Config->Verbose)
111     llvm::outs() << Path << "\n";
112   if (!Config->Reproduce.empty())
113     copyFile(Path, concat_paths(Config->Reproduce, Path));
114 
115   Optional<MemoryBufferRef> Buffer = readFile(Path);
116   if (!Buffer.hasValue())
117     return;
118   MemoryBufferRef MBRef = *Buffer;
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 static void logCommandline(ArrayRef<const char *> Args) {
242   if (std::error_code EC = sys::fs::create_directories(
243         Config->Reproduce, /*IgnoreExisting=*/false)) {
244     error(EC, Config->Reproduce + ": can't create directory");
245     return;
246   }
247 
248   SmallString<128> Path;
249   path::append(Path, Config->Reproduce, "invocation.txt");
250   std::error_code EC;
251   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
252   check(EC);
253 
254   OS << Args[0];
255   for (size_t I = 1, E = Args.size(); I < E; ++I)
256     OS << " " << Args[I];
257   OS << "\n";
258 }
259 
260 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
261   ELFOptTable Parser;
262   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
263   if (Args.hasArg(OPT_help)) {
264     printHelp(ArgsArr[0]);
265     return;
266   }
267   if (Args.hasArg(OPT_version)) {
268     printVersion();
269     return;
270   }
271 
272   readConfigs(Args);
273   initLLVM(Args);
274 
275   if (!Config->Reproduce.empty())
276     logCommandline(ArgsArr);
277 
278   createFiles(Args);
279   checkOptions(Args);
280   if (HasError)
281     return;
282 
283   switch (Config->EKind) {
284   case ELF32LEKind:
285     link<ELF32LE>(Args);
286     return;
287   case ELF32BEKind:
288     link<ELF32BE>(Args);
289     return;
290   case ELF64LEKind:
291     link<ELF64LE>(Args);
292     return;
293   case ELF64BEKind:
294     link<ELF64BE>(Args);
295     return;
296   default:
297     error("-m or at least a .o file required");
298   }
299 }
300 
301 // Initializes Config members by the command line options.
302 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
303   for (auto *Arg : Args.filtered(OPT_L))
304     Config->SearchPaths.push_back(Arg->getValue());
305 
306   std::vector<StringRef> RPaths;
307   for (auto *Arg : Args.filtered(OPT_rpath))
308     RPaths.push_back(Arg->getValue());
309   if (!RPaths.empty())
310     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
311 
312   if (auto *Arg = Args.getLastArg(OPT_m)) {
313     // Parse ELF{32,64}{LE,BE} and CPU type.
314     StringRef S = Arg->getValue();
315     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
316     Config->Emulation = S;
317   }
318 
319   if (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind)
320     Config->Mips64EL = true;
321 
322   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
323   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
324   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
325   Config->Demangle = !Args.hasArg(OPT_no_demangle);
326   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
327   Config->DiscardAll = Args.hasArg(OPT_discard_all);
328   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
329   Config->DiscardNone = Args.hasArg(OPT_discard_none);
330   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
331   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
332   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
333   Config->GcSections = Args.hasArg(OPT_gc_sections);
334   Config->ICF = Args.hasArg(OPT_icf);
335   Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
336   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
337   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
338   Config->Pie = Args.hasArg(OPT_pie);
339   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
340   Config->Relocatable = Args.hasArg(OPT_relocatable);
341   Config->SaveTemps = Args.hasArg(OPT_save_temps);
342   Config->Shared = Args.hasArg(OPT_shared);
343   Config->StripAll = Args.hasArg(OPT_strip_all);
344   Config->StripDebug = Args.hasArg(OPT_strip_debug);
345   Config->Threads = Args.hasArg(OPT_threads);
346   Config->Trace = Args.hasArg(OPT_trace);
347   Config->Verbose = Args.hasArg(OPT_verbose);
348   Config->WarnCommon = Args.hasArg(OPT_warn_common);
349 
350   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
351   Config->Entry = getString(Args, OPT_entry);
352   Config->Fini = getString(Args, OPT_fini, "_fini");
353   Config->Init = getString(Args, OPT_init, "_init");
354   Config->OutputFile = getString(Args, OPT_o);
355   Config->Reproduce = getString(Args, OPT_reproduce);
356   Config->SoName = getString(Args, OPT_soname);
357   Config->Sysroot = getString(Args, OPT_sysroot);
358 
359   Config->Optimize = getInteger(Args, OPT_O, 1);
360   Config->LtoO = getInteger(Args, OPT_lto_O, 2);
361   if (Config->LtoO > 3)
362     error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
363   Config->LtoJobs = getInteger(Args, OPT_lto_jobs, 1);
364   if (Config->LtoJobs == 0)
365     error("number of threads must be > 0");
366 
367   Config->ZExecStack = hasZOption(Args, "execstack");
368   Config->ZNodelete = hasZOption(Args, "nodelete");
369   Config->ZNow = hasZOption(Args, "now");
370   Config->ZOrigin = hasZOption(Args, "origin");
371   Config->ZRelro = !hasZOption(Args, "norelro");
372 
373   if (Config->Relocatable)
374     Config->StripAll = false;
375 
376   // --strip-all implies --strip-debug.
377   if (Config->StripAll)
378     Config->StripDebug = true;
379 
380   // Config->Pic is true if we are generating position-independent code.
381   Config->Pic = Config->Pie || Config->Shared;
382 
383   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
384     StringRef S = Arg->getValue();
385     if (S == "gnu") {
386       Config->GnuHash = true;
387       Config->SysvHash = false;
388     } else if (S == "both") {
389       Config->GnuHash = true;
390     } else if (S != "sysv")
391       error("unknown hash style: " + S);
392   }
393 
394   // Parse --build-id or --build-id=<style>.
395   if (Args.hasArg(OPT_build_id))
396     Config->BuildId = BuildIdKind::Fnv1;
397   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
398     StringRef S = Arg->getValue();
399     if (S == "md5") {
400       Config->BuildId = BuildIdKind::Md5;
401     } else if (S == "sha1") {
402       Config->BuildId = BuildIdKind::Sha1;
403     } else
404       error("unknown --build-id style: " + S);
405   }
406 
407   for (auto *Arg : Args.filtered(OPT_undefined))
408     Config->Undefined.push_back(Arg->getValue());
409 
410   if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
411     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
412       parseDynamicList(*Buffer);
413 
414   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
415     Config->DynamicList.push_back(Arg->getValue());
416 
417   if (auto *Arg = Args.getLastArg(OPT_version_script)) {
418     Config->VersionScript = true;
419     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
420       parseVersionScript(*Buffer);
421   }
422 }
423 
424 void LinkerDriver::createFiles(opt::InputArgList &Args) {
425   for (auto *Arg : Args) {
426     switch (Arg->getOption().getID()) {
427     case OPT_l:
428       addLibrary(Arg->getValue());
429       break;
430     case OPT_INPUT:
431     case OPT_script:
432       addFile(Arg->getValue());
433       break;
434     case OPT_as_needed:
435       Config->AsNeeded = true;
436       break;
437     case OPT_no_as_needed:
438       Config->AsNeeded = false;
439       break;
440     case OPT_Bstatic:
441       Config->Static = true;
442       break;
443     case OPT_Bdynamic:
444       Config->Static = false;
445       break;
446     case OPT_whole_archive:
447       WholeArchive = true;
448       break;
449     case OPT_no_whole_archive:
450       WholeArchive = false;
451       break;
452     case OPT_start_lib:
453       InLib = true;
454       break;
455     case OPT_end_lib:
456       InLib = false;
457       break;
458     }
459   }
460 
461   if (Files.empty() && !HasError)
462     error("no input files.");
463 }
464 
465 // Do actual linking. Note that when this function is called,
466 // all linker scripts have already been parsed.
467 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
468   SymbolTable<ELFT> Symtab;
469 
470   std::unique_ptr<TargetInfo> TI(createTarget());
471   Target = TI.get();
472   LinkerScript<ELFT> LS;
473   Script<ELFT>::X = &LS;
474 
475   Config->Rela = ELFT::Is64Bits;
476 
477   // Add entry symbol. Note that AMDGPU binaries have no entry points.
478   if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable &&
479       Config->EMachine != EM_AMDGPU)
480     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
481 
482   // Default output filename is "a.out" by the Unix tradition.
483   if (Config->OutputFile.empty())
484     Config->OutputFile = "a.out";
485 
486   // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
487   if (!Config->Entry.empty()) {
488     StringRef S = Config->Entry;
489     if (S.getAsInteger(0, Config->EntryAddr))
490       Config->EntrySym = Symtab.addUndefined(S)->Backref;
491   }
492 
493   for (std::unique_ptr<InputFile> &F : Files)
494     Symtab.addFile(std::move(F));
495   if (HasError)
496     return; // There were duplicate symbols or incompatible files
497 
498   Symtab.scanUndefinedFlags();
499   Symtab.scanShlibUndefined();
500   Symtab.scanDynamicList();
501   Symtab.scanVersionScript();
502 
503   Symtab.addCombinedLtoObject();
504 
505   for (auto *Arg : Args.filtered(OPT_wrap))
506     Symtab.wrap(Arg->getValue());
507 
508   // Write the result to the file.
509   if (Config->GcSections)
510     markLive<ELFT>(&Symtab);
511   if (Config->ICF)
512     doIcf<ELFT>(&Symtab);
513   writeResult<ELFT>(&Symtab);
514 }
515