1 //===- DriverUtils.cpp ----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Config.h" 10 #include "Driver.h" 11 #include "InputFiles.h" 12 #include "ObjC.h" 13 14 #include "lld/Common/Args.h" 15 #include "lld/Common/ErrorHandler.h" 16 #include "lld/Common/Memory.h" 17 #include "lld/Common/Reproduce.h" 18 #include "llvm/ADT/CachedHashString.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/Bitcode/BitcodeReader.h" 21 #include "llvm/LTO/LTO.h" 22 #include "llvm/Option/Arg.h" 23 #include "llvm/Option/ArgList.h" 24 #include "llvm/Option/Option.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/Path.h" 27 #include "llvm/TextAPI/MachO/InterfaceFile.h" 28 #include "llvm/TextAPI/MachO/TextAPIReader.h" 29 30 using namespace llvm; 31 using namespace llvm::MachO; 32 using namespace llvm::opt; 33 using namespace llvm::sys; 34 using namespace lld; 35 using namespace lld::macho; 36 37 // Create prefix string literals used in Options.td 38 #define PREFIX(NAME, VALUE) const char *NAME[] = VALUE; 39 #include "Options.inc" 40 #undef PREFIX 41 42 // Create table mapping all options defined in Options.td 43 static const OptTable::Info optInfo[] = { 44 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 45 {X1, X2, X10, X11, OPT_##ID, Option::KIND##Class, \ 46 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 47 #include "Options.inc" 48 #undef OPTION 49 }; 50 51 MachOOptTable::MachOOptTable() : OptTable(optInfo) {} 52 53 // Set color diagnostics according to --color-diagnostics={auto,always,never} 54 // or --no-color-diagnostics flags. 55 static void handleColorDiagnostics(InputArgList &args) { 56 const Arg *arg = 57 args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq, 58 OPT_no_color_diagnostics); 59 if (!arg) 60 return; 61 if (arg->getOption().getID() == OPT_color_diagnostics) { 62 lld::errs().enable_colors(true); 63 } else if (arg->getOption().getID() == OPT_no_color_diagnostics) { 64 lld::errs().enable_colors(false); 65 } else { 66 StringRef s = arg->getValue(); 67 if (s == "always") 68 lld::errs().enable_colors(true); 69 else if (s == "never") 70 lld::errs().enable_colors(false); 71 else if (s != "auto") 72 error("unknown option: --color-diagnostics=" + s); 73 } 74 } 75 76 InputArgList MachOOptTable::parse(ArrayRef<const char *> argv) { 77 // Make InputArgList from string vectors. 78 unsigned missingIndex; 79 unsigned missingCount; 80 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size()); 81 82 // Expand response files (arguments in the form of @<filename>) 83 // and then parse the argument again. 84 cl::ExpandResponseFiles(saver, cl::TokenizeGNUCommandLine, vec); 85 InputArgList args = ParseArgs(vec, missingIndex, missingCount); 86 87 // Handle -fatal_warnings early since it converts missing argument warnings 88 // to errors. 89 errorHandler().fatalWarnings = args.hasArg(OPT_fatal_warnings); 90 91 if (missingCount) 92 error(Twine(args.getArgString(missingIndex)) + ": missing argument"); 93 94 handleColorDiagnostics(args); 95 96 for (const Arg *arg : args.filtered(OPT_UNKNOWN)) { 97 std::string nearest; 98 if (findNearest(arg->getAsString(args), nearest) > 1) 99 error("unknown argument '" + arg->getAsString(args) + "'"); 100 else 101 error("unknown argument '" + arg->getAsString(args) + 102 "', did you mean '" + nearest + "'"); 103 } 104 return args; 105 } 106 107 void MachOOptTable::printHelp(const char *argv0, bool showHidden) const { 108 PrintHelp(lld::outs(), (std::string(argv0) + " [options] file...").c_str(), 109 "LLVM Linker", showHidden); 110 lld::outs() << "\n"; 111 } 112 113 static std::string rewritePath(StringRef s) { 114 if (fs::exists(s)) 115 return relativeToRoot(s); 116 return std::string(s); 117 } 118 119 // Reconstructs command line arguments so that so that you can re-run 120 // the same command with the same inputs. This is for --reproduce. 121 std::string macho::createResponseFile(const InputArgList &args) { 122 SmallString<0> data; 123 raw_svector_ostream os(data); 124 125 // Copy the command line to the output while rewriting paths. 126 for (const Arg *arg : args) { 127 switch (arg->getOption().getID()) { 128 case OPT_reproduce: 129 break; 130 case OPT_INPUT: 131 os << quote(rewritePath(arg->getValue())) << "\n"; 132 break; 133 case OPT_o: 134 os << "-o " << quote(path::filename(arg->getValue())) << "\n"; 135 break; 136 case OPT_filelist: 137 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 138 for (StringRef path : args::getLines(*buffer)) 139 os << quote(rewritePath(path)) << "\n"; 140 break; 141 case OPT_force_load: 142 case OPT_rpath: 143 case OPT_syslibroot: 144 case OPT_F: 145 case OPT_L: 146 case OPT_order_file: 147 os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue())) 148 << "\n"; 149 break; 150 case OPT_sectcreate: 151 os << arg->getSpelling() << " " << quote(arg->getValue(0)) << " " 152 << quote(arg->getValue(1)) << " " 153 << quote(rewritePath(arg->getValue(2))) << "\n"; 154 break; 155 default: 156 os << toString(*arg) << "\n"; 157 } 158 } 159 return std::string(data.str()); 160 } 161 162 Optional<std::string> macho::resolveDylibPath(StringRef path) { 163 // TODO: if a tbd and dylib are both present, we should check to make sure 164 // they are consistent. 165 if (fs::exists(path)) 166 return std::string(path); 167 168 SmallString<261> location = path; 169 path::replace_extension(location, ".tbd"); 170 if (fs::exists(location)) 171 return std::string(location); 172 173 return {}; 174 } 175 176 // It's not uncommon to have multiple attempts to load a single dylib, 177 // especially if it's a commonly re-exported core library. 178 static DenseMap<CachedHashStringRef, DylibFile *> loadedDylibs; 179 180 Optional<DylibFile *> macho::loadDylib(MemoryBufferRef mbref, 181 DylibFile *umbrella, 182 bool isBundleLoader) { 183 StringRef path = mbref.getBufferIdentifier(); 184 DylibFile *&file = loadedDylibs[CachedHashStringRef(path)]; 185 if (file) 186 return file; 187 188 file_magic magic = identify_magic(mbref.getBuffer()); 189 if (magic == file_magic::tapi_file) { 190 Expected<std::unique_ptr<InterfaceFile>> result = TextAPIReader::get(mbref); 191 if (!result) { 192 error("could not load TAPI file at " + mbref.getBufferIdentifier() + 193 ": " + toString(result.takeError())); 194 return {}; 195 } 196 file = make<DylibFile>(**result, umbrella, isBundleLoader); 197 } else { 198 assert(magic == file_magic::macho_dynamically_linked_shared_lib || 199 magic == file_magic::macho_dynamically_linked_shared_lib_stub || 200 magic == file_magic::macho_executable || 201 magic == file_magic::macho_bundle); 202 file = make<DylibFile>(mbref, umbrella, isBundleLoader); 203 } 204 return file; 205 } 206 207 Optional<InputFile *> macho::loadArchiveMember(MemoryBufferRef mb, 208 uint32_t modTime, 209 StringRef archiveName, 210 bool objCOnly) { 211 switch (identify_magic(mb.getBuffer())) { 212 case file_magic::macho_object: 213 if (!objCOnly || hasObjCSection(mb)) 214 return make<ObjFile>(mb, modTime, archiveName); 215 return None; 216 case file_magic::bitcode: 217 if (!objCOnly || check(isBitcodeContainingObjCCategory(mb))) 218 return make<BitcodeFile>(mb); 219 return None; 220 default: 221 error(archiveName + ": archive member " + mb.getBufferIdentifier() + 222 " has unhandled file type"); 223 return None; 224 } 225 } 226 227 uint32_t macho::getModTime(StringRef path) { 228 fs::file_status stat; 229 if (!fs::status(path, stat)) 230 if (fs::exists(stat)) 231 return toTimeT(stat.getLastModificationTime()); 232 233 warn("failed to get modification time of " + path); 234 return 0; 235 } 236 237 void macho::printArchiveMemberLoad(StringRef reason, const InputFile *f) { 238 if (config->printEachFile) 239 message(toString(f)); 240 if (config->printWhyLoad) 241 message(reason + " forced load of " + toString(f)); 242 } 243