xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 94eb010f)
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->LtoNewPmPasses = getString(Args, OPT_lto_newpm_passes);
342   Config->OutputFile = getString(Args, OPT_o);
343   Config->SoName = getString(Args, OPT_soname);
344   Config->Sysroot = getString(Args, OPT_sysroot);
345 
346   Config->Optimize = getInteger(Args, OPT_O, 1);
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->ZCombreloc = !hasZOption(Args, "nocombreloc");
355   Config->ZDefs = hasZOption(Args, "defs");
356   Config->ZExecStack = hasZOption(Args, "execstack");
357   Config->ZNodelete = hasZOption(Args, "nodelete");
358   Config->ZNow = hasZOption(Args, "now");
359   Config->ZOrigin = hasZOption(Args, "origin");
360   Config->ZRelro = !hasZOption(Args, "norelro");
361 
362   if (Config->Relocatable)
363     Config->StripAll = false;
364 
365   // --strip-all implies --strip-debug.
366   if (Config->StripAll)
367     Config->StripDebug = true;
368 
369   // Config->Pic is true if we are generating position-independent code.
370   Config->Pic = Config->Pie || Config->Shared;
371 
372   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
373     StringRef S = Arg->getValue();
374     if (S == "gnu") {
375       Config->GnuHash = true;
376       Config->SysvHash = false;
377     } else if (S == "both") {
378       Config->GnuHash = true;
379     } else if (S != "sysv")
380       error("unknown hash style: " + S);
381   }
382 
383   // Parse --build-id or --build-id=<style>.
384   if (Args.hasArg(OPT_build_id))
385     Config->BuildId = BuildIdKind::Fnv1;
386   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
387     StringRef S = Arg->getValue();
388     if (S == "md5") {
389       Config->BuildId = BuildIdKind::Md5;
390     } else if (S == "sha1") {
391       Config->BuildId = BuildIdKind::Sha1;
392     } else if (S == "none") {
393       Config->BuildId = BuildIdKind::None;
394     } else if (S.startswith("0x")) {
395       Config->BuildId = BuildIdKind::Hexstring;
396       Config->BuildIdVector = parseHexstring(S.substr(2));
397     } else {
398       error("unknown --build-id style: " + S);
399     }
400   }
401 
402   for (auto *Arg : Args.filtered(OPT_undefined))
403     Config->Undefined.push_back(Arg->getValue());
404 
405   if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
406     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
407       parseDynamicList(*Buffer);
408 
409   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
410     Config->DynamicList.push_back(Arg->getValue());
411 
412   if (auto *Arg = Args.getLastArg(OPT_version_script)) {
413     Config->VersionScript = true;
414     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
415       parseVersionScript(*Buffer);
416   }
417 }
418 
419 void LinkerDriver::createFiles(opt::InputArgList &Args) {
420   for (auto *Arg : Args) {
421     switch (Arg->getOption().getID()) {
422     case OPT_l:
423       addLibrary(Arg->getValue());
424       break;
425     case OPT_INPUT:
426     case OPT_script:
427       addFile(Arg->getValue());
428       break;
429     case OPT_as_needed:
430       Config->AsNeeded = true;
431       break;
432     case OPT_no_as_needed:
433       Config->AsNeeded = false;
434       break;
435     case OPT_Bstatic:
436       Config->Static = true;
437       break;
438     case OPT_Bdynamic:
439       Config->Static = false;
440       break;
441     case OPT_whole_archive:
442       WholeArchive = true;
443       break;
444     case OPT_no_whole_archive:
445       WholeArchive = false;
446       break;
447     case OPT_start_lib:
448       InLib = true;
449       break;
450     case OPT_end_lib:
451       InLib = false;
452       break;
453     }
454   }
455 
456   if (Files.empty() && !HasError)
457     error("no input files.");
458 }
459 
460 // Do actual linking. Note that when this function is called,
461 // all linker scripts have already been parsed.
462 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
463   SymbolTable<ELFT> Symtab;
464   elf::Symtab<ELFT>::X = &Symtab;
465 
466   std::unique_ptr<TargetInfo> TI(createTarget());
467   Target = TI.get();
468   LinkerScript<ELFT> LS;
469   Script<ELFT>::X = &LS;
470 
471   Config->Rela = ELFT::Is64Bits;
472 
473   // Add entry symbol. Note that AMDGPU binaries have no entry points.
474   if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable &&
475       Config->EMachine != EM_AMDGPU)
476     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
477 
478   // Default output filename is "a.out" by the Unix tradition.
479   if (Config->OutputFile.empty())
480     Config->OutputFile = "a.out";
481 
482   // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
483   if (!Config->Entry.empty()) {
484     StringRef S = Config->Entry;
485     if (S.getAsInteger(0, Config->EntryAddr))
486       Config->EntrySym = Symtab.addUndefined(S);
487   }
488 
489   for (std::unique_ptr<InputFile> &F : Files)
490     Symtab.addFile(std::move(F));
491   if (HasError)
492     return; // There were duplicate symbols or incompatible files
493 
494   Symtab.scanUndefinedFlags();
495   Symtab.scanShlibUndefined();
496   Symtab.scanDynamicList();
497   Symtab.scanVersionScript();
498 
499   Symtab.addCombinedLtoObject();
500   if (HasError)
501     return;
502 
503   for (auto *Arg : Args.filtered(OPT_wrap))
504     Symtab.wrap(Arg->getValue());
505 
506   // Write the result to the file.
507   if (Config->GcSections)
508     markLive<ELFT>();
509   if (Config->ICF)
510     doIcf<ELFT>();
511 
512   // MergeInputSection::splitIntoPieces needs to be called before
513   // any call of MergeInputSection::getOffset. Do that.
514   for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
515        Symtab.getObjectFiles())
516     for (InputSectionBase<ELFT> *S : F->getSections())
517       if (S && S != &InputSection<ELFT>::Discarded && S->Live)
518         if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
519           MS->splitIntoPieces();
520 
521   writeResult<ELFT>(&Symtab);
522 }
523