xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision fcef3e46)
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->Pie && Config->Shared)
148     error("-shared and -pie may not be used together");
149 
150   if (!Config->Relocatable)
151     return;
152 
153   if (Config->Shared)
154     error("-r and -shared may not be used together");
155   if (Config->GcSections)
156     error("-r and --gc-sections may not be used together");
157   if (Config->ICF)
158     error("-r and --icf may not be used together");
159   if (Config->Pie)
160     error("-r and -pie may not be used together");
161 }
162 
163 static StringRef
164 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
165   if (auto *Arg = Args.getLastArg(Key))
166     return Arg->getValue();
167   return Default;
168 }
169 
170 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
171   for (auto *Arg : Args.filtered(OPT_z))
172     if (Key == Arg->getValue())
173       return true;
174   return false;
175 }
176 
177 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
178   ELFOptTable Parser;
179   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
180   if (Args.hasArg(OPT_help)) {
181     printHelp(ArgsArr[0]);
182     return;
183   }
184   if (Args.hasArg(OPT_version)) {
185     printVersion();
186     return;
187   }
188 
189   readConfigs(Args);
190   createFiles(Args);
191   checkOptions(Args);
192   if (HasError)
193     return;
194 
195   switch (Config->EKind) {
196   case ELF32LEKind:
197     link<ELF32LE>(Args);
198     return;
199   case ELF32BEKind:
200     link<ELF32BE>(Args);
201     return;
202   case ELF64LEKind:
203     link<ELF64LE>(Args);
204     return;
205   case ELF64BEKind:
206     link<ELF64BE>(Args);
207     return;
208   default:
209     error("-m or at least a .o file required");
210   }
211 }
212 
213 // Initializes Config members by the command line options.
214 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
215   for (auto *Arg : Args.filtered(OPT_L))
216     Config->SearchPaths.push_back(Arg->getValue());
217 
218   std::vector<StringRef> RPaths;
219   for (auto *Arg : Args.filtered(OPT_rpath))
220     RPaths.push_back(Arg->getValue());
221   if (!RPaths.empty())
222     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
223 
224   if (auto *Arg = Args.getLastArg(OPT_m)) {
225     // Parse ELF{32,64}{LE,BE} and CPU type.
226     StringRef S = Arg->getValue();
227     std::tie(Config->EKind, Config->EMachine) = parseEmulation(S);
228     Config->Emulation = S;
229   }
230 
231   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
232   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
233   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
234   Config->BuildId = Args.hasArg(OPT_build_id);
235   Config->Demangle = !Args.hasArg(OPT_no_demangle);
236   Config->DiscardAll = Args.hasArg(OPT_discard_all);
237   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
238   Config->DiscardNone = Args.hasArg(OPT_discard_none);
239   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
240   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
241   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
242   Config->GcSections = Args.hasArg(OPT_gc_sections);
243   Config->ICF = Args.hasArg(OPT_icf);
244   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
245   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
246   Config->Pie = Args.hasArg(OPT_pie);
247   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
248   Config->Relocatable = Args.hasArg(OPT_relocatable);
249   Config->SaveTemps = Args.hasArg(OPT_save_temps);
250   Config->Shared = Args.hasArg(OPT_shared);
251   Config->StripAll = Args.hasArg(OPT_strip_all);
252   Config->Threads = Args.hasArg(OPT_threads);
253   Config->Verbose = Args.hasArg(OPT_verbose);
254   Config->WarnCommon = Args.hasArg(OPT_warn_common);
255 
256   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
257   Config->Entry = getString(Args, OPT_entry);
258   Config->Fini = getString(Args, OPT_fini, "_fini");
259   Config->Init = getString(Args, OPT_init, "_init");
260   Config->OutputFile = getString(Args, OPT_o);
261   Config->SoName = getString(Args, OPT_soname);
262   Config->Sysroot = getString(Args, OPT_sysroot);
263 
264   Config->ZExecStack = hasZOption(Args, "execstack");
265   Config->ZNodelete = hasZOption(Args, "nodelete");
266   Config->ZNow = hasZOption(Args, "now");
267   Config->ZOrigin = hasZOption(Args, "origin");
268   Config->ZRelro = !hasZOption(Args, "norelro");
269 
270   Config->Pic = Config->Pie || Config->Shared;
271 
272   if (Config->Relocatable)
273     Config->StripAll = false;
274 
275   if (auto *Arg = Args.getLastArg(OPT_O)) {
276     StringRef Val = Arg->getValue();
277     if (Val.getAsInteger(10, Config->Optimize))
278       error("invalid optimization level");
279   }
280 
281   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
282     StringRef S = Arg->getValue();
283     if (S == "gnu") {
284       Config->GnuHash = true;
285       Config->SysvHash = false;
286     } else if (S == "both") {
287       Config->GnuHash = true;
288     } else if (S != "sysv")
289       error("unknown hash style: " + S);
290   }
291 
292   for (auto *Arg : Args.filtered(OPT_undefined))
293     Config->Undefined.push_back(Arg->getValue());
294 }
295 
296 void LinkerDriver::createFiles(opt::InputArgList &Args) {
297   for (auto *Arg : Args) {
298     switch (Arg->getOption().getID()) {
299     case OPT_l:
300       addLibrary(Arg->getValue());
301       break;
302     case OPT_INPUT:
303     case OPT_script:
304       addFile(Arg->getValue());
305       break;
306     case OPT_as_needed:
307       Config->AsNeeded = true;
308       break;
309     case OPT_no_as_needed:
310       Config->AsNeeded = false;
311       break;
312     case OPT_Bstatic:
313       Config->Static = true;
314       break;
315     case OPT_Bdynamic:
316       Config->Static = false;
317       break;
318     case OPT_whole_archive:
319       WholeArchive = true;
320       break;
321     case OPT_no_whole_archive:
322       WholeArchive = false;
323       break;
324     }
325   }
326 
327   if (Files.empty() && !HasError)
328     error("no input files.");
329 }
330 
331 template <class ELFT> static void initSymbols() {
332   ElfSym<ELFT>::Etext.setBinding(STB_GLOBAL);
333   ElfSym<ELFT>::Edata.setBinding(STB_GLOBAL);
334   ElfSym<ELFT>::End.setBinding(STB_GLOBAL);
335   ElfSym<ELFT>::Ignored.setBinding(STB_WEAK);
336   ElfSym<ELFT>::Ignored.setVisibility(STV_HIDDEN);
337 }
338 
339 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
340   // For LTO
341   InitializeAllTargets();
342   InitializeAllTargetMCs();
343   InitializeAllAsmPrinters();
344   InitializeAllAsmParsers();
345 
346   initSymbols<ELFT>();
347 
348   SymbolTable<ELFT> Symtab;
349   std::unique_ptr<TargetInfo> TI(createTarget());
350   Target = TI.get();
351 
352   Config->Rela = ELFT::Is64Bits;
353 
354   // Add entry symbol.
355   // There is no entry symbol for AMDGPU binaries, so skip adding one to avoid
356   // having and undefined symbol.
357   if (Config->Entry.empty() && !Config->Shared && !Config->Relocatable &&
358       Config->EMachine != EM_AMDGPU)
359     Config->Entry = Config->EMachine == EM_MIPS ? "__start" : "_start";
360 
361   // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
362   // is magical and is used to produce a R_386_GOTPC relocation.
363   // The R_386_GOTPC relocation value doesn't actually depend on the
364   // symbol value, so it could use an index of STN_UNDEF which, according
365   // to the spec, means the symbol value is 0.
366   // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
367   // the object file.
368   // The situation is even stranger on x86_64 where the assembly doesn't
369   // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
370   // an undefined symbol in the .o files.
371   // Given that the symbol is effectively unused, we just create a dummy
372   // hidden one to avoid the undefined symbol error.
373   if (!Config->Relocatable)
374     Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
375 
376   if (!Config->Entry.empty()) {
377     // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
378     StringRef S = Config->Entry;
379     if (S.getAsInteger(0, Config->EntryAddr))
380       Config->EntrySym = Symtab.addUndefined(S);
381   }
382 
383   if (Config->EMachine == EM_MIPS) {
384     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
385     // start of function and 'gp' pointer into GOT.
386     Config->MipsGpDisp = Symtab.addIgnored("_gp_disp");
387     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
388     // pointer. This symbol is used in the code generated by .cpload pseudo-op
389     // in case of using -mno-shared option.
390     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
391     Config->MipsLocalGp = Symtab.addIgnored("__gnu_local_gp");
392 
393     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
394     // so that it points to an absolute address which is relative to GOT.
395     // See "Global Data Symbols" in Chapter 6 in the following document:
396     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
397     Symtab.addAbsolute("_gp", ElfSym<ELFT>::MipsGp);
398   }
399 
400   for (std::unique_ptr<InputFile> &F : Files)
401     Symtab.addFile(std::move(F));
402   if (HasError)
403     return; // There were duplicate symbols or incompatible files
404 
405   for (StringRef S : Config->Undefined)
406     Symtab.addUndefinedOpt(S);
407 
408   Symtab.addCombinedLtoObject();
409 
410   for (auto *Arg : Args.filtered(OPT_wrap))
411     Symtab.wrap(Arg->getValue());
412 
413   if (Config->OutputFile.empty())
414     Config->OutputFile = "a.out";
415 
416   // Write the result to the file.
417   Symtab.scanShlibUndefined();
418   if (Config->GcSections)
419     markLive<ELFT>(&Symtab);
420   if (Config->ICF)
421     doIcf<ELFT>(&Symtab);
422   writeResult<ELFT>(&Symtab);
423 }
424