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