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 #include "Target.h" 14 15 #include "lld/Common/Args.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "lld/Common/Reproduce.h" 19 #include "llvm/ADT/CachedHashString.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/Bitcode/BitcodeReader.h" 22 #include "llvm/LTO/LTO.h" 23 #include "llvm/Option/Arg.h" 24 #include "llvm/Option/ArgList.h" 25 #include "llvm/Option/Option.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/FileSystem.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/TextAPI/InterfaceFile.h" 30 #include "llvm/TextAPI/TextAPIReader.h" 31 32 using namespace llvm; 33 using namespace llvm::MachO; 34 using namespace llvm::opt; 35 using namespace llvm::sys; 36 using namespace lld; 37 using namespace lld::macho; 38 39 // Create prefix string literals used in Options.td 40 #define PREFIX(NAME, VALUE) const char *NAME[] = VALUE; 41 #include "Options.inc" 42 #undef PREFIX 43 44 // Create table mapping all options defined in Options.td 45 static const OptTable::Info optInfo[] = { 46 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ 47 {X1, X2, X10, X11, OPT_##ID, Option::KIND##Class, \ 48 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, 49 #include "Options.inc" 50 #undef OPTION 51 }; 52 53 MachOOptTable::MachOOptTable() : OptTable(optInfo) {} 54 55 // Set color diagnostics according to --color-diagnostics={auto,always,never} 56 // or --no-color-diagnostics flags. 57 static void handleColorDiagnostics(InputArgList &args) { 58 const Arg *arg = 59 args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq, 60 OPT_no_color_diagnostics); 61 if (!arg) 62 return; 63 if (arg->getOption().getID() == OPT_color_diagnostics) { 64 lld::errs().enable_colors(true); 65 } else if (arg->getOption().getID() == OPT_no_color_diagnostics) { 66 lld::errs().enable_colors(false); 67 } else { 68 StringRef s = arg->getValue(); 69 if (s == "always") 70 lld::errs().enable_colors(true); 71 else if (s == "never") 72 lld::errs().enable_colors(false); 73 else if (s != "auto") 74 error("unknown option: --color-diagnostics=" + s); 75 } 76 } 77 78 InputArgList MachOOptTable::parse(ArrayRef<const char *> argv) { 79 // Make InputArgList from string vectors. 80 unsigned missingIndex; 81 unsigned missingCount; 82 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size()); 83 84 // Expand response files (arguments in the form of @<filename>) 85 // and then parse the argument again. 86 cl::ExpandResponseFiles(saver, cl::TokenizeGNUCommandLine, vec); 87 InputArgList args = ParseArgs(vec, missingIndex, missingCount); 88 89 // Handle -fatal_warnings early since it converts missing argument warnings 90 // to errors. 91 errorHandler().fatalWarnings = args.hasArg(OPT_fatal_warnings); 92 93 if (missingCount) 94 error(Twine(args.getArgString(missingIndex)) + ": missing argument"); 95 96 handleColorDiagnostics(args); 97 98 for (const Arg *arg : args.filtered(OPT_UNKNOWN)) { 99 std::string nearest; 100 if (findNearest(arg->getAsString(args), nearest) > 1) 101 error("unknown argument '" + arg->getAsString(args) + "'"); 102 else 103 error("unknown argument '" + arg->getAsString(args) + 104 "', did you mean '" + nearest + "'"); 105 } 106 return args; 107 } 108 109 void MachOOptTable::printHelp(const char *argv0, bool showHidden) const { 110 PrintHelp(lld::outs(), (std::string(argv0) + " [options] file...").c_str(), 111 "LLVM Linker", showHidden); 112 lld::outs() << "\n"; 113 } 114 115 static std::string rewritePath(StringRef s) { 116 if (fs::exists(s)) 117 return relativeToRoot(s); 118 return std::string(s); 119 } 120 121 // Reconstructs command line arguments so that so that you can re-run 122 // the same command with the same inputs. This is for --reproduce. 123 std::string macho::createResponseFile(const InputArgList &args) { 124 SmallString<0> data; 125 raw_svector_ostream os(data); 126 127 // Copy the command line to the output while rewriting paths. 128 for (const Arg *arg : args) { 129 switch (arg->getOption().getID()) { 130 case OPT_reproduce: 131 break; 132 case OPT_INPUT: 133 os << quote(rewritePath(arg->getValue())) << "\n"; 134 break; 135 case OPT_o: 136 os << "-o " << quote(path::filename(arg->getValue())) << "\n"; 137 break; 138 case OPT_filelist: 139 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 140 for (StringRef path : args::getLines(*buffer)) 141 os << quote(rewritePath(path)) << "\n"; 142 break; 143 case OPT_F: 144 case OPT_L: 145 case OPT_bundle_loader: 146 case OPT_exported_symbols_list: 147 case OPT_force_load: 148 case OPT_order_file: 149 case OPT_rpath: 150 case OPT_syslibroot: 151 case OPT_unexported_symbols_list: 152 os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue())) 153 << "\n"; 154 break; 155 case OPT_sectcreate: 156 os << arg->getSpelling() << " " << quote(arg->getValue(0)) << " " 157 << quote(arg->getValue(1)) << " " 158 << quote(rewritePath(arg->getValue(2))) << "\n"; 159 break; 160 default: 161 os << toString(*arg) << "\n"; 162 } 163 } 164 return std::string(data.str()); 165 } 166 167 Optional<std::string> macho::resolveDylibPath(StringRef path) { 168 // TODO: if a tbd and dylib are both present, we should check to make sure 169 // they are consistent. 170 if (fs::exists(path)) 171 return std::string(path); 172 else 173 depTracker->logFileNotFound(path); 174 175 SmallString<261> location = path; 176 path::replace_extension(location, ".tbd"); 177 if (fs::exists(location)) 178 return std::string(location); 179 else 180 depTracker->logFileNotFound(location); 181 return {}; 182 } 183 184 // It's not uncommon to have multiple attempts to load a single dylib, 185 // especially if it's a commonly re-exported core library. 186 static DenseMap<CachedHashStringRef, DylibFile *> loadedDylibs; 187 188 Optional<DylibFile *> macho::loadDylib(MemoryBufferRef mbref, 189 DylibFile *umbrella, 190 bool isBundleLoader) { 191 CachedHashStringRef path(mbref.getBufferIdentifier()); 192 DylibFile *file = loadedDylibs[path]; 193 if (file) 194 return file; 195 196 file_magic magic = identify_magic(mbref.getBuffer()); 197 if (magic == file_magic::tapi_file) { 198 Expected<std::unique_ptr<InterfaceFile>> result = TextAPIReader::get(mbref); 199 if (!result) { 200 error("could not load TAPI file at " + mbref.getBufferIdentifier() + 201 ": " + toString(result.takeError())); 202 return {}; 203 } 204 file = make<DylibFile>(**result, umbrella, isBundleLoader); 205 } else { 206 assert(magic == file_magic::macho_dynamically_linked_shared_lib || 207 magic == file_magic::macho_dynamically_linked_shared_lib_stub || 208 magic == file_magic::macho_executable || 209 magic == file_magic::macho_bundle); 210 file = make<DylibFile>(mbref, umbrella, isBundleLoader); 211 } 212 // Note that DylibFile's ctor may recursively invoke loadDylib(), which can 213 // cause loadedDylibs to get resized and its iterators invalidated. As such, 214 // we redo the key lookup here instead of caching an iterator from our earlier 215 // lookup at the start of the function. 216 loadedDylibs[path] = file; 217 return file; 218 } 219 220 Optional<InputFile *> macho::loadArchiveMember(MemoryBufferRef mb, 221 uint32_t modTime, 222 StringRef archiveName, 223 bool objCOnly) { 224 switch (identify_magic(mb.getBuffer())) { 225 case file_magic::macho_object: 226 if (!objCOnly || hasObjCSection(mb)) 227 return make<ObjFile>(mb, modTime, archiveName); 228 return None; 229 case file_magic::bitcode: 230 if (!objCOnly || check(isBitcodeContainingObjCCategory(mb))) 231 return make<BitcodeFile>(mb); 232 return None; 233 default: 234 error(archiveName + ": archive member " + mb.getBufferIdentifier() + 235 " has unhandled file type"); 236 return None; 237 } 238 } 239 240 uint32_t macho::getModTime(StringRef path) { 241 fs::file_status stat; 242 if (!fs::status(path, stat)) 243 if (fs::exists(stat)) 244 return toTimeT(stat.getLastModificationTime()); 245 246 warn("failed to get modification time of " + path); 247 return 0; 248 } 249 250 void macho::printArchiveMemberLoad(StringRef reason, const InputFile *f) { 251 if (config->printEachFile) 252 message(toString(f)); 253 if (config->printWhyLoad) 254 message(reason + " forced load of " + toString(f)); 255 } 256 257 macho::DependencyTracker::DependencyTracker(StringRef path) 258 : path(path), active(!path.empty()) { 259 if (active && fs::exists(path) && !fs::can_write(path)) { 260 warn("Ignoring dependency_info option since specified path is not " 261 "writeable."); 262 active = false; 263 } 264 } 265 266 void macho::DependencyTracker::write(llvm::StringRef version, 267 const llvm::SetVector<InputFile *> &inputs, 268 llvm::StringRef output) { 269 if (!active) 270 return; 271 272 std::error_code ec; 273 llvm::raw_fd_ostream os(path, ec, llvm::sys::fs::OF_None); 274 if (ec) { 275 warn("Error writing dependency info to file"); 276 return; 277 } 278 279 auto addDep = [&os](DepOpCode opcode, const StringRef &path) { 280 // XXX: Even though DepOpCode's underlying type is uint8_t, 281 // this cast is still needed because Clang older than 10.x has a bug, 282 // where it doesn't know to cast the enum to its underlying type. 283 // Hence `<< DepOpCode` is ambiguous to it. 284 os << static_cast<uint8_t>(opcode); 285 os << path; 286 os << '\0'; 287 }; 288 289 addDep(DepOpCode::Version, version); 290 291 // Sort the input by its names. 292 std::vector<StringRef> inputNames; 293 inputNames.reserve(inputs.size()); 294 for (InputFile *f : inputs) 295 inputNames.push_back(f->getName()); 296 llvm::sort(inputNames); 297 298 for (const StringRef &in : inputNames) 299 addDep(DepOpCode::Input, in); 300 301 for (const std::string &f : notFounds) 302 addDep(DepOpCode::NotFound, f); 303 304 addDep(DepOpCode::Output, output); 305 } 306