xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision c1fe2c43)
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 "SymbolTable.h"
17 #include "Target.h"
18 #include "Writer.h"
19 #include "lld/Driver/Driver.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/TargetSelect.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <utility>
24 
25 using namespace llvm;
26 using namespace llvm::ELF;
27 using namespace llvm::object;
28 
29 using namespace lld;
30 using namespace lld::elf;
31 
32 Configuration *elf::Config;
33 LinkerDriver *elf::Driver;
34 
35 bool elf::link(ArrayRef<const char *> Args, raw_ostream &Error) {
36   HasError = false;
37   ErrorOS = &Error;
38   Configuration C;
39   LinkerDriver D;
40   LinkerScript LS;
41   Config = &C;
42   Driver = &D;
43   Script = &LS;
44   Driver->main(Args);
45   return !HasError;
46 }
47 
48 static std::pair<ELFKind, uint16_t> parseEmulation(StringRef S) {
49   if (S == "elf32btsmip")
50     return {ELF32BEKind, EM_MIPS};
51   if (S == "elf32ltsmip")
52     return {ELF32LEKind, EM_MIPS};
53   if (S == "elf32ppc" || S == "elf32ppc_fbsd")
54     return {ELF32BEKind, EM_PPC};
55   if (S == "elf64ppc" || S == "elf64ppc_fbsd")
56     return {ELF64BEKind, EM_PPC64};
57   if (S == "elf_i386")
58     return {ELF32LEKind, EM_386};
59   if (S == "elf_x86_64")
60     return {ELF64LEKind, EM_X86_64};
61   if (S == "aarch64linux")
62     return {ELF64LEKind, EM_AARCH64};
63   if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
64     error("Windows targets are not supported on the ELF frontend: " + S);
65   else
66     error("unknown emulation: " + S);
67   return {ELFNoneKind, 0};
68 }
69 
70 // Returns slices of MB by parsing MB as an archive file.
71 // Each slice consists of a member file in the archive.
72 static std::vector<MemoryBufferRef> getArchiveMembers(MemoryBufferRef MB) {
73   std::unique_ptr<Archive> File =
74       check(Archive::create(MB), "Failed to parse archive");
75 
76   std::vector<MemoryBufferRef> V;
77   for (const ErrorOr<Archive::Child> &COrErr : File->children()) {
78     Archive::Child C = check(COrErr, "Could not get the child of the archive " +
79                                          File->getFileName());
80     MemoryBufferRef Mb =
81         check(C.getMemoryBufferRef(),
82               "Could not get the buffer for a child of the archive " +
83                   File->getFileName());
84     V.push_back(Mb);
85   }
86   return V;
87 }
88 
89 // Opens and parses a file. Path has to be resolved already.
90 // Newly created memory buffers are owned by this driver.
91 void LinkerDriver::addFile(StringRef Path) {
92   using namespace llvm::sys::fs;
93   log(Path);
94   auto MBOrErr = MemoryBuffer::getFile(Path);
95   if (!MBOrErr) {
96     error(MBOrErr, "cannot open " + Path);
97     return;
98   }
99   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
100   MemoryBufferRef MBRef = MB->getMemBufferRef();
101   OwningMBs.push_back(std::move(MB)); // take MB ownership
102 
103   switch (identify_magic(MBRef.getBuffer())) {
104   case file_magic::unknown:
105     Script->read(MBRef);
106     return;
107   case file_magic::archive:
108     if (WholeArchive) {
109       for (MemoryBufferRef MB : getArchiveMembers(MBRef))
110         Files.push_back(createObjectFile(MB, Path));
111       return;
112     }
113     Files.push_back(make_unique<ArchiveFile>(MBRef));
114     return;
115   case file_magic::elf_shared_object:
116     if (Config->Relocatable) {
117       error("attempted static link of dynamic object " + Path);
118       return;
119     }
120     Files.push_back(createSharedFile(MBRef));
121     return;
122   default:
123     Files.push_back(createObjectFile(MBRef));
124   }
125 }
126 
127 // Add a given library by searching it from input search paths.
128 void LinkerDriver::addLibrary(StringRef Name) {
129   std::string Path = searchLibrary(Name);
130   if (Path.empty())
131     error("unable to find library -l" + Name);
132   else
133     addFile(Path);
134 }
135 
136 // Some command line options or some combinations of them are not allowed.
137 // This function checks for such errors.
138 static void checkOptions(opt::InputArgList &Args) {
139   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
140   // table which is a relatively new feature.
141   if (Config->EMachine == EM_MIPS && Config->GnuHash)
142     error("the .gnu.hash section is not compatible with the MIPS target.");
143 
144   if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
145     error("-e option is not valid for AMDGPU.");
146 
147   if (!Config->Relocatable)
148     return;
149 
150   if (Config->Shared)
151     error("-r and -shared may not be used together");
152   if (Config->GcSections)
153     error("-r and --gc-sections may not be used together");
154   if (Config->ICF)
155     error("-r and --icf may not be used together");
156 }
157 
158 static StringRef
159 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
160   if (auto *Arg = Args.getLastArg(Key))
161     return Arg->getValue();
162   return Default;
163 }
164 
165 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
166   for (auto *Arg : Args.filtered(OPT_z))
167     if (Key == Arg->getValue())
168       return true;
169   return false;
170 }
171 
172 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
173   opt::InputArgList Args = parseArgs(&Alloc, ArgsArr.slice(1));
174   if (Args.hasArg(OPT_help)) {
175     printHelp(ArgsArr[0]);
176     return;
177   }
178   if (Args.hasArg(OPT_version)) {
179     printVersion();
180     return;
181   }
182 
183   readConfigs(Args);
184   createFiles(Args);
185   checkOptions(Args);
186   if (HasError)
187     return;
188 
189   switch (Config->EKind) {
190   case ELF32LEKind:
191     link<ELF32LE>(Args);
192     return;
193   case ELF32BEKind:
194     link<ELF32BE>(Args);
195     return;
196   case ELF64LEKind:
197     link<ELF64LE>(Args);
198     return;
199   case ELF64BEKind:
200     link<ELF64BE>(Args);
201     return;
202   default:
203     error("-m or at least a .o file required");
204   }
205 }
206 
207 // Initializes Config members by the command line options.
208 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
209   for (auto *Arg : Args.filtered(OPT_L))
210     Config->SearchPaths.push_back(Arg->getValue());
211 
212   std::vector<StringRef> RPaths;
213   for (auto *Arg : Args.filtered(OPT_rpath))
214     RPaths.push_back(Arg->getValue());
215   if (!RPaths.empty())
216     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
217 
218   if (auto *Arg = Args.getLastArg(OPT_m)) {
219     // Parse ELF{32,64}{LE,BE} and CPU type.
220     StringRef S = Arg->getValue();
221     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
222     Config->Emulation = S;
223   }
224 
225   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
226   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
227   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
228   Config->BuildId = Args.hasArg(OPT_build_id);
229   Config->Demangle = !Args.hasArg(OPT_no_demangle);
230   Config->DiscardAll = Args.hasArg(OPT_discard_all);
231   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
232   Config->DiscardNone = Args.hasArg(OPT_discard_none);
233   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
234   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
235   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
236   Config->GcSections = Args.hasArg(OPT_gc_sections);
237   Config->ICF = Args.hasArg(OPT_icf);
238   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
239   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
240   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
241   Config->Relocatable = Args.hasArg(OPT_relocatable);
242   Config->SaveTemps = Args.hasArg(OPT_save_temps);
243   Config->Shared = Args.hasArg(OPT_shared);
244   Config->StripAll = Args.hasArg(OPT_strip_all);
245   Config->Threads = Args.hasArg(OPT_threads);
246   Config->Verbose = Args.hasArg(OPT_verbose);
247   Config->WarnCommon = Args.hasArg(OPT_warn_common);
248 
249   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
250   Config->Entry = getString(Args, OPT_entry);
251   Config->Fini = getString(Args, OPT_fini, "_fini");
252   Config->Init = getString(Args, OPT_init, "_init");
253   Config->OutputFile = getString(Args, OPT_o);
254   Config->SoName = getString(Args, OPT_soname);
255   Config->Sysroot = getString(Args, OPT_sysroot);
256 
257   Config->ZExecStack = hasZOption(Args, "execstack");
258   Config->ZNodelete = hasZOption(Args, "nodelete");
259   Config->ZNow = hasZOption(Args, "now");
260   Config->ZOrigin = hasZOption(Args, "origin");
261   Config->ZRelro = !hasZOption(Args, "norelro");
262 
263   if (Config->Relocatable)
264     Config->StripAll = false;
265 
266   if (auto *Arg = Args.getLastArg(OPT_O)) {
267     StringRef Val = Arg->getValue();
268     if (Val.getAsInteger(10, Config->Optimize))
269       error("invalid optimization level");
270   }
271 
272   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
273     StringRef S = Arg->getValue();
274     if (S == "gnu") {
275       Config->GnuHash = true;
276       Config->SysvHash = false;
277     } else if (S == "both") {
278       Config->GnuHash = true;
279     } else if (S != "sysv")
280       error("unknown hash style: " + S);
281   }
282 
283   for (auto *Arg : Args.filtered(OPT_undefined))
284     Config->Undefined.push_back(Arg->getValue());
285 }
286 
287 void LinkerDriver::createFiles(opt::InputArgList &Args) {
288   for (auto *Arg : Args) {
289     switch (Arg->getOption().getID()) {
290     case OPT_l:
291       addLibrary(Arg->getValue());
292       break;
293     case OPT_INPUT:
294     case OPT_script:
295       addFile(Arg->getValue());
296       break;
297     case OPT_as_needed:
298       Config->AsNeeded = true;
299       break;
300     case OPT_no_as_needed:
301       Config->AsNeeded = false;
302       break;
303     case OPT_Bstatic:
304       Config->Static = true;
305       break;
306     case OPT_Bdynamic:
307       Config->Static = false;
308       break;
309     case OPT_whole_archive:
310       WholeArchive = true;
311       break;
312     case OPT_no_whole_archive:
313       WholeArchive = false;
314       break;
315     }
316   }
317 
318   if (Files.empty() && !HasError)
319     error("no input files.");
320 }
321 
322 template <class ELFT> static void initSymbols() {
323   ElfSym<ELFT>::Etext.setBinding(STB_GLOBAL);
324   ElfSym<ELFT>::Edata.setBinding(STB_GLOBAL);
325   ElfSym<ELFT>::End.setBinding(STB_GLOBAL);
326   ElfSym<ELFT>::Ignored.setBinding(STB_WEAK);
327   ElfSym<ELFT>::Ignored.setVisibility(STV_HIDDEN);
328 }
329 
330 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
331   // For LTO
332   InitializeAllTargets();
333   InitializeAllTargetMCs();
334   InitializeAllAsmPrinters();
335   InitializeAllAsmParsers();
336 
337   initSymbols<ELFT>();
338 
339   SymbolTable<ELFT> Symtab;
340   std::unique_ptr<TargetInfo> TI(createTarget());
341   Target = TI.get();
342 
343   Config->Rela = ELFT::Is64Bits;
344 
345   if (!Config->Shared && !Config->Relocatable) {
346     // Add entry symbol.
347     //
348     // There is no entry symbol for AMDGPU binaries, so skip adding one to avoid
349     // having and undefined symbol.
350     if (Config->Entry.empty() && Config->EMachine != EM_AMDGPU)
351       Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
352 
353     // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
354     // is magical and is used to produce a R_386_GOTPC relocation.
355     // The R_386_GOTPC relocation value doesn't actually depend on the
356     // symbol value, so it could use an index of STN_UNDEF which, according
357     // to the spec, means the symbol value is 0.
358     // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
359     // the object file.
360     // The situation is even stranger on x86_64 where the assembly doesn't
361     // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
362     // an undefined symbol in the .o files.
363     // Given that the symbol is effectively unused, we just create a dummy
364     // hidden one to avoid the undefined symbol error.
365     Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
366   }
367 
368   if (!Config->Entry.empty()) {
369     // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
370     StringRef S = Config->Entry;
371     if (S.getAsInteger(0, Config->EntryAddr))
372       Config->EntrySym = Symtab.addUndefined(S);
373   }
374 
375   if (Config->EMachine == EM_MIPS) {
376     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
377     // start of function and 'gp' pointer into GOT.
378     Config->MipsGpDisp = Symtab.addIgnored("_gp_disp");
379     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
380     // pointer. This symbol is used in the code generated by .cpload pseudo-op
381     // in case of using -mno-shared option.
382     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
383     Config->MipsLocalGp = Symtab.addIgnored("__gnu_local_gp");
384 
385     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
386     // so that it points to an absolute address which is relative to GOT.
387     // See "Global Data Symbols" in Chapter 6 in the following document:
388     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
389     Symtab.addAbsolute("_gp", ElfSym<ELFT>::MipsGp);
390   }
391 
392   for (std::unique_ptr<InputFile> &F : Files)
393     Symtab.addFile(std::move(F));
394   if (HasError)
395     return; // There were duplicate symbols or incompatible files
396 
397   for (StringRef S : Config->Undefined)
398     Symtab.addUndefinedOpt(S);
399 
400   Symtab.addCombinedLtoObject();
401 
402   for (auto *Arg : Args.filtered(OPT_wrap))
403     Symtab.wrap(Arg->getValue());
404 
405   if (Config->OutputFile.empty())
406     Config->OutputFile = "a.out";
407 
408   // Write the result to the file.
409   Symtab.scanShlibUndefined();
410   if (Config->GcSections)
411     markLive<ELFT>(&Symtab);
412   if (Config->ICF)
413     doIcf<ELFT>(&Symtab);
414   writeResult<ELFT>(&Symtab);
415 }
416