1 //===- DriverUtils.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 // This file contains utility functions for the driver. Because there 11 // are so many small functions, we created this separate file to make 12 // Driver.cpp less cluttered. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "Driver.h" 17 #include "lld/Common/ErrorHandler.h" 18 #include "lld/Common/Memory.h" 19 #include "lld/Common/Reproduce.h" 20 #include "lld/Common/Version.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/Option/Option.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/FileSystem.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/Process.h" 29 30 using namespace llvm; 31 using namespace llvm::sys; 32 33 using namespace lld; 34 using namespace lld::elf; 35 36 // Create OptTable 37 38 // Create prefix string literals used in Options.td 39 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; 40 #include "Options.inc" 41 #undef PREFIX 42 43 // Create table mapping all options defined in Options.td 44 static const opt::OptTable::Info OptInfo[] = { 45 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 46 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \ 47 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 48 #include "Options.inc" 49 #undef OPTION 50 }; 51 52 ELFOptTable::ELFOptTable() : OptTable(OptInfo) {} 53 54 // Set color diagnostics according to -color-diagnostics={auto,always,never} 55 // or -no-color-diagnostics flags. 56 static void handleColorDiagnostics(opt::InputArgList &Args) { 57 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq, 58 OPT_no_color_diagnostics); 59 if (!Arg) 60 return; 61 else if (Arg->getOption().getID() == OPT_color_diagnostics) 62 errorHandler().ColorDiagnostics = true; 63 else if (Arg->getOption().getID() == OPT_no_color_diagnostics) 64 errorHandler().ColorDiagnostics = false; 65 else { 66 StringRef S = Arg->getValue(); 67 if (S == "always") 68 errorHandler().ColorDiagnostics = true; 69 else if (S == "never") 70 errorHandler().ColorDiagnostics = false; 71 else if (S != "auto") 72 error("unknown option: -color-diagnostics=" + S); 73 } 74 } 75 76 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) { 77 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) { 78 StringRef S = Arg->getValue(); 79 if (S != "windows" && S != "posix") 80 error("invalid response file quoting: " + S); 81 if (S == "windows") 82 return cl::TokenizeWindowsCommandLine; 83 return cl::TokenizeGNUCommandLine; 84 } 85 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32) 86 return cl::TokenizeWindowsCommandLine; 87 return cl::TokenizeGNUCommandLine; 88 } 89 90 // Parses a given list of options. 91 opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) { 92 // Make InputArgList from string vectors. 93 unsigned MissingIndex; 94 unsigned MissingCount; 95 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size()); 96 97 // We need to get the quoting style for response files before parsing all 98 // options so we parse here before and ignore all the options but 99 // --rsp-quoting. 100 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount); 101 102 // Expand response files (arguments in the form of @<filename>) 103 // and then parse the argument again. 104 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec); 105 Args = this->ParseArgs(Vec, MissingIndex, MissingCount); 106 107 handleColorDiagnostics(Args); 108 if (MissingCount) 109 error(Twine(Args.getArgString(MissingIndex)) + ": missing argument"); 110 111 for (auto *Arg : Args.filtered(OPT_UNKNOWN)) 112 error("unknown argument: " + Arg->getSpelling()); 113 return Args; 114 } 115 116 void elf::printHelp(const char *Argv0) { 117 ELFOptTable Table; 118 Table.PrintHelp(outs(), Argv0, "lld", false /*ShowHidden*/, 119 true /*ShowAllAliases*/); 120 outs() << "\n"; 121 122 // Scripts generated by Libtool versions up to at least 2.4.6 (the most 123 // recent version as of March 2017) expect /: supported targets:.* elf/ 124 // in a message for the -help option. If it doesn't match, the scripts 125 // assume that the linker doesn't support very basic features such as 126 // shared libraries. Therefore, we need to print out at least "elf". 127 // Here, we print out all the targets that we support. 128 outs() << Argv0 << ": supported targets: " 129 << "elf32-i386 elf32-iamcu elf32-littlearm elf32-ntradbigmips " 130 << "elf32-ntradlittlemips elf32-powerpc elf32-tradbigmips " 131 << "elf32-tradlittlemips elf32-x86-64 " 132 << "elf64-amdgpu elf64-littleaarch64 elf64-powerpc elf64-tradbigmips " 133 << "elf64-tradlittlemips elf64-x86-64\n"; 134 } 135 136 // Reconstructs command line arguments so that so that you can re-run 137 // the same command with the same inputs. This is for --reproduce. 138 std::string elf::createResponseFile(const opt::InputArgList &Args) { 139 SmallString<0> Data; 140 raw_svector_ostream OS(Data); 141 OS << "--chroot .\n"; 142 143 // Copy the command line to the output while rewriting paths. 144 for (auto *Arg : Args) { 145 switch (Arg->getOption().getUnaliasedOption().getID()) { 146 case OPT_reproduce: 147 break; 148 case OPT_INPUT: 149 OS << quote(rewritePath(Arg->getValue())) << "\n"; 150 break; 151 case OPT_o: 152 // If -o path contains directories, "lld @response.txt" will likely 153 // fail because the archive we are creating doesn't contain empty 154 // directories for the output path (-o doesn't create directories). 155 // Strip directories to prevent the issue. 156 OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n"; 157 break; 158 case OPT_dynamic_list: 159 case OPT_library_path: 160 case OPT_rpath: 161 case OPT_script: 162 case OPT_symbol_ordering_file: 163 case OPT_sysroot: 164 case OPT_version_script: 165 OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue())) 166 << "\n"; 167 break; 168 default: 169 OS << toString(Arg) << "\n"; 170 } 171 } 172 return Data.str(); 173 } 174 175 // Find a file by concatenating given paths. If a resulting path 176 // starts with "=", the character is replaced with a --sysroot value. 177 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) { 178 SmallString<128> S; 179 if (Path1.startswith("=")) 180 path::append(S, Config->Sysroot, Path1.substr(1), Path2); 181 else 182 path::append(S, Path1, Path2); 183 184 if (fs::exists(S)) 185 return S.str().str(); 186 return None; 187 } 188 189 Optional<std::string> elf::findFromSearchPaths(StringRef Path) { 190 for (StringRef Dir : Config->SearchPaths) 191 if (Optional<std::string> S = findFile(Dir, Path)) 192 return S; 193 return None; 194 } 195 196 // This is for -lfoo. We'll look for libfoo.so or libfoo.a from 197 // search paths. 198 Optional<std::string> elf::searchLibrary(StringRef Name) { 199 if (Name.startswith(":")) 200 return findFromSearchPaths(Name.substr(1)); 201 202 for (StringRef Dir : Config->SearchPaths) { 203 if (!Config->Static) 204 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so")) 205 return S; 206 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) 207 return S; 208 } 209 return None; 210 } 211 212 // If a linker script doesn't exist in the current directory, we also look for 213 // the script in the '-L' search paths. This matches the behaviour of both '-T' 214 // and linker script INPUT() directives in ld.bfd. 215 Optional<std::string> elf::searchLinkerScript(StringRef Name) { 216 if (fs::exists(Name)) 217 return Name.str(); 218 return findFromSearchPaths(Name); 219 } 220