1 //===- DriverUtils.cpp ----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 #include "InputFiles.h"
15 #include "lld/Common/Args.h"
16 #include "lld/Common/CommonLinkerContext.h"
17 #include "lld/Common/Reproduce.h"
18 #include "llvm/ADT/CachedHashString.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/LTO/LTO.h"
21 #include "llvm/Option/Arg.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Option/Option.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/TextAPI/InterfaceFile.h"
28 #include "llvm/TextAPI/TextAPIReader.h"
31 using namespace llvm::MachO
;
32 using namespace llvm::opt
;
33 using namespace llvm::sys
;
35 using namespace lld::macho
;
37 // Create prefix string literals used in Options.td
38 #define PREFIX(NAME, VALUE) \
39 static constexpr StringLiteral NAME##_init[] = VALUE; \
40 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
41 std::size(NAME##_init) - 1);
42 #include "Options.inc"
45 // Create table mapping all options defined in Options.td
46 static constexpr OptTable::Info optInfo
[] = {
47 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
48 VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, \
53 HELPTEXTSFORVARIANTS, \
56 opt::Option::KIND##Class, \
64 #include "Options.inc"
68 MachOOptTable::MachOOptTable() : GenericOptTable(optInfo
) {}
70 // Set color diagnostics according to --color-diagnostics={auto,always,never}
71 // or --no-color-diagnostics flags.
72 static void handleColorDiagnostics(InputArgList
&args
) {
74 args
.getLastArg(OPT_color_diagnostics
, OPT_color_diagnostics_eq
,
75 OPT_no_color_diagnostics
);
78 if (arg
->getOption().getID() == OPT_color_diagnostics
) {
79 lld::errs().enable_colors(true);
80 } else if (arg
->getOption().getID() == OPT_no_color_diagnostics
) {
81 lld::errs().enable_colors(false);
83 StringRef s
= arg
->getValue();
85 lld::errs().enable_colors(true);
86 else if (s
== "never")
87 lld::errs().enable_colors(false);
89 error("unknown option: --color-diagnostics=" + s
);
93 InputArgList
MachOOptTable::parse(ArrayRef
<const char *> argv
) {
94 // Make InputArgList from string vectors.
95 unsigned missingIndex
;
96 unsigned missingCount
;
97 SmallVector
<const char *, 256> vec(argv
.data(), argv
.data() + argv
.size());
99 // Expand response files (arguments in the form of @<filename>)
100 // and then parse the argument again.
101 cl::ExpandResponseFiles(saver(), cl::TokenizeGNUCommandLine
, vec
);
102 InputArgList args
= ParseArgs(vec
, missingIndex
, missingCount
);
104 // Handle -fatal_warnings early since it converts missing argument warnings
106 errorHandler().fatalWarnings
= args
.hasArg(OPT_fatal_warnings
);
107 errorHandler().suppressWarnings
= args
.hasArg(OPT_w
);
110 error(Twine(args
.getArgString(missingIndex
)) + ": missing argument");
112 handleColorDiagnostics(args
);
114 for (const Arg
*arg
: args
.filtered(OPT_UNKNOWN
)) {
116 if (findNearest(arg
->getAsString(args
), nearest
) > 1)
117 error("unknown argument '" + arg
->getAsString(args
) + "'");
119 error("unknown argument '" + arg
->getAsString(args
) +
120 "', did you mean '" + nearest
+ "'");
125 void MachOOptTable::printHelp(const char *argv0
, bool showHidden
) const {
126 OptTable::printHelp(lld::outs(),
127 (std::string(argv0
) + " [options] file...").c_str(),
128 "LLVM Linker", showHidden
);
132 static std::string
rewritePath(StringRef s
) {
134 return relativeToRoot(s
);
135 return std::string(s
);
138 static std::string
rewriteInputPath(StringRef s
) {
139 // Don't bother rewriting "absolute" paths that are actually under the
140 // syslibroot; simply rewriting the syslibroot is sufficient.
141 if (rerootPath(s
) == s
&& fs::exists(s
))
142 return relativeToRoot(s
);
143 return std::string(s
);
146 // Reconstructs command line arguments so that so that you can re-run
147 // the same command with the same inputs. This is for --reproduce.
148 std::string
macho::createResponseFile(const InputArgList
&args
) {
150 raw_svector_ostream
os(data
);
152 // Copy the command line to the output while rewriting paths.
153 for (const Arg
*arg
: args
) {
154 switch (arg
->getOption().getID()) {
158 os
<< quote(rewriteInputPath(arg
->getValue())) << "\n";
161 os
<< "-o " << quote(path::filename(arg
->getValue())) << "\n";
164 if (std::optional
<MemoryBufferRef
> buffer
= readFile(arg
->getValue()))
165 for (StringRef path
: args::getLines(*buffer
))
166 os
<< quote(rewriteInputPath(path
)) << "\n";
169 case OPT_weak_library
:
170 case OPT_load_hidden
:
171 os
<< arg
->getSpelling() << " "
172 << quote(rewriteInputPath(arg
->getValue())) << "\n";
176 case OPT_bundle_loader
:
177 case OPT_exported_symbols_list
:
180 case OPT_unexported_symbols_list
:
181 os
<< arg
->getSpelling() << " " << quote(rewritePath(arg
->getValue()))
185 os
<< arg
->getSpelling() << " " << quote(arg
->getValue(0)) << " "
186 << quote(arg
->getValue(1)) << " "
187 << quote(rewritePath(arg
->getValue(2))) << "\n";
190 os
<< toString(*arg
) << "\n";
193 return std::string(data
);
196 static void searchedDylib(const Twine
&path
, bool found
) {
197 if (config
->printDylibSearch
)
198 message("searched " + path
+ (found
? ", found " : ", not found"));
200 depTracker
->logFileNotFound(path
);
203 std::optional
<StringRef
> macho::resolveDylibPath(StringRef dylibPath
) {
204 // TODO: if a tbd and dylib are both present, we should check to make sure
205 // they are consistent.
206 SmallString
<261> tbdPath
= dylibPath
;
207 path::replace_extension(tbdPath
, ".tbd");
208 bool tbdExists
= fs::exists(tbdPath
);
209 searchedDylib(tbdPath
, tbdExists
);
211 return saver().save(tbdPath
.str());
213 bool dylibExists
= fs::exists(dylibPath
);
214 searchedDylib(dylibPath
, dylibExists
);
216 return saver().save(dylibPath
);
220 // It's not uncommon to have multiple attempts to load a single dylib,
221 // especially if it's a commonly re-exported core library.
222 static DenseMap
<CachedHashStringRef
, DylibFile
*> loadedDylibs
;
224 DylibFile
*macho::loadDylib(MemoryBufferRef mbref
, DylibFile
*umbrella
,
225 bool isBundleLoader
, bool explicitlyLinked
) {
226 CachedHashStringRef
path(mbref
.getBufferIdentifier());
227 DylibFile
*&file
= loadedDylibs
[path
];
229 if (explicitlyLinked
)
230 file
->setExplicitlyLinked();
235 file_magic magic
= identify_magic(mbref
.getBuffer());
236 if (magic
== file_magic::tapi_file
) {
237 Expected
<std::unique_ptr
<InterfaceFile
>> result
= TextAPIReader::get(mbref
);
239 error("could not load TAPI file at " + mbref
.getBufferIdentifier() +
240 ": " + toString(result
.takeError()));
244 make
<DylibFile
>(**result
, umbrella
, isBundleLoader
, explicitlyLinked
);
246 // parseReexports() can recursively call loadDylib(). That's fine since
247 // we wrote the DylibFile we just loaded to the loadDylib cache via the
248 // `file` reference. But the recursive load can grow loadDylibs, so the
249 // `file` reference might become invalid after parseReexports() -- so copy
250 // the pointer it refers to before continuing.
252 if (newFile
->exportingFile
)
253 newFile
->parseReexports(**result
);
255 assert(magic
== file_magic::macho_dynamically_linked_shared_lib
||
256 magic
== file_magic::macho_dynamically_linked_shared_lib_stub
||
257 magic
== file_magic::macho_executable
||
258 magic
== file_magic::macho_bundle
);
259 file
= make
<DylibFile
>(mbref
, umbrella
, isBundleLoader
, explicitlyLinked
);
261 // parseLoadCommands() can also recursively call loadDylib(). See comment
262 // in previous block for why this means we must copy `file` here.
264 if (newFile
->exportingFile
)
265 newFile
->parseLoadCommands(mbref
);
270 void macho::resetLoadedDylibs() { loadedDylibs
.clear(); }
272 std::optional
<StringRef
>
273 macho::findPathCombination(const Twine
&name
,
274 const std::vector
<StringRef
> &roots
,
275 ArrayRef
<StringRef
> extensions
) {
276 SmallString
<261> base
;
277 for (StringRef dir
: roots
) {
279 path::append(base
, name
);
280 for (StringRef ext
: extensions
) {
281 Twine location
= base
+ ext
;
282 bool exists
= fs::exists(location
);
283 searchedDylib(location
, exists
);
285 return saver().save(location
.str());
291 StringRef
macho::rerootPath(StringRef path
) {
292 if (!path::is_absolute(path
, path::Style::posix
) || path
.ends_with(".o"))
295 if (std::optional
<StringRef
> rerootedPath
=
296 findPathCombination(path
, config
->systemLibraryRoots
))
297 return *rerootedPath
;
302 uint32_t macho::getModTime(StringRef path
) {
303 if (config
->zeroModTime
)
306 fs::file_status stat
;
307 if (!fs::status(path
, stat
))
308 if (fs::exists(stat
))
309 return toTimeT(stat
.getLastModificationTime());
311 warn("failed to get modification time of " + path
);
315 void macho::printArchiveMemberLoad(StringRef reason
, const InputFile
*f
) {
316 if (config
->printEachFile
)
317 message(toString(f
));
318 if (config
->printWhyLoad
)
319 message(reason
+ " forced load of " + toString(f
));
322 macho::DependencyTracker::DependencyTracker(StringRef path
)
323 : path(path
), active(!path
.empty()) {
324 if (active
&& fs::exists(path
) && !fs::can_write(path
)) {
325 warn("Ignoring dependency_info option since specified path is not "
331 void macho::DependencyTracker::write(StringRef version
,
332 const SetVector
<InputFile
*> &inputs
,
338 raw_fd_ostream
os(path
, ec
, fs::OF_None
);
340 warn("Error writing dependency info to file");
344 auto addDep
= [&os
](DepOpCode opcode
, const StringRef
&path
) {
345 // XXX: Even though DepOpCode's underlying type is uint8_t,
346 // this cast is still needed because Clang older than 10.x has a bug,
347 // where it doesn't know to cast the enum to its underlying type.
348 // Hence `<< DepOpCode` is ambiguous to it.
349 os
<< static_cast<uint8_t>(opcode
);
354 addDep(DepOpCode::Version
, version
);
356 // Sort the input by its names.
357 std::vector
<StringRef
> inputNames
;
358 inputNames
.reserve(inputs
.size());
359 for (InputFile
*f
: inputs
)
360 inputNames
.push_back(f
->getName());
361 llvm::sort(inputNames
);
363 for (const StringRef
&in
: inputNames
)
364 addDep(DepOpCode::Input
, in
);
366 for (const std::string
&f
: notFounds
)
367 addDep(DepOpCode::NotFound
, f
);
369 addDep(DepOpCode::Output
, output
);