xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 217cf69b)
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 "InputSection.h"
16 #include "LinkerScript.h"
17 #include "SymbolListFile.h"
18 #include "SymbolTable.h"
19 #include "Target.h"
20 #include "Writer.h"
21 #include "lld/Driver/Driver.h"
22 #include "llvm/ADT/StringExtras.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 sys::fs;
110   if (Config->Verbose)
111     outs() << Path << "\n";
112 
113   Optional<MemoryBufferRef> Buffer = readFile(Path);
114   if (!Buffer.hasValue())
115     return;
116   MemoryBufferRef MBRef = *Buffer;
117 
118   switch (identify_magic(MBRef.getBuffer())) {
119   case file_magic::unknown:
120     readLinkerScript(MBRef);
121     return;
122   case file_magic::archive:
123     if (WholeArchive) {
124       for (MemoryBufferRef MB : getArchiveMembers(MBRef))
125         Files.push_back(createObjectFile(MB, Path));
126       return;
127     }
128     Files.push_back(make_unique<ArchiveFile>(MBRef));
129     return;
130   case file_magic::elf_shared_object:
131     if (Config->Relocatable) {
132       error("attempted static link of dynamic object " + Path);
133       return;
134     }
135     Files.push_back(createSharedFile(MBRef));
136     return;
137   default:
138     if (InLib)
139       Files.push_back(make_unique<LazyObjectFile>(MBRef));
140     else
141       Files.push_back(createObjectFile(MBRef));
142   }
143 }
144 
145 Optional<MemoryBufferRef> LinkerDriver::readFile(StringRef Path) {
146   auto MBOrErr = MemoryBuffer::getFile(Path);
147   error(MBOrErr, "cannot open " + Path);
148   if (HasError)
149     return None;
150   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
151   MemoryBufferRef MBRef = MB->getMemBufferRef();
152   OwningMBs.push_back(std::move(MB)); // take MB ownership
153 
154   if (Cpio)
155     Cpio->append(relativeToRoot(Path), MBRef.getBuffer());
156 
157   return MBRef;
158 }
159 
160 // Add a given library by searching it from input search paths.
161 void LinkerDriver::addLibrary(StringRef Name) {
162   std::string Path = searchLibrary(Name);
163   if (Path.empty())
164     error("unable to find library -l" + Name);
165   else
166     addFile(Path);
167 }
168 
169 // This function is called on startup. We need this for LTO since
170 // LTO calls LLVM functions to compile bitcode files to native code.
171 // Technically this can be delayed until we read bitcode files, but
172 // we don't bother to do lazily because the initialization is fast.
173 static void initLLVM(opt::InputArgList &Args) {
174   InitializeAllTargets();
175   InitializeAllTargetMCs();
176   InitializeAllAsmPrinters();
177   InitializeAllAsmParsers();
178 
179   // This is a flag to discard all but GlobalValue names.
180   // We want to enable it by default because it saves memory.
181   // Disable it only when a developer option (-save-temps) is given.
182   Driver->Context.setDiscardValueNames(!Config->SaveTemps);
183   Driver->Context.enableDebugTypeODRUniquing();
184 
185   // Parse and evaluate -mllvm options.
186   std::vector<const char *> V;
187   V.push_back("lld (LLVM option parsing)");
188   for (auto *Arg : Args.filtered(OPT_mllvm))
189     V.push_back(Arg->getValue());
190   cl::ParseCommandLineOptions(V.size(), V.data());
191 }
192 
193 // Some command line options or some combinations of them are not allowed.
194 // This function checks for such errors.
195 static void checkOptions(opt::InputArgList &Args) {
196   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
197   // table which is a relatively new feature.
198   if (Config->EMachine == EM_MIPS && Config->GnuHash)
199     error("the .gnu.hash section is not compatible with the MIPS target.");
200 
201   if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
202     error("-e option is not valid for AMDGPU.");
203 
204   if (Config->Pie && Config->Shared)
205     error("-shared and -pie may not be used together");
206 
207   if (Config->Relocatable) {
208     if (Config->Shared)
209       error("-r and -shared may not be used together");
210     if (Config->GcSections)
211       error("-r and --gc-sections may not be used together");
212     if (Config->ICF)
213       error("-r and --icf may not be used together");
214     if (Config->Pie)
215       error("-r and -pie may not be used together");
216   }
217 }
218 
219 static StringRef
220 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
221   if (auto *Arg = Args.getLastArg(Key))
222     return Arg->getValue();
223   return Default;
224 }
225 
226 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
227   int V = Default;
228   if (auto *Arg = Args.getLastArg(Key)) {
229     StringRef S = Arg->getValue();
230     if (S.getAsInteger(10, V))
231       error(Arg->getSpelling() + ": number expected, but got " + S);
232   }
233   return V;
234 }
235 
236 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
237   for (auto *Arg : Args.filtered(OPT_z))
238     if (Key == Arg->getValue())
239       return true;
240   return false;
241 }
242 
243 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
244   ELFOptTable Parser;
245   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
246   if (Args.hasArg(OPT_help)) {
247     printHelp(ArgsArr[0]);
248     return;
249   }
250   if (Args.hasArg(OPT_version)) {
251     outs() << getVersionString();
252     return;
253   }
254 
255   if (auto *Arg = Args.getLastArg(OPT_reproduce)) {
256     // Note that --reproduce is a debug option so you can ignore it
257     // if you are trying to understand the whole picture of the code.
258     Cpio.reset(CpioFile::create(Arg->getValue()));
259     if (Cpio) {
260       Cpio->append("response.txt", createResponseFile(Args));
261       Cpio->append("version.txt", getVersionString());
262     }
263   }
264 
265   readConfigs(Args);
266   initLLVM(Args);
267   createFiles(Args);
268   checkOptions(Args);
269   if (HasError)
270     return;
271 
272   switch (Config->EKind) {
273   case ELF32LEKind:
274     link<ELF32LE>(Args);
275     return;
276   case ELF32BEKind:
277     link<ELF32BE>(Args);
278     return;
279   case ELF64LEKind:
280     link<ELF64LE>(Args);
281     return;
282   case ELF64BEKind:
283     link<ELF64BE>(Args);
284     return;
285   default:
286     error("-m or at least a .o file required");
287   }
288 }
289 
290 // Initializes Config members by the command line options.
291 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
292   for (auto *Arg : Args.filtered(OPT_L))
293     Config->SearchPaths.push_back(Arg->getValue());
294 
295   std::vector<StringRef> RPaths;
296   for (auto *Arg : Args.filtered(OPT_rpath))
297     RPaths.push_back(Arg->getValue());
298   if (!RPaths.empty())
299     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
300 
301   if (auto *Arg = Args.getLastArg(OPT_m)) {
302     // Parse ELF{32,64}{LE,BE} and CPU type.
303     StringRef S = Arg->getValue();
304     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
305     Config->Emulation = S;
306   }
307 
308   if (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind)
309     Config->Mips64EL = true;
310 
311   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
312   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
313   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
314   Config->Demangle = !Args.hasArg(OPT_no_demangle);
315   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
316   Config->DiscardAll = Args.hasArg(OPT_discard_all);
317   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
318   Config->DiscardNone = Args.hasArg(OPT_discard_none);
319   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
320   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
321   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
322   Config->GcSections = Args.hasArg(OPT_gc_sections);
323   Config->ICF = Args.hasArg(OPT_icf);
324   Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
325   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
326   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
327   Config->Pie = Args.hasArg(OPT_pie);
328   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
329   Config->Relocatable = Args.hasArg(OPT_relocatable);
330   Config->SaveTemps = Args.hasArg(OPT_save_temps);
331   Config->Shared = Args.hasArg(OPT_shared);
332   Config->StripAll = Args.hasArg(OPT_strip_all);
333   Config->StripDebug = Args.hasArg(OPT_strip_debug);
334   Config->Threads = Args.hasArg(OPT_threads);
335   Config->Trace = Args.hasArg(OPT_trace);
336   Config->Verbose = Args.hasArg(OPT_verbose);
337   Config->WarnCommon = Args.hasArg(OPT_warn_common);
338 
339   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
340   Config->Entry = getString(Args, OPT_entry);
341   Config->Fini = getString(Args, OPT_fini, "_fini");
342   Config->Init = getString(Args, OPT_init, "_init");
343   Config->LtoAAPipeline = getString(Args, OPT_lto_aa_pipeline);
344   Config->LtoNewPmPasses = getString(Args, OPT_lto_newpm_passes);
345   Config->OutputFile = getString(Args, OPT_o);
346   Config->SoName = getString(Args, OPT_soname);
347   Config->Sysroot = getString(Args, OPT_sysroot);
348 
349   Config->Optimize = getInteger(Args, OPT_O, 1);
350   Config->LtoO = getInteger(Args, OPT_lto_O, 2);
351   if (Config->LtoO > 3)
352     error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
353   Config->LtoJobs = getInteger(Args, OPT_lto_jobs, 1);
354   if (Config->LtoJobs == 0)
355     error("number of threads must be > 0");
356 
357   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
358   Config->ZDefs = hasZOption(Args, "defs");
359   Config->ZExecStack = hasZOption(Args, "execstack");
360   Config->ZNodelete = hasZOption(Args, "nodelete");
361   Config->ZNow = hasZOption(Args, "now");
362   Config->ZOrigin = hasZOption(Args, "origin");
363   Config->ZRelro = !hasZOption(Args, "norelro");
364 
365   if (Config->Relocatable)
366     Config->StripAll = false;
367 
368   // --strip-all implies --strip-debug.
369   if (Config->StripAll)
370     Config->StripDebug = true;
371 
372   // Config->Pic is true if we are generating position-independent code.
373   Config->Pic = Config->Pie || Config->Shared;
374 
375   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
376     StringRef S = Arg->getValue();
377     if (S == "gnu") {
378       Config->GnuHash = true;
379       Config->SysvHash = false;
380     } else if (S == "both") {
381       Config->GnuHash = true;
382     } else if (S != "sysv")
383       error("unknown hash style: " + S);
384   }
385 
386   // Parse --build-id or --build-id=<style>.
387   if (Args.hasArg(OPT_build_id))
388     Config->BuildId = BuildIdKind::Fnv1;
389   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
390     StringRef S = Arg->getValue();
391     if (S == "md5") {
392       Config->BuildId = BuildIdKind::Md5;
393     } else if (S == "sha1") {
394       Config->BuildId = BuildIdKind::Sha1;
395     } else if (S == "none") {
396       Config->BuildId = BuildIdKind::None;
397     } else if (S.startswith("0x")) {
398       Config->BuildId = BuildIdKind::Hexstring;
399       Config->BuildIdVector = parseHexstring(S.substr(2));
400     } else {
401       error("unknown --build-id style: " + S);
402     }
403   }
404 
405   for (auto *Arg : Args.filtered(OPT_undefined))
406     Config->Undefined.push_back(Arg->getValue());
407 
408   if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
409     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
410       parseDynamicList(*Buffer);
411 
412   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
413     Config->DynamicList.push_back(Arg->getValue());
414 
415   if (auto *Arg = Args.getLastArg(OPT_version_script)) {
416     Config->VersionScript = true;
417     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
418       parseVersionScript(*Buffer);
419   }
420 }
421 
422 void LinkerDriver::createFiles(opt::InputArgList &Args) {
423   for (auto *Arg : Args) {
424     switch (Arg->getOption().getID()) {
425     case OPT_l:
426       addLibrary(Arg->getValue());
427       break;
428     case OPT_alias_script_T:
429     case OPT_INPUT:
430     case OPT_script:
431       addFile(Arg->getValue());
432       break;
433     case OPT_as_needed:
434       Config->AsNeeded = true;
435       break;
436     case OPT_no_as_needed:
437       Config->AsNeeded = false;
438       break;
439     case OPT_Bstatic:
440       Config->Static = true;
441       break;
442     case OPT_Bdynamic:
443       Config->Static = false;
444       break;
445     case OPT_whole_archive:
446       WholeArchive = true;
447       break;
448     case OPT_no_whole_archive:
449       WholeArchive = false;
450       break;
451     case OPT_start_lib:
452       InLib = true;
453       break;
454     case OPT_end_lib:
455       InLib = false;
456       break;
457     }
458   }
459 
460   if (Files.empty() && !HasError)
461     error("no input files.");
462 }
463 
464 // Do actual linking. Note that when this function is called,
465 // all linker scripts have already been parsed.
466 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
467   SymbolTable<ELFT> Symtab;
468   elf::Symtab<ELFT>::X = &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);
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   if (HasError)
505     return;
506 
507   for (auto *Arg : Args.filtered(OPT_wrap))
508     Symtab.wrap(Arg->getValue());
509 
510   // Write the result to the file.
511   if (Config->GcSections)
512     markLive<ELFT>();
513   if (Config->ICF)
514     doIcf<ELFT>();
515 
516   // MergeInputSection::splitIntoPieces needs to be called before
517   // any call of MergeInputSection::getOffset. Do that.
518   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
519        Symtab.getObjectFiles())
520     for (InputSectionBase<ELFT> *S : F->getSections())
521       if (S && S != &InputSection<ELFT>::Discarded && S->Live)
522         if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
523           MS->splitIntoPieces();
524 
525   writeResult<ELFT>(&Symtab);
526 }
527