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