xref: /freebsd/contrib/llvm-project/lld/MachO/DriverUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e8d8bef9SDimitry Andric //===- DriverUtils.cpp ----------------------------------------------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric 
9e8d8bef9SDimitry Andric #include "Config.h"
10fe6060f1SDimitry Andric #include "Driver.h"
11e8d8bef9SDimitry Andric #include "InputFiles.h"
12fe6060f1SDimitry Andric #include "ObjC.h"
13fe6060f1SDimitry Andric #include "Target.h"
14e8d8bef9SDimitry Andric 
15e8d8bef9SDimitry Andric #include "lld/Common/Args.h"
1604eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
17e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h"
18e8d8bef9SDimitry Andric #include "llvm/ADT/CachedHashString.h"
19e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h"
20fe6060f1SDimitry Andric #include "llvm/LTO/LTO.h"
21e8d8bef9SDimitry Andric #include "llvm/Option/Arg.h"
22e8d8bef9SDimitry Andric #include "llvm/Option/ArgList.h"
23e8d8bef9SDimitry Andric #include "llvm/Option/Option.h"
24e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h"
25fe6060f1SDimitry Andric #include "llvm/Support/FileSystem.h"
26e8d8bef9SDimitry Andric #include "llvm/Support/Path.h"
27fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h"
28fe6060f1SDimitry Andric #include "llvm/TextAPI/TextAPIReader.h"
29e8d8bef9SDimitry Andric 
30e8d8bef9SDimitry Andric using namespace llvm;
31e8d8bef9SDimitry Andric using namespace llvm::MachO;
32e8d8bef9SDimitry Andric using namespace llvm::opt;
33e8d8bef9SDimitry Andric using namespace llvm::sys;
34e8d8bef9SDimitry Andric using namespace lld;
35e8d8bef9SDimitry Andric using namespace lld::macho;
36e8d8bef9SDimitry Andric 
37e8d8bef9SDimitry Andric // Create prefix string literals used in Options.td
38bdd1243dSDimitry Andric #define PREFIX(NAME, VALUE)                                                    \
39bdd1243dSDimitry Andric   static constexpr StringLiteral NAME##_init[] = VALUE;                        \
40bdd1243dSDimitry Andric   static constexpr ArrayRef<StringLiteral> NAME(NAME##_init,                   \
41bdd1243dSDimitry Andric                                                 std::size(NAME##_init) - 1);
42e8d8bef9SDimitry Andric #include "Options.inc"
43e8d8bef9SDimitry Andric #undef PREFIX
44e8d8bef9SDimitry Andric 
45e8d8bef9SDimitry Andric // Create table mapping all options defined in Options.td
46bdd1243dSDimitry Andric static constexpr OptTable::Info optInfo[] = {
475f757f3fSDimitry Andric #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS,         \
48*0fca6ea1SDimitry Andric                VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR,     \
49*0fca6ea1SDimitry Andric                VALUES)                                                         \
50*0fca6ea1SDimitry Andric   {PREFIX,                                                                     \
51*0fca6ea1SDimitry Andric    NAME,                                                                       \
52*0fca6ea1SDimitry Andric    HELPTEXT,                                                                   \
53*0fca6ea1SDimitry Andric    HELPTEXTSFORVARIANTS,                                                       \
54*0fca6ea1SDimitry Andric    METAVAR,                                                                    \
55*0fca6ea1SDimitry Andric    OPT_##ID,                                                                   \
56*0fca6ea1SDimitry Andric    opt::Option::KIND##Class,                                                   \
57*0fca6ea1SDimitry Andric    PARAM,                                                                      \
58*0fca6ea1SDimitry Andric    FLAGS,                                                                      \
59*0fca6ea1SDimitry Andric    VISIBILITY,                                                                 \
60*0fca6ea1SDimitry Andric    OPT_##GROUP,                                                                \
61*0fca6ea1SDimitry Andric    OPT_##ALIAS,                                                                \
62*0fca6ea1SDimitry Andric    ALIASARGS,                                                                  \
635f757f3fSDimitry Andric    VALUES},
64e8d8bef9SDimitry Andric #include "Options.inc"
65e8d8bef9SDimitry Andric #undef OPTION
66e8d8bef9SDimitry Andric };
67e8d8bef9SDimitry Andric 
MachOOptTable()68bdd1243dSDimitry Andric MachOOptTable::MachOOptTable() : GenericOptTable(optInfo) {}
69e8d8bef9SDimitry Andric 
70e8d8bef9SDimitry Andric // Set color diagnostics according to --color-diagnostics={auto,always,never}
71e8d8bef9SDimitry Andric // or --no-color-diagnostics flags.
handleColorDiagnostics(InputArgList & args)72fe6060f1SDimitry Andric static void handleColorDiagnostics(InputArgList &args) {
73fe6060f1SDimitry Andric   const Arg *arg =
74fe6060f1SDimitry Andric       args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
75e8d8bef9SDimitry Andric                       OPT_no_color_diagnostics);
76e8d8bef9SDimitry Andric   if (!arg)
77e8d8bef9SDimitry Andric     return;
78e8d8bef9SDimitry Andric   if (arg->getOption().getID() == OPT_color_diagnostics) {
79e8d8bef9SDimitry Andric     lld::errs().enable_colors(true);
80e8d8bef9SDimitry Andric   } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
81e8d8bef9SDimitry Andric     lld::errs().enable_colors(false);
82e8d8bef9SDimitry Andric   } else {
83e8d8bef9SDimitry Andric     StringRef s = arg->getValue();
84e8d8bef9SDimitry Andric     if (s == "always")
85e8d8bef9SDimitry Andric       lld::errs().enable_colors(true);
86e8d8bef9SDimitry Andric     else if (s == "never")
87e8d8bef9SDimitry Andric       lld::errs().enable_colors(false);
88e8d8bef9SDimitry Andric     else if (s != "auto")
89e8d8bef9SDimitry Andric       error("unknown option: --color-diagnostics=" + s);
90e8d8bef9SDimitry Andric   }
91e8d8bef9SDimitry Andric }
92e8d8bef9SDimitry Andric 
parse(ArrayRef<const char * > argv)93fe6060f1SDimitry Andric InputArgList MachOOptTable::parse(ArrayRef<const char *> argv) {
94e8d8bef9SDimitry Andric   // Make InputArgList from string vectors.
95e8d8bef9SDimitry Andric   unsigned missingIndex;
96e8d8bef9SDimitry Andric   unsigned missingCount;
97e8d8bef9SDimitry Andric   SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
98e8d8bef9SDimitry Andric 
99e8d8bef9SDimitry Andric   // Expand response files (arguments in the form of @<filename>)
100e8d8bef9SDimitry Andric   // and then parse the argument again.
10104eeddc0SDimitry Andric   cl::ExpandResponseFiles(saver(), cl::TokenizeGNUCommandLine, vec);
102fe6060f1SDimitry Andric   InputArgList args = ParseArgs(vec, missingIndex, missingCount);
103e8d8bef9SDimitry Andric 
104e8d8bef9SDimitry Andric   // Handle -fatal_warnings early since it converts missing argument warnings
105e8d8bef9SDimitry Andric   // to errors.
106e8d8bef9SDimitry Andric   errorHandler().fatalWarnings = args.hasArg(OPT_fatal_warnings);
10781ad6265SDimitry Andric   errorHandler().suppressWarnings = args.hasArg(OPT_w);
108e8d8bef9SDimitry Andric 
109e8d8bef9SDimitry Andric   if (missingCount)
110e8d8bef9SDimitry Andric     error(Twine(args.getArgString(missingIndex)) + ": missing argument");
111e8d8bef9SDimitry Andric 
112e8d8bef9SDimitry Andric   handleColorDiagnostics(args);
113e8d8bef9SDimitry Andric 
114fe6060f1SDimitry Andric   for (const Arg *arg : args.filtered(OPT_UNKNOWN)) {
115e8d8bef9SDimitry Andric     std::string nearest;
116e8d8bef9SDimitry Andric     if (findNearest(arg->getAsString(args), nearest) > 1)
117e8d8bef9SDimitry Andric       error("unknown argument '" + arg->getAsString(args) + "'");
118e8d8bef9SDimitry Andric     else
119e8d8bef9SDimitry Andric       error("unknown argument '" + arg->getAsString(args) +
120e8d8bef9SDimitry Andric             "', did you mean '" + nearest + "'");
121e8d8bef9SDimitry Andric   }
122e8d8bef9SDimitry Andric   return args;
123e8d8bef9SDimitry Andric }
124e8d8bef9SDimitry Andric 
printHelp(const char * argv0,bool showHidden) const125e8d8bef9SDimitry Andric void MachOOptTable::printHelp(const char *argv0, bool showHidden) const {
126fe6060f1SDimitry Andric   OptTable::printHelp(lld::outs(),
127fe6060f1SDimitry Andric                       (std::string(argv0) + " [options] file...").c_str(),
128e8d8bef9SDimitry Andric                       "LLVM Linker", showHidden);
129e8d8bef9SDimitry Andric   lld::outs() << "\n";
130e8d8bef9SDimitry Andric }
131e8d8bef9SDimitry Andric 
rewritePath(StringRef s)132e8d8bef9SDimitry Andric static std::string rewritePath(StringRef s) {
133e8d8bef9SDimitry Andric   if (fs::exists(s))
134e8d8bef9SDimitry Andric     return relativeToRoot(s);
135e8d8bef9SDimitry Andric   return std::string(s);
136e8d8bef9SDimitry Andric }
137e8d8bef9SDimitry Andric 
rewriteInputPath(StringRef s)138fe6060f1SDimitry Andric static std::string rewriteInputPath(StringRef s) {
139fe6060f1SDimitry Andric   // Don't bother rewriting "absolute" paths that are actually under the
140fe6060f1SDimitry Andric   // syslibroot; simply rewriting the syslibroot is sufficient.
141fe6060f1SDimitry Andric   if (rerootPath(s) == s && fs::exists(s))
142fe6060f1SDimitry Andric     return relativeToRoot(s);
143fe6060f1SDimitry Andric   return std::string(s);
144fe6060f1SDimitry Andric }
145fe6060f1SDimitry Andric 
146e8d8bef9SDimitry Andric // Reconstructs command line arguments so that so that you can re-run
147e8d8bef9SDimitry Andric // the same command with the same inputs. This is for --reproduce.
createResponseFile(const InputArgList & args)148fe6060f1SDimitry Andric std::string macho::createResponseFile(const InputArgList &args) {
149e8d8bef9SDimitry Andric   SmallString<0> data;
150e8d8bef9SDimitry Andric   raw_svector_ostream os(data);
151e8d8bef9SDimitry Andric 
152e8d8bef9SDimitry Andric   // Copy the command line to the output while rewriting paths.
153fe6060f1SDimitry Andric   for (const Arg *arg : args) {
154e8d8bef9SDimitry Andric     switch (arg->getOption().getID()) {
155e8d8bef9SDimitry Andric     case OPT_reproduce:
156e8d8bef9SDimitry Andric       break;
157e8d8bef9SDimitry Andric     case OPT_INPUT:
158fe6060f1SDimitry Andric       os << quote(rewriteInputPath(arg->getValue())) << "\n";
159e8d8bef9SDimitry Andric       break;
160e8d8bef9SDimitry Andric     case OPT_o:
161e8d8bef9SDimitry Andric       os << "-o " << quote(path::filename(arg->getValue())) << "\n";
162e8d8bef9SDimitry Andric       break;
163e8d8bef9SDimitry Andric     case OPT_filelist:
164bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
165e8d8bef9SDimitry Andric         for (StringRef path : args::getLines(*buffer))
166fe6060f1SDimitry Andric           os << quote(rewriteInputPath(path)) << "\n";
167e8d8bef9SDimitry Andric       break;
168e8d8bef9SDimitry Andric     case OPT_force_load:
169fe6060f1SDimitry Andric     case OPT_weak_library:
170972a253aSDimitry Andric     case OPT_load_hidden:
171fe6060f1SDimitry Andric       os << arg->getSpelling() << " "
172fe6060f1SDimitry Andric          << quote(rewriteInputPath(arg->getValue())) << "\n";
173fe6060f1SDimitry Andric       break;
174e8d8bef9SDimitry Andric     case OPT_F:
175e8d8bef9SDimitry Andric     case OPT_L:
176fe6060f1SDimitry Andric     case OPT_bundle_loader:
177fe6060f1SDimitry Andric     case OPT_exported_symbols_list:
178e8d8bef9SDimitry Andric     case OPT_order_file:
179fe6060f1SDimitry Andric     case OPT_syslibroot:
180fe6060f1SDimitry Andric     case OPT_unexported_symbols_list:
181e8d8bef9SDimitry Andric       os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
182e8d8bef9SDimitry Andric          << "\n";
183e8d8bef9SDimitry Andric       break;
184e8d8bef9SDimitry Andric     case OPT_sectcreate:
185e8d8bef9SDimitry Andric       os << arg->getSpelling() << " " << quote(arg->getValue(0)) << " "
186e8d8bef9SDimitry Andric          << quote(arg->getValue(1)) << " "
187e8d8bef9SDimitry Andric          << quote(rewritePath(arg->getValue(2))) << "\n";
188e8d8bef9SDimitry Andric       break;
189e8d8bef9SDimitry Andric     default:
190e8d8bef9SDimitry Andric       os << toString(*arg) << "\n";
191e8d8bef9SDimitry Andric     }
192e8d8bef9SDimitry Andric   }
1937a6dacacSDimitry Andric   return std::string(data);
194e8d8bef9SDimitry Andric }
195e8d8bef9SDimitry Andric 
searchedDylib(const Twine & path,bool found)196fe6060f1SDimitry Andric static void searchedDylib(const Twine &path, bool found) {
197fe6060f1SDimitry Andric   if (config->printDylibSearch)
198fe6060f1SDimitry Andric     message("searched " + path + (found ? ", found " : ", not found"));
199fe6060f1SDimitry Andric   if (!found)
200fe6060f1SDimitry Andric     depTracker->logFileNotFound(path);
201fe6060f1SDimitry Andric }
202fe6060f1SDimitry Andric 
resolveDylibPath(StringRef dylibPath)203bdd1243dSDimitry Andric std::optional<StringRef> macho::resolveDylibPath(StringRef dylibPath) {
204e8d8bef9SDimitry Andric   // TODO: if a tbd and dylib are both present, we should check to make sure
205e8d8bef9SDimitry Andric   // they are consistent.
206fe6060f1SDimitry Andric   SmallString<261> tbdPath = dylibPath;
207fe6060f1SDimitry Andric   path::replace_extension(tbdPath, ".tbd");
208fe6060f1SDimitry Andric   bool tbdExists = fs::exists(tbdPath);
209fe6060f1SDimitry Andric   searchedDylib(tbdPath, tbdExists);
210fe6060f1SDimitry Andric   if (tbdExists)
21104eeddc0SDimitry Andric     return saver().save(tbdPath.str());
212349cc55cSDimitry Andric 
213349cc55cSDimitry Andric   bool dylibExists = fs::exists(dylibPath);
214349cc55cSDimitry Andric   searchedDylib(dylibPath, dylibExists);
215349cc55cSDimitry Andric   if (dylibExists)
21604eeddc0SDimitry Andric     return saver().save(dylibPath);
217e8d8bef9SDimitry Andric   return {};
218e8d8bef9SDimitry Andric }
219e8d8bef9SDimitry Andric 
220e8d8bef9SDimitry Andric // It's not uncommon to have multiple attempts to load a single dylib,
221e8d8bef9SDimitry Andric // especially if it's a commonly re-exported core library.
222e8d8bef9SDimitry Andric static DenseMap<CachedHashStringRef, DylibFile *> loadedDylibs;
223e8d8bef9SDimitry Andric 
loadDylib(MemoryBufferRef mbref,DylibFile * umbrella,bool isBundleLoader,bool explicitlyLinked)224fe6060f1SDimitry Andric DylibFile *macho::loadDylib(MemoryBufferRef mbref, DylibFile *umbrella,
22581ad6265SDimitry Andric                             bool isBundleLoader, bool explicitlyLinked) {
226fe6060f1SDimitry Andric   CachedHashStringRef path(mbref.getBufferIdentifier());
227fe6060f1SDimitry Andric   DylibFile *&file = loadedDylibs[path];
22881ad6265SDimitry Andric   if (file) {
22981ad6265SDimitry Andric     if (explicitlyLinked)
23061cfbce3SDimitry Andric       file->setExplicitlyLinked();
231e8d8bef9SDimitry Andric     return file;
23281ad6265SDimitry Andric   }
233e8d8bef9SDimitry Andric 
234fe6060f1SDimitry Andric   DylibFile *newFile;
235e8d8bef9SDimitry Andric   file_magic magic = identify_magic(mbref.getBuffer());
236e8d8bef9SDimitry Andric   if (magic == file_magic::tapi_file) {
237e8d8bef9SDimitry Andric     Expected<std::unique_ptr<InterfaceFile>> result = TextAPIReader::get(mbref);
238e8d8bef9SDimitry Andric     if (!result) {
239e8d8bef9SDimitry Andric       error("could not load TAPI file at " + mbref.getBufferIdentifier() +
240e8d8bef9SDimitry Andric             ": " + toString(result.takeError()));
241fe6060f1SDimitry Andric       return nullptr;
242e8d8bef9SDimitry Andric     }
24381ad6265SDimitry Andric     file =
24481ad6265SDimitry Andric         make<DylibFile>(**result, umbrella, isBundleLoader, explicitlyLinked);
245fe6060f1SDimitry Andric 
246fe6060f1SDimitry Andric     // parseReexports() can recursively call loadDylib(). That's fine since
247fe6060f1SDimitry Andric     // we wrote the DylibFile we just loaded to the loadDylib cache via the
248fe6060f1SDimitry Andric     // `file` reference. But the recursive load can grow loadDylibs, so the
249fe6060f1SDimitry Andric     // `file` reference might become invalid after parseReexports() -- so copy
250fe6060f1SDimitry Andric     // the pointer it refers to before continuing.
251fe6060f1SDimitry Andric     newFile = file;
252fe6060f1SDimitry Andric     if (newFile->exportingFile)
253fe6060f1SDimitry Andric       newFile->parseReexports(**result);
254e8d8bef9SDimitry Andric   } else {
255e8d8bef9SDimitry Andric     assert(magic == file_magic::macho_dynamically_linked_shared_lib ||
256fe6060f1SDimitry Andric            magic == file_magic::macho_dynamically_linked_shared_lib_stub ||
257fe6060f1SDimitry Andric            magic == file_magic::macho_executable ||
258fe6060f1SDimitry Andric            magic == file_magic::macho_bundle);
25981ad6265SDimitry Andric     file = make<DylibFile>(mbref, umbrella, isBundleLoader, explicitlyLinked);
260fe6060f1SDimitry Andric 
261fe6060f1SDimitry Andric     // parseLoadCommands() can also recursively call loadDylib(). See comment
262fe6060f1SDimitry Andric     // in previous block for why this means we must copy `file` here.
263fe6060f1SDimitry Andric     newFile = file;
264fe6060f1SDimitry Andric     if (newFile->exportingFile)
265fe6060f1SDimitry Andric       newFile->parseLoadCommands(mbref);
266e8d8bef9SDimitry Andric   }
267fe6060f1SDimitry Andric   return newFile;
268fe6060f1SDimitry Andric }
269fe6060f1SDimitry Andric 
resetLoadedDylibs()270349cc55cSDimitry Andric void macho::resetLoadedDylibs() { loadedDylibs.clear(); }
271349cc55cSDimitry Andric 
272bdd1243dSDimitry Andric std::optional<StringRef>
findPathCombination(const Twine & name,const std::vector<StringRef> & roots,ArrayRef<StringRef> extensions)273fe6060f1SDimitry Andric macho::findPathCombination(const Twine &name,
274fe6060f1SDimitry Andric                            const std::vector<StringRef> &roots,
275fe6060f1SDimitry Andric                            ArrayRef<StringRef> extensions) {
276fe6060f1SDimitry Andric   SmallString<261> base;
277fe6060f1SDimitry Andric   for (StringRef dir : roots) {
278fe6060f1SDimitry Andric     base = dir;
279fe6060f1SDimitry Andric     path::append(base, name);
280fe6060f1SDimitry Andric     for (StringRef ext : extensions) {
281fe6060f1SDimitry Andric       Twine location = base + ext;
282fe6060f1SDimitry Andric       bool exists = fs::exists(location);
283fe6060f1SDimitry Andric       searchedDylib(location, exists);
284fe6060f1SDimitry Andric       if (exists)
28504eeddc0SDimitry Andric         return saver().save(location.str());
286fe6060f1SDimitry Andric     }
287fe6060f1SDimitry Andric   }
288fe6060f1SDimitry Andric   return {};
289fe6060f1SDimitry Andric }
290fe6060f1SDimitry Andric 
rerootPath(StringRef path)291fe6060f1SDimitry Andric StringRef macho::rerootPath(StringRef path) {
29206c3fb27SDimitry Andric   if (!path::is_absolute(path, path::Style::posix) || path.ends_with(".o"))
293fe6060f1SDimitry Andric     return path;
294fe6060f1SDimitry Andric 
295bdd1243dSDimitry Andric   if (std::optional<StringRef> rerootedPath =
296fe6060f1SDimitry Andric           findPathCombination(path, config->systemLibraryRoots))
297fe6060f1SDimitry Andric     return *rerootedPath;
298fe6060f1SDimitry Andric 
299fe6060f1SDimitry Andric   return path;
300fe6060f1SDimitry Andric }
301fe6060f1SDimitry Andric 
getModTime(StringRef path)302e8d8bef9SDimitry Andric uint32_t macho::getModTime(StringRef path) {
303fe6060f1SDimitry Andric   if (config->zeroModTime)
304fe6060f1SDimitry Andric     return 0;
305fe6060f1SDimitry Andric 
306e8d8bef9SDimitry Andric   fs::file_status stat;
307e8d8bef9SDimitry Andric   if (!fs::status(path, stat))
308e8d8bef9SDimitry Andric     if (fs::exists(stat))
309e8d8bef9SDimitry Andric       return toTimeT(stat.getLastModificationTime());
310e8d8bef9SDimitry Andric 
311e8d8bef9SDimitry Andric   warn("failed to get modification time of " + path);
312e8d8bef9SDimitry Andric   return 0;
313e8d8bef9SDimitry Andric }
314e8d8bef9SDimitry Andric 
printArchiveMemberLoad(StringRef reason,const InputFile * f)315e8d8bef9SDimitry Andric void macho::printArchiveMemberLoad(StringRef reason, const InputFile *f) {
316e8d8bef9SDimitry Andric   if (config->printEachFile)
317e8d8bef9SDimitry Andric     message(toString(f));
318e8d8bef9SDimitry Andric   if (config->printWhyLoad)
319e8d8bef9SDimitry Andric     message(reason + " forced load of " + toString(f));
320e8d8bef9SDimitry Andric }
321fe6060f1SDimitry Andric 
DependencyTracker(StringRef path)322fe6060f1SDimitry Andric macho::DependencyTracker::DependencyTracker(StringRef path)
323fe6060f1SDimitry Andric     : path(path), active(!path.empty()) {
324fe6060f1SDimitry Andric   if (active && fs::exists(path) && !fs::can_write(path)) {
325fe6060f1SDimitry Andric     warn("Ignoring dependency_info option since specified path is not "
326fe6060f1SDimitry Andric          "writeable.");
327fe6060f1SDimitry Andric     active = false;
328fe6060f1SDimitry Andric   }
329fe6060f1SDimitry Andric }
330fe6060f1SDimitry Andric 
write(StringRef version,const SetVector<InputFile * > & inputs,StringRef output)331fe6060f1SDimitry Andric void macho::DependencyTracker::write(StringRef version,
332fe6060f1SDimitry Andric                                      const SetVector<InputFile *> &inputs,
333fe6060f1SDimitry Andric                                      StringRef output) {
334fe6060f1SDimitry Andric   if (!active)
335fe6060f1SDimitry Andric     return;
336fe6060f1SDimitry Andric 
337fe6060f1SDimitry Andric   std::error_code ec;
338fe6060f1SDimitry Andric   raw_fd_ostream os(path, ec, fs::OF_None);
339fe6060f1SDimitry Andric   if (ec) {
340fe6060f1SDimitry Andric     warn("Error writing dependency info to file");
341fe6060f1SDimitry Andric     return;
342fe6060f1SDimitry Andric   }
343fe6060f1SDimitry Andric 
344fe6060f1SDimitry Andric   auto addDep = [&os](DepOpCode opcode, const StringRef &path) {
345fe6060f1SDimitry Andric     // XXX: Even though DepOpCode's underlying type is uint8_t,
346fe6060f1SDimitry Andric     // this cast is still needed because Clang older than 10.x has a bug,
347fe6060f1SDimitry Andric     // where it doesn't know to cast the enum to its underlying type.
348fe6060f1SDimitry Andric     // Hence `<< DepOpCode` is ambiguous to it.
349fe6060f1SDimitry Andric     os << static_cast<uint8_t>(opcode);
350fe6060f1SDimitry Andric     os << path;
351fe6060f1SDimitry Andric     os << '\0';
352fe6060f1SDimitry Andric   };
353fe6060f1SDimitry Andric 
354fe6060f1SDimitry Andric   addDep(DepOpCode::Version, version);
355fe6060f1SDimitry Andric 
356fe6060f1SDimitry Andric   // Sort the input by its names.
357fe6060f1SDimitry Andric   std::vector<StringRef> inputNames;
358fe6060f1SDimitry Andric   inputNames.reserve(inputs.size());
359fe6060f1SDimitry Andric   for (InputFile *f : inputs)
360fe6060f1SDimitry Andric     inputNames.push_back(f->getName());
361fe6060f1SDimitry Andric   llvm::sort(inputNames);
362fe6060f1SDimitry Andric 
363fe6060f1SDimitry Andric   for (const StringRef &in : inputNames)
364fe6060f1SDimitry Andric     addDep(DepOpCode::Input, in);
365fe6060f1SDimitry Andric 
366fe6060f1SDimitry Andric   for (const std::string &f : notFounds)
367fe6060f1SDimitry Andric     addDep(DepOpCode::NotFound, f);
368fe6060f1SDimitry Andric 
369fe6060f1SDimitry Andric   addDep(DepOpCode::Output, output);
370fe6060f1SDimitry Andric }
371