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 "Driver.h"
10 #include "Config.h"
11 #include "InputFiles.h"
12 
13 #include "lld/Common/Args.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/Memory.h"
16 #include "lld/Common/Reproduce.h"
17 #include "llvm/Option/Arg.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Option/Option.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/TextAPI/MachO/TextAPIReader.h"
23 
24 using namespace llvm;
25 using namespace llvm::MachO;
26 using namespace llvm::opt;
27 using namespace llvm::sys;
28 using namespace lld;
29 using namespace lld::macho;
30 
31 // Create prefix string literals used in Options.td
32 #define PREFIX(NAME, VALUE) const char *NAME[] = VALUE;
33 #include "Options.inc"
34 #undef PREFIX
35 
36 // Create table mapping all options defined in Options.td
37 static const opt::OptTable::Info optInfo[] = {
38 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
39   {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
40    X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
41 #include "Options.inc"
42 #undef OPTION
43 };
44 
45 MachOOptTable::MachOOptTable() : OptTable(optInfo) {}
46 
47 // Set color diagnostics according to --color-diagnostics={auto,always,never}
48 // or --no-color-diagnostics flags.
49 static void handleColorDiagnostics(opt::InputArgList &args) {
50   auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
51                               OPT_no_color_diagnostics);
52   if (!arg)
53     return;
54   if (arg->getOption().getID() == OPT_color_diagnostics) {
55     lld::errs().enable_colors(true);
56   } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
57     lld::errs().enable_colors(false);
58   } else {
59     StringRef s = arg->getValue();
60     if (s == "always")
61       lld::errs().enable_colors(true);
62     else if (s == "never")
63       lld::errs().enable_colors(false);
64     else if (s != "auto")
65       error("unknown option: --color-diagnostics=" + s);
66   }
67 }
68 
69 opt::InputArgList MachOOptTable::parse(ArrayRef<const char *> argv) {
70   // Make InputArgList from string vectors.
71   unsigned missingIndex;
72   unsigned missingCount;
73   SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
74 
75   // Expand response files (arguments in the form of @<filename>)
76   // and then parse the argument again.
77   cl::ExpandResponseFiles(saver, cl::TokenizeGNUCommandLine, vec);
78   opt::InputArgList args = ParseArgs(vec, missingIndex, missingCount);
79 
80   // Handle -fatal_warnings early since it converts missing argument warnings
81   // to errors.
82   errorHandler().fatalWarnings = args.hasArg(OPT_fatal_warnings);
83 
84   if (missingCount)
85     error(Twine(args.getArgString(missingIndex)) + ": missing argument");
86 
87   handleColorDiagnostics(args);
88 
89   for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {
90     std::string nearest;
91     if (findNearest(arg->getAsString(args), nearest) > 1)
92       error("unknown argument '" + arg->getAsString(args) + "'");
93     else
94       error("unknown argument '" + arg->getAsString(args) +
95             "', did you mean '" + nearest + "'");
96   }
97   return args;
98 }
99 
100 void MachOOptTable::printHelp(const char *argv0, bool showHidden) const {
101   PrintHelp(lld::outs(), (std::string(argv0) + " [options] file...").c_str(),
102             "LLVM Linker", showHidden);
103   lld::outs() << "\n";
104 }
105 
106 static std::string rewritePath(StringRef s) {
107   if (fs::exists(s))
108     return relativeToRoot(s);
109   return std::string(s);
110 }
111 
112 // Reconstructs command line arguments so that so that you can re-run
113 // the same command with the same inputs. This is for --reproduce.
114 std::string macho::createResponseFile(const opt::InputArgList &args) {
115   SmallString<0> data;
116   raw_svector_ostream os(data);
117 
118   // Copy the command line to the output while rewriting paths.
119   for (auto *arg : args) {
120     switch (arg->getOption().getID()) {
121     case OPT_reproduce:
122       break;
123     case OPT_INPUT:
124       os << quote(rewritePath(arg->getValue())) << "\n";
125       break;
126     case OPT_o:
127       os << "-o " << quote(path::filename(arg->getValue())) << "\n";
128       break;
129     case OPT_filelist:
130       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
131         for (StringRef path : args::getLines(*buffer))
132           os << quote(rewritePath(path)) << "\n";
133       break;
134     case OPT_force_load:
135     case OPT_rpath:
136     case OPT_syslibroot:
137     case OPT_F:
138     case OPT_L:
139     case OPT_order_file:
140       os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
141          << "\n";
142       break;
143     case OPT_sectcreate:
144       os << arg->getSpelling() << " " << quote(arg->getValue(0)) << " "
145          << quote(arg->getValue(1)) << " "
146          << quote(rewritePath(arg->getValue(2))) << "\n";
147       break;
148     default:
149       os << toString(*arg) << "\n";
150     }
151   }
152   return std::string(data.str());
153 }
154 
155 Optional<std::string> macho::resolveDylibPath(StringRef path) {
156   // TODO: if a tbd and dylib are both present, we should check to make sure
157   // they are consistent.
158   if (fs::exists(path))
159     return std::string(path);
160 
161   SmallString<261> location = path;
162   path::replace_extension(location, ".tbd");
163   if (fs::exists(location))
164     return std::string(location);
165 
166   return {};
167 }
168 
169 Optional<DylibFile *> macho::makeDylibFromTAPI(MemoryBufferRef mbref,
170                                                DylibFile *umbrella) {
171   Expected<std::unique_ptr<InterfaceFile>> result = TextAPIReader::get(mbref);
172   if (!result) {
173     error("could not load TAPI file at " + mbref.getBufferIdentifier() + ": " +
174           toString(result.takeError()));
175     return {};
176   }
177   return make<DylibFile>(**result, umbrella);
178 }
179 
180 uint32_t macho::getModTime(StringRef path) {
181   fs::file_status stat;
182   if (!fs::status(path, stat))
183     if (fs::exists(stat))
184       return toTimeT(stat.getLastModificationTime());
185 
186   warn("failed to get modification time of " + path);
187   return 0;
188 }
189 
190 void macho::printArchiveMemberLoad(StringRef reason, const InputFile *f) {
191   if (config->printEachFile)
192     lld::outs() << toString(f) << '\n';
193   if (config->printWhyLoad)
194     lld::outs() << reason << " forced load of " << toString(f) << '\n';
195 }
196