xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision d5658b08)
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 *lld::elf2::Config;
30 LinkerDriver *lld::elf2::Driver;
31 
32 void lld::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")
46     return {ELF32BEKind, EM_PPC};
47   if (S == "elf64ppc")
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   error("Unknown emulation: " + S);
56 }
57 
58 // Opens and parses a file. Path has to be resolved already.
59 // Newly created memory buffers are owned by this driver.
60 void LinkerDriver::addFile(StringRef Path) {
61   using namespace llvm::sys::fs;
62   if (Config->Verbose)
63     llvm::outs() << Path << "\n";
64   auto MBOrErr = MemoryBuffer::getFile(Path);
65   error(MBOrErr, "cannot open " + Path);
66   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
67   MemoryBufferRef MBRef = MB->getMemBufferRef();
68   OwningMBs.push_back(std::move(MB)); // take MB ownership
69 
70   switch (identify_magic(MBRef.getBuffer())) {
71   case file_magic::unknown:
72     readLinkerScript(&Alloc, MBRef);
73     return;
74   case file_magic::archive:
75     if (WholeArchive) {
76       auto File = make_unique<ArchiveFile>(MBRef);
77       for (MemoryBufferRef &MB : File->getMembers())
78         Files.push_back(createELFFile<ObjectFile>(MB));
79       OwningArchives.emplace_back(std::move(File));
80       return;
81     }
82     Files.push_back(make_unique<ArchiveFile>(MBRef));
83     return;
84   case file_magic::elf_shared_object:
85     Files.push_back(createELFFile<SharedFile>(MBRef));
86     return;
87   default:
88     Files.push_back(createELFFile<ObjectFile>(MBRef));
89   }
90 }
91 
92 static StringRef
93 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
94   if (auto *Arg = Args.getLastArg(Key))
95     return Arg->getValue();
96   return Default;
97 }
98 
99 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
100   for (auto *Arg : Args.filtered(OPT_z))
101     if (Key == Arg->getValue())
102       return true;
103   return false;
104 }
105 
106 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
107   initSymbols();
108 
109   opt::InputArgList Args = parseArgs(&Alloc, ArgsArr);
110   createFiles(Args);
111 
112   // Traditional linkers can generate re-linkable object files instead
113   // of executables or DSOs. We don't support that since the feature
114   // does not seem to provide more value than the static archiver.
115   if (Args.hasArg(OPT_relocatable))
116     error("-r option is not supported. Use 'ar' command instead.");
117 
118   switch (Config->EKind) {
119   case ELF32LEKind:
120     link<ELF32LE>(Args);
121     return;
122   case ELF32BEKind:
123     link<ELF32BE>(Args);
124     return;
125   case ELF64LEKind:
126     link<ELF64LE>(Args);
127     return;
128   case ELF64BEKind:
129     link<ELF64BE>(Args);
130     return;
131   default:
132     error("-m or at least a .o file required");
133   }
134 }
135 
136 void LinkerDriver::createFiles(opt::InputArgList &Args) {
137   for (auto *Arg : Args.filtered(OPT_L))
138     Config->SearchPaths.push_back(Arg->getValue());
139 
140   std::vector<StringRef> RPaths;
141   for (auto *Arg : Args.filtered(OPT_rpath))
142     RPaths.push_back(Arg->getValue());
143   if (!RPaths.empty())
144     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
145 
146   if (auto *Arg = Args.getLastArg(OPT_m)) {
147     StringRef S = Arg->getValue();
148     std::pair<ELFKind, uint16_t> P = parseEmulation(S);
149     Config->EKind = P.first;
150     Config->EMachine = P.second;
151     Config->Emulation = S;
152   }
153 
154   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
155   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
156   Config->DiscardAll = Args.hasArg(OPT_discard_all);
157   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
158   Config->DiscardNone = Args.hasArg(OPT_discard_none);
159   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
160   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
161   Config->GcSections = Args.hasArg(OPT_gc_sections);
162   Config->NoInhibitExec = Args.hasArg(OPT_noinhibit_exec);
163   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
164   Config->Shared = Args.hasArg(OPT_shared);
165   Config->StripAll = Args.hasArg(OPT_strip_all);
166   Config->Verbose = Args.hasArg(OPT_verbose);
167 
168   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
169   Config->Entry = getString(Args, OPT_entry);
170   Config->Fini = getString(Args, OPT_fini, "_fini");
171   Config->Init = getString(Args, OPT_init, "_init");
172   Config->OutputFile = getString(Args, OPT_o);
173   Config->SoName = getString(Args, OPT_soname);
174   Config->Sysroot = getString(Args, OPT_sysroot);
175 
176   Config->ZNodelete = hasZOption(Args, "nodelete");
177   Config->ZNow = hasZOption(Args, "now");
178   Config->ZOrigin = hasZOption(Args, "origin");
179 
180   if (auto *Arg = Args.getLastArg(OPT_O)) {
181     StringRef Val = Arg->getValue();
182     if (Val.getAsInteger(10, Config->Optimize))
183       error("Invalid optimization level");
184   }
185 
186   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
187     StringRef S = Arg->getValue();
188     if (S == "gnu") {
189       Config->GnuHash = true;
190       Config->SysvHash = false;
191     } else if (S == "both") {
192       Config->GnuHash = true;
193     } else if (S != "sysv")
194       error("Unknown hash style: " + S);
195   }
196 
197   for (auto *Arg : Args.filtered(OPT_undefined))
198     Config->Undefined.push_back(Arg->getValue());
199 
200   for (auto *Arg : Args) {
201     switch (Arg->getOption().getID()) {
202     case OPT_l:
203       addFile(searchLibrary(Arg->getValue()));
204       break;
205     case OPT_INPUT:
206     case OPT_script:
207       addFile(Arg->getValue());
208       break;
209     case OPT_as_needed:
210       Config->AsNeeded = true;
211       break;
212     case OPT_no_as_needed:
213       Config->AsNeeded = false;
214       break;
215     case OPT_Bstatic:
216       Config->Static = true;
217       break;
218     case OPT_Bdynamic:
219       Config->Static = false;
220       break;
221     case OPT_whole_archive:
222       WholeArchive = true;
223       break;
224     case OPT_no_whole_archive:
225       WholeArchive = false;
226       break;
227     }
228   }
229 
230   if (Files.empty())
231     error("no input files.");
232 
233   if (Config->GnuHash && Config->EMachine == EM_MIPS)
234     error("The .gnu.hash section is not compatible with the MIPS target.");
235 }
236 
237 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
238   SymbolTable<ELFT> Symtab;
239   Target.reset(createTarget());
240 
241   if (!Config->Shared) {
242     // Add entry symbol.
243     if (Config->Entry.empty())
244       Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
245 
246     // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
247     StringRef S = Config->Entry;
248     if (S.getAsInteger(0, Config->EntryAddr))
249       Config->EntrySym = Symtab.addUndefined(S);
250 
251     // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
252     // is magical and is used to produce a R_386_GOTPC relocation.
253     // The R_386_GOTPC relocation value doesn't actually depend on the
254     // symbol value, so it could use an index of STN_UNDEF which, according
255     // to the spec, means the symbol value is 0.
256     // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
257     // the object file.
258     // The situation is even stranger on x86_64 where the assembly doesn't
259     // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
260     // an undefined symbol in the .o files.
261     // Given that the symbol is effectively unused, we just create a dummy
262     // hidden one to avoid the undefined symbol error.
263     Symtab.addIgnoredSym("_GLOBAL_OFFSET_TABLE_");
264   }
265 
266   // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
267   // so that it points to an absolute address which is relative to GOT.
268   // See "Global Data Symbols" in Chapter 6 in the following document:
269   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
270   if (Config->EMachine == EM_MIPS)
271     Symtab.addAbsoluteSym("_gp", DefinedAbsolute<ELFT>::MipsGp);
272 
273   for (std::unique_ptr<InputFile> &F : Files)
274     Symtab.addFile(std::move(F));
275 
276   for (StringRef S : Config->Undefined)
277     Symtab.addUndefinedOpt(S);
278 
279   // "-z execstack" value is inferred from input object files (it's false
280   // if all input files have .note.GNU-stack section). Explicit options
281   // override the inferred default value.
282   if (hasZOption(Args, "execstack"))
283     Config->ZExecStack = true;
284   if (hasZOption(Args, "noexecstack"))
285     Config->ZExecStack = false;
286 
287   if (Config->OutputFile.empty())
288     Config->OutputFile = "a.out";
289 
290   // Write the result to the file.
291   Symtab.scanShlibUndefined();
292   if (Config->GcSections)
293     markLive<ELFT>(&Symtab);
294   writeResult<ELFT>(&Symtab);
295 }
296