xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 981986cd)
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   if (Cpio)
119     Cpio->append(relativeToRoot(Path), MBRef.getBuffer());
120 
121   switch (identify_magic(MBRef.getBuffer())) {
122   case file_magic::unknown:
123     readLinkerScript(MBRef);
124     return;
125   case file_magic::archive:
126     if (WholeArchive) {
127       for (MemoryBufferRef MB : getArchiveMembers(MBRef))
128         Files.push_back(createObjectFile(MB, Path));
129       return;
130     }
131     Files.push_back(make_unique<ArchiveFile>(MBRef));
132     return;
133   case file_magic::elf_shared_object:
134     if (Config->Relocatable) {
135       error("attempted static link of dynamic object " + Path);
136       return;
137     }
138     Files.push_back(createSharedFile(MBRef));
139     return;
140   default:
141     if (InLib)
142       Files.push_back(make_unique<LazyObjectFile>(MBRef));
143     else
144       Files.push_back(createObjectFile(MBRef));
145   }
146 }
147 
148 Optional<MemoryBufferRef> LinkerDriver::readFile(StringRef Path) {
149   auto MBOrErr = MemoryBuffer::getFile(Path);
150   error(MBOrErr, "cannot open " + Path);
151   if (HasError)
152     return None;
153   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
154   MemoryBufferRef MBRef = MB->getMemBufferRef();
155   OwningMBs.push_back(std::move(MB)); // take MB ownership
156   return MBRef;
157 }
158 
159 // Add a given library by searching it from input search paths.
160 void LinkerDriver::addLibrary(StringRef Name) {
161   std::string Path = searchLibrary(Name);
162   if (Path.empty())
163     error("unable to find library -l" + Name);
164   else
165     addFile(Path);
166 }
167 
168 // This function is called on startup. We need this for LTO since
169 // LTO calls LLVM functions to compile bitcode files to native code.
170 // Technically this can be delayed until we read bitcode files, but
171 // we don't bother to do lazily because the initialization is fast.
172 static void initLLVM(opt::InputArgList &Args) {
173   InitializeAllTargets();
174   InitializeAllTargetMCs();
175   InitializeAllAsmPrinters();
176   InitializeAllAsmParsers();
177 
178   // This is a flag to discard all but GlobalValue names.
179   // We want to enable it by default because it saves memory.
180   // Disable it only when a developer option (-save-temps) is given.
181   Driver->Context.setDiscardValueNames(!Config->SaveTemps);
182   Driver->Context.enableDebugTypeODRUniquing();
183 
184   // Parse and evaluate -mllvm options.
185   std::vector<const char *> V;
186   V.push_back("lld (LLVM option parsing)");
187   for (auto *Arg : Args.filtered(OPT_mllvm))
188     V.push_back(Arg->getValue());
189   cl::ParseCommandLineOptions(V.size(), V.data());
190 }
191 
192 // Some command line options or some combinations of them are not allowed.
193 // This function checks for such errors.
194 static void checkOptions(opt::InputArgList &Args) {
195   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
196   // table which is a relatively new feature.
197   if (Config->EMachine == EM_MIPS && Config->GnuHash)
198     error("the .gnu.hash section is not compatible with the MIPS target.");
199 
200   if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
201     error("-e option is not valid for AMDGPU.");
202 
203   if (Config->Pie && Config->Shared)
204     error("-shared and -pie may not be used together");
205 
206   if (Config->Relocatable) {
207     if (Config->Shared)
208       error("-r and -shared may not be used together");
209     if (Config->GcSections)
210       error("-r and --gc-sections may not be used together");
211     if (Config->ICF)
212       error("-r and --icf may not be used together");
213     if (Config->Pie)
214       error("-r and -pie may not be used together");
215   }
216 }
217 
218 static StringRef
219 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
220   if (auto *Arg = Args.getLastArg(Key))
221     return Arg->getValue();
222   return Default;
223 }
224 
225 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
226   int V = Default;
227   if (auto *Arg = Args.getLastArg(Key)) {
228     StringRef S = Arg->getValue();
229     if (S.getAsInteger(10, V))
230       error(Arg->getSpelling() + ": number expected, but got " + S);
231   }
232   return V;
233 }
234 
235 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
236   for (auto *Arg : Args.filtered(OPT_z))
237     if (Key == Arg->getValue())
238       return true;
239   return false;
240 }
241 
242 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
243   ELFOptTable Parser;
244   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
245   if (Args.hasArg(OPT_help)) {
246     printHelp(ArgsArr[0]);
247     return;
248   }
249   if (Args.hasArg(OPT_version)) {
250     printVersion();
251     return;
252   }
253 
254   readConfigs(Args);
255   initLLVM(Args);
256 
257   if (auto *Arg = Args.getLastArg(OPT_reproduce)) {
258     // Note that --reproduce is a debug option so you can ignore it
259     // if you are trying to understand the whole picture of the code.
260     Cpio.reset(CpioFile::create(Arg->getValue()));
261     if (Cpio)
262       Cpio->append("response.txt", createResponseFile(Args));
263   }
264 
265   createFiles(Args);
266   checkOptions(Args);
267   if (HasError)
268     return;
269 
270   switch (Config->EKind) {
271   case ELF32LEKind:
272     link<ELF32LE>(Args);
273     return;
274   case ELF32BEKind:
275     link<ELF32BE>(Args);
276     return;
277   case ELF64LEKind:
278     link<ELF64LE>(Args);
279     return;
280   case ELF64BEKind:
281     link<ELF64BE>(Args);
282     return;
283   default:
284     error("-m or at least a .o file required");
285   }
286 }
287 
288 // Initializes Config members by the command line options.
289 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
290   for (auto *Arg : Args.filtered(OPT_L))
291     Config->SearchPaths.push_back(Arg->getValue());
292 
293   std::vector<StringRef> RPaths;
294   for (auto *Arg : Args.filtered(OPT_rpath))
295     RPaths.push_back(Arg->getValue());
296   if (!RPaths.empty())
297     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
298 
299   if (auto *Arg = Args.getLastArg(OPT_m)) {
300     // Parse ELF{32,64}{LE,BE} and CPU type.
301     StringRef S = Arg->getValue();
302     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
303     Config->Emulation = S;
304   }
305 
306   if (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind)
307     Config->Mips64EL = true;
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->LtoAAPipeline = getString(Args, OPT_lto_aa_pipeline);
342   Config->LtoNewPmPasses = getString(Args, OPT_lto_newpm_passes);
343   Config->OutputFile = getString(Args, OPT_o);
344   Config->SoName = getString(Args, OPT_soname);
345   Config->Sysroot = getString(Args, OPT_sysroot);
346 
347   Config->Optimize = getInteger(Args, OPT_O, 1);
348   Config->LtoO = getInteger(Args, OPT_lto_O, 2);
349   if (Config->LtoO > 3)
350     error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
351   Config->LtoJobs = getInteger(Args, OPT_lto_jobs, 1);
352   if (Config->LtoJobs == 0)
353     error("number of threads must be > 0");
354 
355   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
356   Config->ZDefs = hasZOption(Args, "defs");
357   Config->ZExecStack = hasZOption(Args, "execstack");
358   Config->ZNodelete = hasZOption(Args, "nodelete");
359   Config->ZNow = hasZOption(Args, "now");
360   Config->ZOrigin = hasZOption(Args, "origin");
361   Config->ZRelro = !hasZOption(Args, "norelro");
362 
363   if (Config->Relocatable)
364     Config->StripAll = false;
365 
366   // --strip-all implies --strip-debug.
367   if (Config->StripAll)
368     Config->StripDebug = true;
369 
370   // Config->Pic is true if we are generating position-independent code.
371   Config->Pic = Config->Pie || Config->Shared;
372 
373   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
374     StringRef S = Arg->getValue();
375     if (S == "gnu") {
376       Config->GnuHash = true;
377       Config->SysvHash = false;
378     } else if (S == "both") {
379       Config->GnuHash = true;
380     } else if (S != "sysv")
381       error("unknown hash style: " + S);
382   }
383 
384   // Parse --build-id or --build-id=<style>.
385   if (Args.hasArg(OPT_build_id))
386     Config->BuildId = BuildIdKind::Fnv1;
387   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
388     StringRef S = Arg->getValue();
389     if (S == "md5") {
390       Config->BuildId = BuildIdKind::Md5;
391     } else if (S == "sha1") {
392       Config->BuildId = BuildIdKind::Sha1;
393     } else if (S == "none") {
394       Config->BuildId = BuildIdKind::None;
395     } else if (S.startswith("0x")) {
396       Config->BuildId = BuildIdKind::Hexstring;
397       Config->BuildIdVector = parseHexstring(S.substr(2));
398     } else {
399       error("unknown --build-id style: " + S);
400     }
401   }
402 
403   for (auto *Arg : Args.filtered(OPT_undefined))
404     Config->Undefined.push_back(Arg->getValue());
405 
406   if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
407     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
408       parseDynamicList(*Buffer);
409 
410   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
411     Config->DynamicList.push_back(Arg->getValue());
412 
413   if (auto *Arg = Args.getLastArg(OPT_version_script)) {
414     Config->VersionScript = true;
415     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
416       parseVersionScript(*Buffer);
417   }
418 }
419 
420 void LinkerDriver::createFiles(opt::InputArgList &Args) {
421   for (auto *Arg : Args) {
422     switch (Arg->getOption().getID()) {
423     case OPT_l:
424       addLibrary(Arg->getValue());
425       break;
426     case OPT_alias_script_T:
427     case OPT_INPUT:
428     case OPT_script:
429       addFile(Arg->getValue());
430       break;
431     case OPT_as_needed:
432       Config->AsNeeded = true;
433       break;
434     case OPT_no_as_needed:
435       Config->AsNeeded = false;
436       break;
437     case OPT_Bstatic:
438       Config->Static = true;
439       break;
440     case OPT_Bdynamic:
441       Config->Static = false;
442       break;
443     case OPT_whole_archive:
444       WholeArchive = true;
445       break;
446     case OPT_no_whole_archive:
447       WholeArchive = false;
448       break;
449     case OPT_start_lib:
450       InLib = true;
451       break;
452     case OPT_end_lib:
453       InLib = false;
454       break;
455     }
456   }
457 
458   if (Files.empty() && !HasError)
459     error("no input files.");
460 }
461 
462 // Do actual linking. Note that when this function is called,
463 // all linker scripts have already been parsed.
464 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
465   SymbolTable<ELFT> Symtab;
466   elf::Symtab<ELFT>::X = &Symtab;
467 
468   std::unique_ptr<TargetInfo> TI(createTarget());
469   Target = TI.get();
470   LinkerScript<ELFT> LS;
471   Script<ELFT>::X = &LS;
472 
473   Config->Rela = ELFT::Is64Bits;
474 
475   // Add entry symbol. Note that AMDGPU binaries have no entry points.
476   if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable &&
477       Config->EMachine != EM_AMDGPU)
478     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
479 
480   // Default output filename is "a.out" by the Unix tradition.
481   if (Config->OutputFile.empty())
482     Config->OutputFile = "a.out";
483 
484   // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
485   if (!Config->Entry.empty()) {
486     StringRef S = Config->Entry;
487     if (S.getAsInteger(0, Config->EntryAddr))
488       Config->EntrySym = Symtab.addUndefined(S);
489   }
490 
491   for (std::unique_ptr<InputFile> &F : Files)
492     Symtab.addFile(std::move(F));
493   if (HasError)
494     return; // There were duplicate symbols or incompatible files
495 
496   Symtab.scanUndefinedFlags();
497   Symtab.scanShlibUndefined();
498   Symtab.scanDynamicList();
499   Symtab.scanVersionScript();
500 
501   Symtab.addCombinedLtoObject();
502   if (HasError)
503     return;
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>();
511   if (Config->ICF)
512     doIcf<ELFT>();
513 
514   // MergeInputSection::splitIntoPieces needs to be called before
515   // any call of MergeInputSection::getOffset. Do that.
516   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
517        Symtab.getObjectFiles())
518     for (InputSectionBase<ELFT> *S : F->getSections())
519       if (S && S != &InputSection<ELFT>::Discarded && S->Live)
520         if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
521           MS->splitIntoPieces();
522 
523   writeResult<ELFT>(&Symtab);
524 }
525