xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 2a064143)
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   ErrorOr<std::unique_ptr<Archive>> FileOrErr = Archive::create(MB);
74   fatal(FileOrErr, "Failed to parse archive");
75   std::unique_ptr<Archive> File = std::move(*FileOrErr);
76 
77   std::vector<MemoryBufferRef> V;
78   for (const ErrorOr<Archive::Child> &C : File->children()) {
79     fatal(C, "Could not get the child of the archive " + File->getFileName());
80     ErrorOr<MemoryBufferRef> MbOrErr = C->getMemoryBufferRef();
81     fatal(MbOrErr, "Could not get the buffer for a child of the archive " +
82                        File->getFileName());
83     V.push_back(*MbOrErr);
84   }
85   return V;
86 }
87 
88 // Opens and parses a file. Path has to be resolved already.
89 // Newly created memory buffers are owned by this driver.
90 void LinkerDriver::addFile(StringRef Path) {
91   using namespace llvm::sys::fs;
92   log(Path);
93   auto MBOrErr = MemoryBuffer::getFile(Path);
94   if (error(MBOrErr, "cannot open " + Path))
95     return;
96   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
97   MemoryBufferRef MBRef = MB->getMemBufferRef();
98   OwningMBs.push_back(std::move(MB)); // take MB ownership
99 
100   switch (identify_magic(MBRef.getBuffer())) {
101   case file_magic::unknown:
102     Script->read(MBRef);
103     return;
104   case file_magic::archive:
105     if (WholeArchive) {
106       StringRef S = MBRef.getBufferIdentifier();
107       for (MemoryBufferRef MB : getArchiveMembers(MBRef))
108         Files.push_back(createObjectFile(MB, S));
109       return;
110     }
111     Files.push_back(make_unique<ArchiveFile>(MBRef));
112     return;
113   case file_magic::elf_shared_object:
114     if (Config->Relocatable) {
115       error("Attempted static link of dynamic object " + Path);
116       return;
117     }
118     Files.push_back(createSharedFile(MBRef));
119     return;
120   default:
121     Files.push_back(createObjectFile(MBRef));
122   }
123 }
124 
125 // Add a given library by searching it from input search paths.
126 void LinkerDriver::addLibrary(StringRef Name) {
127   std::string Path = searchLibrary(Name);
128   if (Path.empty())
129     error("Unable to find library -l" + Name);
130   else
131     addFile(Path);
132 }
133 
134 // Some command line options or some combinations of them are not allowed.
135 // This function checks for such errors.
136 static void checkOptions(opt::InputArgList &Args) {
137   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
138   // table which is a relatively new feature.
139   if (Config->EMachine == EM_MIPS && Config->GnuHash)
140     error("The .gnu.hash section is not compatible with the MIPS target.");
141 
142   if (Config->EMachine == EM_AMDGPU && !Config->Entry.empty())
143     error("-e option is not valid for AMDGPU.");
144 
145   if (!Config->Relocatable)
146     return;
147 
148   if (Config->Shared)
149     error("-r and -shared may not be used together");
150   if (Config->GcSections)
151     error("-r and --gc-sections may not be used together");
152   if (Config->ICF)
153     error("-r and --icf may not be used together");
154 }
155 
156 static StringRef
157 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
158   if (auto *Arg = Args.getLastArg(Key))
159     return Arg->getValue();
160   return Default;
161 }
162 
163 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
164   for (auto *Arg : Args.filtered(OPT_z))
165     if (Key == Arg->getValue())
166       return true;
167   return false;
168 }
169 
170 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
171   initSymbols();
172 
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->Demangle = !Args.hasArg(OPT_no_demangle);
229   Config->DiscardAll = Args.hasArg(OPT_discard_all);
230   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
231   Config->DiscardNone = Args.hasArg(OPT_discard_none);
232   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
233   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
234   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
235   Config->GcSections = Args.hasArg(OPT_gc_sections);
236   Config->ICF = Args.hasArg(OPT_icf);
237   Config->NoInhibitExec = Args.hasArg(OPT_noinhibit_exec);
238   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
239   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
240   Config->Relocatable = Args.hasArg(OPT_relocatable);
241   Config->Shared = Args.hasArg(OPT_shared);
242   Config->StripAll = Args.hasArg(OPT_strip_all);
243   Config->Verbose = Args.hasArg(OPT_verbose);
244 
245   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
246   Config->Entry = getString(Args, OPT_entry);
247   Config->Fini = getString(Args, OPT_fini, "_fini");
248   Config->Init = getString(Args, OPT_init, "_init");
249   Config->OutputFile = getString(Args, OPT_o);
250   Config->SoName = getString(Args, OPT_soname);
251   Config->Sysroot = getString(Args, OPT_sysroot);
252 
253   Config->ZExecStack = hasZOption(Args, "execstack");
254   Config->ZNodelete = hasZOption(Args, "nodelete");
255   Config->ZNow = hasZOption(Args, "now");
256   Config->ZOrigin = hasZOption(Args, "origin");
257   Config->ZRelro = !hasZOption(Args, "norelro");
258 
259   if (Config->Relocatable)
260     Config->StripAll = false;
261 
262   if (auto *Arg = Args.getLastArg(OPT_O)) {
263     StringRef Val = Arg->getValue();
264     if (Val.getAsInteger(10, Config->Optimize))
265       error("Invalid optimization level");
266   }
267 
268   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
269     StringRef S = Arg->getValue();
270     if (S == "gnu") {
271       Config->GnuHash = true;
272       Config->SysvHash = false;
273     } else if (S == "both") {
274       Config->GnuHash = true;
275     } else if (S != "sysv")
276       error("Unknown hash style: " + S);
277   }
278 
279   for (auto *Arg : Args.filtered(OPT_undefined))
280     Config->Undefined.push_back(Arg->getValue());
281 }
282 
283 void LinkerDriver::createFiles(opt::InputArgList &Args) {
284   for (auto *Arg : Args) {
285     switch (Arg->getOption().getID()) {
286     case OPT_l:
287       addLibrary(Arg->getValue());
288       break;
289     case OPT_INPUT:
290     case OPT_script:
291       addFile(Arg->getValue());
292       break;
293     case OPT_as_needed:
294       Config->AsNeeded = true;
295       break;
296     case OPT_no_as_needed:
297       Config->AsNeeded = false;
298       break;
299     case OPT_Bstatic:
300       Config->Static = true;
301       break;
302     case OPT_Bdynamic:
303       Config->Static = false;
304       break;
305     case OPT_whole_archive:
306       WholeArchive = true;
307       break;
308     case OPT_no_whole_archive:
309       WholeArchive = false;
310       break;
311     }
312   }
313 
314   if (Files.empty() && !HasError)
315     error("no input files.");
316 }
317 
318 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
319   // For LTO
320   InitializeAllTargets();
321   InitializeAllTargetMCs();
322   InitializeAllAsmPrinters();
323 
324   SymbolTable<ELFT> Symtab;
325   std::unique_ptr<TargetInfo> TI(createTarget());
326   Target = TI.get();
327 
328   if (!Config->Shared && !Config->Relocatable) {
329     // Add entry symbol.
330     //
331     // There is no entry symbol for AMDGPU binaries, so skip adding one to avoid
332     // having and undefined symbol.
333     if (Config->Entry.empty() && Config->EMachine != EM_AMDGPU)
334       Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
335 
336     // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
337     // is magical and is used to produce a R_386_GOTPC relocation.
338     // The R_386_GOTPC relocation value doesn't actually depend on the
339     // symbol value, so it could use an index of STN_UNDEF which, according
340     // to the spec, means the symbol value is 0.
341     // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
342     // the object file.
343     // The situation is even stranger on x86_64 where the assembly doesn't
344     // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
345     // an undefined symbol in the .o files.
346     // Given that the symbol is effectively unused, we just create a dummy
347     // hidden one to avoid the undefined symbol error.
348     Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
349   }
350 
351   if (!Config->Entry.empty()) {
352     // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
353     StringRef S = Config->Entry;
354     if (S.getAsInteger(0, Config->EntryAddr))
355       Config->EntrySym = Symtab.addUndefined(S);
356   }
357 
358   if (Config->EMachine == EM_MIPS) {
359     // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
360     // start of function and 'gp' pointer into GOT.
361     Config->MipsGpDisp = Symtab.addIgnored("_gp_disp");
362     // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
363     // pointer. This symbol is used in the code generated by .cpload pseudo-op
364     // in case of using -mno-shared option.
365     // https://sourceware.org/ml/binutils/2004-12/msg00094.html
366     Config->MipsLocalGp = Symtab.addIgnored("__gnu_local_gp");
367 
368     // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
369     // so that it points to an absolute address which is relative to GOT.
370     // See "Global Data Symbols" in Chapter 6 in the following document:
371     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
372     Symtab.addAbsolute("_gp", ElfSym<ELFT>::MipsGp);
373   }
374 
375   for (std::unique_ptr<InputFile> &F : Files)
376     Symtab.addFile(std::move(F));
377   if (HasError)
378     return; // There were duplicate symbols or incompatible files
379 
380   for (StringRef S : Config->Undefined)
381     Symtab.addUndefinedOpt(S);
382 
383   Symtab.addCombinedLtoObject();
384 
385   for (auto *Arg : Args.filtered(OPT_wrap))
386     Symtab.wrap(Arg->getValue());
387 
388   if (Config->OutputFile.empty())
389     Config->OutputFile = "a.out";
390 
391   // Write the result to the file.
392   Symtab.scanShlibUndefined();
393   if (Config->GcSections)
394     markLive<ELFT>(&Symtab);
395   if (Config->ICF)
396     doIcf<ELFT>(&Symtab);
397   writeResult<ELFT>(&Symtab);
398 }
399