xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision bc32b5cf)
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   // This is a flag to discard all but GlobalValue names.
174   // We want to enable it by default because it saves memory.
175   // Disable it only when a developer option (-save-temps) is given.
176   Driver->Context.setDiscardValueNames(!Config->SaveTemps);
177   Driver->Context.enableDebugTypeODRUniquing();
178 
179   // Parse and evaluate -mllvm options.
180   std::vector<const char *> V;
181   V.push_back("lld (LLVM option parsing)");
182   for (auto *Arg : Args.filtered(OPT_mllvm))
183     V.push_back(Arg->getValue());
184   cl::ParseCommandLineOptions(V.size(), V.data());
185 }
186 
187 // Some command line options or some combinations of them are not allowed.
188 // This function checks for such errors.
189 static void checkOptions(opt::InputArgList &Args) {
190   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
191   // table which is a relatively new feature.
192   if (Config->EMachine == EM_MIPS && Config->GnuHash)
193     error("the .gnu.hash section is not compatible with the MIPS target.");
194 
195   if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
196     error("-e option is not valid for AMDGPU.");
197 
198   if (Config->Pie && Config->Shared)
199     error("-shared and -pie may not be used together");
200 
201   if (Config->Relocatable) {
202     if (Config->Shared)
203       error("-r and -shared may not be used together");
204     if (Config->GcSections)
205       error("-r and --gc-sections may not be used together");
206     if (Config->ICF)
207       error("-r and --icf may not be used together");
208     if (Config->Pie)
209       error("-r and -pie may not be used together");
210   }
211 }
212 
213 static StringRef
214 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
215   if (auto *Arg = Args.getLastArg(Key))
216     return Arg->getValue();
217   return Default;
218 }
219 
220 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
221   int V = Default;
222   if (auto *Arg = Args.getLastArg(Key)) {
223     StringRef S = Arg->getValue();
224     if (S.getAsInteger(10, V))
225       error(Arg->getSpelling() + ": number expected, but got " + S);
226   }
227   return V;
228 }
229 
230 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
231   for (auto *Arg : Args.filtered(OPT_z))
232     if (Key == Arg->getValue())
233       return true;
234   return false;
235 }
236 
237 static void logCommandline(ArrayRef<const char *> Args) {
238   if (std::error_code EC = sys::fs::create_directories(
239         Config->Reproduce, /*IgnoreExisting=*/false)) {
240     error(EC, Config->Reproduce + ": can't create directory");
241     return;
242   }
243 
244   SmallString<128> Path;
245   path::append(Path, Config->Reproduce, "invocation.txt");
246   std::error_code EC;
247   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
248   check(EC);
249 
250   OS << Args[0];
251   for (size_t I = 1, E = Args.size(); I < E; ++I)
252     OS << " " << Args[I];
253   OS << "\n";
254 }
255 
256 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
257   ELFOptTable Parser;
258   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
259   if (Args.hasArg(OPT_help)) {
260     printHelp(ArgsArr[0]);
261     return;
262   }
263   if (Args.hasArg(OPT_version)) {
264     printVersion();
265     return;
266   }
267 
268   readConfigs(Args);
269   initLLVM(Args);
270 
271   if (!Config->Reproduce.empty())
272     logCommandline(ArgsArr);
273 
274   createFiles(Args);
275   checkOptions(Args);
276   if (HasError)
277     return;
278 
279   switch (Config->EKind) {
280   case ELF32LEKind:
281     link<ELF32LE>(Args);
282     return;
283   case ELF32BEKind:
284     link<ELF32BE>(Args);
285     return;
286   case ELF64LEKind:
287     link<ELF64LE>(Args);
288     return;
289   case ELF64BEKind:
290     link<ELF64BE>(Args);
291     return;
292   default:
293     error("-m or at least a .o file required");
294   }
295 }
296 
297 // Initializes Config members by the command line options.
298 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
299   for (auto *Arg : Args.filtered(OPT_L))
300     Config->SearchPaths.push_back(Arg->getValue());
301 
302   std::vector<StringRef> RPaths;
303   for (auto *Arg : Args.filtered(OPT_rpath))
304     RPaths.push_back(Arg->getValue());
305   if (!RPaths.empty())
306     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
307 
308   if (auto *Arg = Args.getLastArg(OPT_m)) {
309     // Parse ELF{32,64}{LE,BE} and CPU type.
310     StringRef S = Arg->getValue();
311     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
312     Config->Emulation = S;
313   }
314 
315   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
316   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
317   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
318   Config->Demangle = !Args.hasArg(OPT_no_demangle);
319   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
320   Config->DiscardAll = Args.hasArg(OPT_discard_all);
321   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
322   Config->DiscardNone = Args.hasArg(OPT_discard_none);
323   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
324   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
325   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
326   Config->GcSections = Args.hasArg(OPT_gc_sections);
327   Config->ICF = Args.hasArg(OPT_icf);
328   Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
329   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
330   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
331   Config->Pie = Args.hasArg(OPT_pie);
332   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
333   Config->Relocatable = Args.hasArg(OPT_relocatable);
334   Config->SaveTemps = Args.hasArg(OPT_save_temps);
335   Config->Shared = Args.hasArg(OPT_shared);
336   Config->StripAll = Args.hasArg(OPT_strip_all);
337   Config->StripDebug = Args.hasArg(OPT_strip_debug);
338   Config->Threads = Args.hasArg(OPT_threads);
339   Config->Trace = Args.hasArg(OPT_trace);
340   Config->Verbose = Args.hasArg(OPT_verbose);
341   Config->WarnCommon = Args.hasArg(OPT_warn_common);
342 
343   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
344   Config->Entry = getString(Args, OPT_entry);
345   Config->Fini = getString(Args, OPT_fini, "_fini");
346   Config->Init = getString(Args, OPT_init, "_init");
347   Config->OutputFile = getString(Args, OPT_o);
348   Config->Reproduce = getString(Args, OPT_reproduce);
349   Config->SoName = getString(Args, OPT_soname);
350   Config->Sysroot = getString(Args, OPT_sysroot);
351 
352   Config->Optimize = getInteger(Args, OPT_O, 0);
353   Config->LtoO = getInteger(Args, OPT_lto_O, 2);
354   if (Config->LtoO > 3)
355     error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
356   Config->LtoJobs = getInteger(Args, OPT_lto_jobs, 1);
357   if (Config->LtoJobs == 0)
358     error("number of threads must be > 0");
359 
360   Config->ZExecStack = hasZOption(Args, "execstack");
361   Config->ZNodelete = hasZOption(Args, "nodelete");
362   Config->ZNow = hasZOption(Args, "now");
363   Config->ZOrigin = hasZOption(Args, "origin");
364   Config->ZRelro = !hasZOption(Args, "norelro");
365 
366   if (Config->Relocatable)
367     Config->StripAll = false;
368 
369   // --strip-all implies --strip-debug.
370   if (Config->StripAll)
371     Config->StripDebug = true;
372 
373   // Config->Pic is true if we are generating position-independent code.
374   Config->Pic = Config->Pie || Config->Shared;
375 
376   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
377     StringRef S = Arg->getValue();
378     if (S == "gnu") {
379       Config->GnuHash = true;
380       Config->SysvHash = false;
381     } else if (S == "both") {
382       Config->GnuHash = true;
383     } else if (S != "sysv")
384       error("unknown hash style: " + S);
385   }
386 
387   // Parse --build-id or --build-id=<style>.
388   if (Args.hasArg(OPT_build_id))
389     Config->BuildId = BuildIdKind::Fnv1;
390   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
391     StringRef S = Arg->getValue();
392     if (S == "md5") {
393       Config->BuildId = BuildIdKind::Md5;
394     } else if (S == "sha1") {
395       Config->BuildId = BuildIdKind::Sha1;
396     } else
397       error("unknown --build-id style: " + S);
398   }
399 
400   for (auto *Arg : Args.filtered(OPT_undefined))
401     Config->Undefined.push_back(Arg->getValue());
402 
403   if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
404     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
405       parseDynamicList(*Buffer);
406 
407   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
408     Config->DynamicList.push_back(Arg->getValue());
409 
410   if (auto *Arg = Args.getLastArg(OPT_version_script)) {
411     Config->VersionScript = true;
412     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
413       parseVersionScript(*Buffer);
414   }
415 }
416 
417 void LinkerDriver::createFiles(opt::InputArgList &Args) {
418   for (auto *Arg : Args) {
419     switch (Arg->getOption().getID()) {
420     case OPT_l:
421       addLibrary(Arg->getValue());
422       break;
423     case OPT_INPUT:
424     case OPT_script:
425       addFile(Arg->getValue());
426       break;
427     case OPT_as_needed:
428       Config->AsNeeded = true;
429       break;
430     case OPT_no_as_needed:
431       Config->AsNeeded = false;
432       break;
433     case OPT_Bstatic:
434       Config->Static = true;
435       break;
436     case OPT_Bdynamic:
437       Config->Static = false;
438       break;
439     case OPT_whole_archive:
440       WholeArchive = true;
441       break;
442     case OPT_no_whole_archive:
443       WholeArchive = false;
444       break;
445     case OPT_start_lib:
446       InLib = true;
447       break;
448     case OPT_end_lib:
449       InLib = false;
450       break;
451     }
452   }
453 
454   if (Files.empty() && !HasError)
455     error("no input files.");
456 }
457 
458 // Do actual linking. Note that when this function is called,
459 // all linker scripts have already been parsed.
460 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
461   SymbolTable<ELFT> Symtab;
462 
463   std::unique_ptr<TargetInfo> TI(createTarget());
464   Target = TI.get();
465   LinkerScript<ELFT> LS;
466   Script<ELFT>::X = &LS;
467 
468   Config->Rela = ELFT::Is64Bits;
469 
470   // Add entry symbol. Note that AMDGPU binaries have no entry points.
471   if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable &&
472       Config->EMachine != EM_AMDGPU)
473     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
474 
475   // Default output filename is "a.out" by the Unix tradition.
476   if (Config->OutputFile.empty())
477     Config->OutputFile = "a.out";
478 
479   // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
480   if (!Config->Entry.empty()) {
481     StringRef S = Config->Entry;
482     if (S.getAsInteger(0, Config->EntryAddr))
483       Config->EntrySym = Symtab.addUndefined(S)->Backref;
484   }
485 
486   for (std::unique_ptr<InputFile> &F : Files)
487     Symtab.addFile(std::move(F));
488   if (HasError)
489     return; // There were duplicate symbols or incompatible files
490 
491   Symtab.scanUndefinedFlags();
492   Symtab.scanShlibUndefined();
493   Symtab.scanDynamicList();
494   Symtab.scanVersionScript();
495 
496   Symtab.addCombinedLtoObject();
497 
498   for (auto *Arg : Args.filtered(OPT_wrap))
499     Symtab.wrap(Arg->getValue());
500 
501   // Write the result to the file.
502   if (Config->GcSections)
503     markLive<ELFT>(&Symtab);
504   if (Config->ICF)
505     doIcf<ELFT>(&Symtab);
506   writeResult<ELFT>(&Symtab);
507 }
508