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