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