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->DiscardAll = Args.hasArg(OPT_discard_all); 189 Config->DiscardLocals = Args.hasArg(OPT_discard_locals); 190 Config->DiscardNone = Args.hasArg(OPT_discard_none); 191 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags); 192 Config->ExportDynamic = Args.hasArg(OPT_export_dynamic); 193 Config->GcSections = Args.hasArg(OPT_gc_sections); 194 Config->NoInhibitExec = Args.hasArg(OPT_noinhibit_exec); 195 Config->NoUndefined = Args.hasArg(OPT_no_undefined); 196 Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections); 197 Config->Shared = Args.hasArg(OPT_shared); 198 Config->StripAll = Args.hasArg(OPT_strip_all); 199 Config->Verbose = Args.hasArg(OPT_verbose); 200 201 Config->DynamicLinker = getString(Args, OPT_dynamic_linker); 202 Config->Entry = getString(Args, OPT_entry); 203 Config->Fini = getString(Args, OPT_fini, "_fini"); 204 Config->Init = getString(Args, OPT_init, "_init"); 205 Config->OutputFile = getString(Args, OPT_o); 206 Config->SoName = getString(Args, OPT_soname); 207 Config->Sysroot = getString(Args, OPT_sysroot); 208 209 Config->ZExecStack = hasZOption(Args, "execstack"); 210 Config->ZNodelete = hasZOption(Args, "nodelete"); 211 Config->ZNow = hasZOption(Args, "now"); 212 Config->ZOrigin = hasZOption(Args, "origin"); 213 Config->ZRelro = !hasZOption(Args, "norelro"); 214 215 if (auto *Arg = Args.getLastArg(OPT_O)) { 216 StringRef Val = Arg->getValue(); 217 if (Val.getAsInteger(10, Config->Optimize)) 218 error("Invalid optimization level"); 219 } 220 221 if (auto *Arg = Args.getLastArg(OPT_hash_style)) { 222 StringRef S = Arg->getValue(); 223 if (S == "gnu") { 224 Config->GnuHash = true; 225 Config->SysvHash = false; 226 } else if (S == "both") { 227 Config->GnuHash = true; 228 } else if (S != "sysv") 229 error("Unknown hash style: " + S); 230 } 231 232 for (auto *Arg : Args.filtered(OPT_undefined)) 233 Config->Undefined.push_back(Arg->getValue()); 234 } 235 236 void LinkerDriver::createFiles(opt::InputArgList &Args) { 237 for (auto *Arg : Args) { 238 switch (Arg->getOption().getID()) { 239 case OPT_l: 240 addFile(searchLibrary(Arg->getValue())); 241 break; 242 case OPT_INPUT: 243 case OPT_script: 244 addFile(Arg->getValue()); 245 break; 246 case OPT_as_needed: 247 Config->AsNeeded = true; 248 break; 249 case OPT_no_as_needed: 250 Config->AsNeeded = false; 251 break; 252 case OPT_Bstatic: 253 Config->Static = true; 254 break; 255 case OPT_Bdynamic: 256 Config->Static = false; 257 break; 258 case OPT_whole_archive: 259 WholeArchive = true; 260 break; 261 case OPT_no_whole_archive: 262 WholeArchive = false; 263 break; 264 } 265 } 266 267 if (Files.empty()) 268 error("no input files."); 269 } 270 271 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) { 272 SymbolTable<ELFT> Symtab; 273 Target.reset(createTarget()); 274 275 if (!Config->Shared) { 276 // Add entry symbol. 277 // 278 // There is no entry symbol for AMDGPU binaries, so skip adding one to avoid 279 // having and undefined symbol. 280 if (Config->Entry.empty() && Config->EMachine != EM_AMDGPU) 281 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; 282 283 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol 284 // is magical and is used to produce a R_386_GOTPC relocation. 285 // The R_386_GOTPC relocation value doesn't actually depend on the 286 // symbol value, so it could use an index of STN_UNDEF which, according 287 // to the spec, means the symbol value is 0. 288 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in 289 // the object file. 290 // The situation is even stranger on x86_64 where the assembly doesn't 291 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as 292 // an undefined symbol in the .o files. 293 // Given that the symbol is effectively unused, we just create a dummy 294 // hidden one to avoid the undefined symbol error. 295 Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_"); 296 } 297 298 if (!Config->Entry.empty()) { 299 // Set either EntryAddr (if S is a number) or EntrySym (otherwise). 300 StringRef S = Config->Entry; 301 if (S.getAsInteger(0, Config->EntryAddr)) 302 Config->EntrySym = Symtab.addUndefined(S); 303 } 304 305 if (Config->EMachine == EM_MIPS) { 306 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between 307 // start of function and gp pointer into GOT. Use 'strong' variant of 308 // the addIgnored to prevent '_gp_disp' substitution. 309 Config->MipsGpDisp = Symtab.addIgnoredStrong("_gp_disp"); 310 311 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer 312 // so that it points to an absolute address which is relative to GOT. 313 // See "Global Data Symbols" in Chapter 6 in the following document: 314 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 315 Symtab.addAbsolute("_gp", ElfSym<ELFT>::MipsGp); 316 } 317 318 for (std::unique_ptr<InputFile> &F : Files) 319 Symtab.addFile(std::move(F)); 320 321 for (StringRef S : Config->Undefined) 322 Symtab.addUndefinedOpt(S); 323 324 for (auto *Arg : Args.filtered(OPT_wrap)) 325 Symtab.wrap(Arg->getValue()); 326 327 if (Config->OutputFile.empty()) 328 Config->OutputFile = "a.out"; 329 330 // Write the result to the file. 331 Symtab.scanShlibUndefined(); 332 if (Config->GcSections) 333 markLive<ELFT>(&Symtab); 334 writeResult<ELFT>(&Symtab); 335 } 336