xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 09178283)
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   Config->Emulation = S;
42   if (S == "elf32btsmip")
43     return {ELF32BEKind, EM_MIPS};
44   if (S == "elf32ltsmip")
45     return {ELF32LEKind, EM_MIPS};
46   if (S == "elf32ppc")
47     return {ELF32BEKind, EM_PPC};
48   if (S == "elf64ppc")
49     return {ELF64BEKind, EM_PPC64};
50   if (S == "elf_i386")
51     return {ELF32LEKind, EM_386};
52   if (S == "elf_x86_64")
53     return {ELF64LEKind, EM_X86_64};
54   error("Unknown emulation: " + S);
55 }
56 
57 // Opens and parses a file. Path has to be resolved already.
58 // Newly created memory buffers are owned by this driver.
59 void LinkerDriver::addFile(StringRef Path) {
60   using namespace llvm::sys::fs;
61   if (Config->Verbose)
62     llvm::outs() << Path << "\n";
63   auto MBOrErr = MemoryBuffer::getFile(Path);
64   error(MBOrErr, "cannot open " + Path);
65   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
66   MemoryBufferRef MBRef = MB->getMemBufferRef();
67   OwningMBs.push_back(std::move(MB)); // take MB ownership
68 
69   switch (identify_magic(MBRef.getBuffer())) {
70   case file_magic::unknown:
71     readLinkerScript(&Alloc, MBRef);
72     return;
73   case file_magic::archive:
74     if (WholeArchive) {
75       auto File = make_unique<ArchiveFile>(MBRef);
76       for (MemoryBufferRef &MB : File->getMembers())
77         Files.push_back(createELFFile<ObjectFile>(MB));
78       OwningArchives.emplace_back(std::move(File));
79       return;
80     }
81     Files.push_back(make_unique<ArchiveFile>(MBRef));
82     return;
83   case file_magic::elf_shared_object:
84     Files.push_back(createELFFile<SharedFile>(MBRef));
85     return;
86   default:
87     Files.push_back(createELFFile<ObjectFile>(MBRef));
88   }
89 }
90 
91 static StringRef
92 getString(opt::InputArgList &Args, unsigned Key, StringRef Default = "") {
93   if (auto *Arg = Args.getLastArg(Key))
94     return Arg->getValue();
95   return Default;
96 }
97 
98 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
99   initSymbols();
100 
101   opt::InputArgList Args = parseArgs(&Alloc, ArgsArr);
102   createFiles(Args);
103 
104   switch (Config->EKind) {
105   case ELF32LEKind:
106     link<ELF32LE>(Args);
107     return;
108   case ELF32BEKind:
109     link<ELF32BE>(Args);
110     return;
111   case ELF64LEKind:
112     link<ELF64LE>(Args);
113     return;
114   case ELF64BEKind:
115     link<ELF64BE>(Args);
116     return;
117   default:
118     error("-m or at least a .o file required");
119   }
120 }
121 
122 void LinkerDriver::createFiles(opt::InputArgList &Args) {
123   for (auto *Arg : Args.filtered(OPT_L))
124     Config->SearchPaths.push_back(Arg->getValue());
125 
126   std::vector<StringRef> RPaths;
127   for (auto *Arg : Args.filtered(OPT_rpath))
128     RPaths.push_back(Arg->getValue());
129   if (!RPaths.empty())
130     Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
131 
132   if (auto *Arg = Args.getLastArg(OPT_m)) {
133     std::pair<ELFKind, uint16_t> P = parseEmulation(Arg->getValue());
134     Config->EKind = P.first;
135     Config->EMachine = P.second;
136   }
137 
138   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
139   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
140   Config->DiscardAll = Args.hasArg(OPT_discard_all);
141   Config->DiscardLocals = Args.hasArg(OPT_discard_locals);
142   Config->DiscardNone = Args.hasArg(OPT_discard_none);
143   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
144   Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
145   Config->NoInhibitExec = Args.hasArg(OPT_noinhibit_exec);
146   Config->NoUndefined = Args.hasArg(OPT_no_undefined);
147   Config->Shared = Args.hasArg(OPT_shared);
148   Config->Verbose = Args.hasArg(OPT_verbose);
149 
150   Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
151   Config->Entry = getString(Args, OPT_entry);
152   Config->Fini = getString(Args, OPT_fini, "_fini");
153   Config->Init = getString(Args, OPT_init, "_init");
154   Config->OutputFile = getString(Args, OPT_o);
155   Config->SoName = getString(Args, OPT_soname);
156   Config->Sysroot = getString(Args, OPT_sysroot);
157 
158   for (auto *Arg : Args.filtered(OPT_z))
159     if (Arg->getValue() == StringRef("now"))
160       Config->ZNow = true;
161 
162   for (auto *Arg : Args) {
163     switch (Arg->getOption().getID()) {
164     case OPT_l:
165       addFile(searchLibrary(Arg->getValue()));
166       break;
167     case OPT_INPUT:
168     case OPT_script:
169       addFile(Arg->getValue());
170       break;
171     case OPT_as_needed:
172       Config->AsNeeded = true;
173       break;
174     case OPT_no_as_needed:
175       Config->AsNeeded = false;
176       break;
177     case OPT_Bstatic:
178       Config->Static = true;
179       break;
180     case OPT_Bdynamic:
181       Config->Static = false;
182       break;
183     case OPT_whole_archive:
184       WholeArchive = true;
185       break;
186     case OPT_no_whole_archive:
187       WholeArchive = false;
188       break;
189     }
190   }
191 
192   if (Files.empty())
193     error("no input files.");
194 }
195 
196 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
197   SymbolTable<ELFT> Symtab;
198   Target.reset(createTarget());
199 
200   if (!Config->Shared) {
201     // Add entry symbol.
202     if (Config->Entry.empty())
203       Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
204 
205     // Set either EntryAddr (if S is a number) or EntrySym (otherwise).
206     StringRef S = Config->Entry;
207     if (S.getAsInteger(0, Config->EntryAddr))
208       Config->EntrySym = Symtab.addUndefined(S);
209 
210     // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
211     // is magical and is used to produce a R_386_GOTPC relocation.
212     // The R_386_GOTPC relocation value doesn't actually depend on the
213     // symbol value, so it could use an index of STN_UNDEF which, according
214     // to the spec, means the symbol value is 0.
215     // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
216     // the object file.
217     // The situation is even stranger on x86_64 where the assembly doesn't
218     // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
219     // an undefined symbol in the .o files.
220     // Given that the symbol is effectively unused, we just create a dummy
221     // hidden one to avoid the undefined symbol error.
222     Symtab.addIgnoredSym("_GLOBAL_OFFSET_TABLE_");
223   }
224 
225   for (std::unique_ptr<InputFile> &F : Files)
226     Symtab.addFile(std::move(F));
227 
228   for (auto *Arg : Args.filtered(OPT_undefined))
229     Symtab.addUndefinedOpt(Arg->getValue());
230 
231   if (Config->OutputFile.empty())
232     Config->OutputFile = "a.out";
233 
234   // Write the result to the file.
235   Symtab.scanShlibUndefined();
236   writeResult<ELFT>(&Symtab);
237 }
238