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