1 //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
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 //===----------------------------------------------------------------------===//
9 // This is the entry point to the clang driver; it is a thin wrapper
10 // for functionality in the Driver clang library.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Driver/Driver.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Basic/Stack.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Compilation.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/ToolChain.h"
22 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Frontend/Utils.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Option/Option.h"
33 #include "llvm/Support/BuryPointer.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/CrashRecoveryContext.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/InitLLVM.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/Regex.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/StringSaver.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
51 #include <system_error>
52 using namespace clang;
53 using namespace clang::driver;
54 using namespace llvm::opt;
56 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
57 if (!CanonicalPrefixes) {
58 SmallString<128> ExecutablePath(Argv0);
59 // Do a PATH lookup if Argv0 isn't a valid path.
60 if (!llvm::sys::fs::exists(ExecutablePath))
61 if (llvm::ErrorOr<std::string> P =
62 llvm::sys::findProgramByName(ExecutablePath))
64 return ExecutablePath.str();
67 // This just needs to be some symbol in the binary; C++ doesn't
68 // allow taking the address of ::main however.
69 void *P = (void*) (intptr_t) GetExecutablePath;
70 return llvm::sys::fs::getMainExecutable(Argv0, P);
73 static const char *GetStableCStr(std::set<std::string> &SavedStrings,
75 return SavedStrings.insert(S).first->c_str();
78 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
80 /// The input string is a space separate list of edits to perform,
81 /// they are applied in order to the input argument lists. Edits
82 /// should be one of the following forms:
84 /// '#': Silence information about the changes to the command line arguments.
86 /// '^': Add FOO as a new argument at the beginning of the command line.
88 /// '+': Add FOO as a new argument at the end of the command line.
90 /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
93 /// 'xOPTION': Removes all instances of the literal argument OPTION.
95 /// 'XOPTION': Removes all instances of the literal argument OPTION,
96 /// and the following argument.
98 /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
99 /// at the end of the command line.
101 /// \param OS - The stream to write edit information to.
102 /// \param Args - The vector of command line arguments.
103 /// \param Edit - The override command to perform.
104 /// \param SavedStrings - Set to use for storing string representations.
105 static void ApplyOneQAOverride(raw_ostream &OS,
106 SmallVectorImpl<const char*> &Args,
108 std::set<std::string> &SavedStrings) {
109 // This does not need to be efficient.
111 if (Edit[0] == '^') {
113 GetStableCStr(SavedStrings, Edit.substr(1));
114 OS << "### Adding argument " << Str << " at beginning\n";
115 Args.insert(Args.begin() + 1, Str);
116 } else if (Edit[0] == '+') {
118 GetStableCStr(SavedStrings, Edit.substr(1));
119 OS << "### Adding argument " << Str << " at end\n";
121 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
122 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
123 StringRef MatchPattern = Edit.substr(2).split('/').first;
124 StringRef ReplPattern = Edit.substr(2).split('/').second;
125 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
127 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
128 // Ignore end-of-line response file markers
129 if (Args[i] == nullptr)
131 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
133 if (Repl != Args[i]) {
134 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
135 Args[i] = GetStableCStr(SavedStrings, Repl);
138 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
139 auto Option = Edit.substr(1);
140 for (unsigned i = 1; i < Args.size();) {
141 if (Option == Args[i]) {
142 OS << "### Deleting argument " << Args[i] << '\n';
143 Args.erase(Args.begin() + i);
144 if (Edit[0] == 'X') {
145 if (i < Args.size()) {
146 OS << "### Deleting argument " << Args[i] << '\n';
147 Args.erase(Args.begin() + i);
149 OS << "### Invalid X edit, end of command line!\n";
154 } else if (Edit[0] == 'O') {
155 for (unsigned i = 1; i < Args.size();) {
156 const char *A = Args[i];
157 // Ignore end-of-line response file markers
160 if (A[0] == '-' && A[1] == 'O' &&
162 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
163 ('0' <= A[2] && A[2] <= '9'))))) {
164 OS << "### Deleting argument " << Args[i] << '\n';
165 Args.erase(Args.begin() + i);
169 OS << "### Adding argument " << Edit << " at end\n";
170 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
172 OS << "### Unrecognized edit: " << Edit << "\n";
176 /// ApplyQAOverride - Apply a comma separate list of edits to the
177 /// input argument lists. See ApplyOneQAOverride.
178 static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
179 const char *OverrideStr,
180 std::set<std::string> &SavedStrings) {
181 raw_ostream *OS = &llvm::errs();
183 if (OverrideStr[0] == '#') {
188 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
190 // This does not need to be efficient.
192 const char *S = OverrideStr;
194 const char *End = ::strchr(S, ' ');
198 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
205 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
207 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
209 extern int cc1gen_reproducer_main(ArrayRef<const char *> Argv,
210 const char *Argv0, void *MainAddr);
212 static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
213 SmallVectorImpl<const char *> &ArgVector,
214 std::set<std::string> &SavedStrings) {
215 // Put target and mode arguments at the start of argument list so that
216 // arguments specified in command line could override them. Avoid putting
217 // them at index 0, as an option like '-cc1' must remain the first.
218 int InsertionPoint = 0;
219 if (ArgVector.size() > 0)
222 if (NameParts.DriverMode) {
223 // Add the mode flag to the arguments.
224 ArgVector.insert(ArgVector.begin() + InsertionPoint,
225 GetStableCStr(SavedStrings, NameParts.DriverMode));
228 if (NameParts.TargetIsValid) {
229 const char *arr[] = {"-target", GetStableCStr(SavedStrings,
230 NameParts.TargetPrefix)};
231 ArgVector.insert(ArgVector.begin() + InsertionPoint,
232 std::begin(arr), std::end(arr));
236 static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
237 SmallVectorImpl<const char *> &Opts) {
238 llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
239 // The first instance of '#' should be replaced with '=' in each option.
240 for (const char *Opt : Opts)
241 if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
242 *NumberSignPtr = '=';
245 static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
246 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
247 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
248 if (TheDriver.CCPrintOptions)
249 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
251 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
252 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
253 if (TheDriver.CCPrintHeaders)
254 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
256 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
257 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
258 if (TheDriver.CCLogDiagnostics)
259 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
262 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
263 const std::string &Path) {
264 // If the clang binary happens to be named cl.exe for compatibility reasons,
265 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
266 StringRef ExeBasename(llvm::sys::path::stem(Path));
267 if (ExeBasename.equals_lower("cl"))
268 ExeBasename = "clang-cl";
269 DiagClient->setPrefix(ExeBasename);
272 // This lets us create the DiagnosticsEngine with a properly-filled-out
273 // DiagnosticOptions instance.
274 static DiagnosticOptions *
275 CreateAndPopulateDiagOpts(ArrayRef<const char *> argv, bool &UseNewCC1Process) {
276 auto *DiagOpts = new DiagnosticOptions;
277 unsigned MissingArgIndex, MissingArgCount;
278 InputArgList Args = getDriverOptTable().ParseArgs(
279 argv.slice(1), MissingArgIndex, MissingArgCount);
280 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
281 // Any errors that would be diagnosed here will also be diagnosed later,
282 // when the DiagnosticsEngine actually exists.
283 (void)ParseDiagnosticArgs(*DiagOpts, Args);
286 Args.hasFlag(clang::driver::options::OPT_fno_integrated_cc1,
287 clang::driver::options::OPT_fintegrated_cc1,
288 /*Default=*/CLANG_SPAWN_CC1);
293 static void SetInstallDir(SmallVectorImpl<const char *> &argv,
294 Driver &TheDriver, bool CanonicalPrefixes) {
295 // Attempt to find the original path used to invoke the driver, to determine
296 // the installed path. We do this manually, because we want to support that
297 // path being a symlink.
298 SmallString<128> InstalledPath(argv[0]);
300 // Do a PATH lookup, if there are no directory components.
301 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
302 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
303 llvm::sys::path::filename(InstalledPath.str())))
304 InstalledPath = *Tmp;
306 // FIXME: We don't actually canonicalize this, we just make it absolute.
307 if (CanonicalPrefixes)
308 llvm::sys::fs::make_absolute(InstalledPath);
310 StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
311 if (llvm::sys::fs::exists(InstalledPathParent))
312 TheDriver.setInstalledDir(InstalledPathParent);
315 static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV) {
316 // If we call the cc1 tool from the clangDriver library (through
317 // Driver::CC1Main), we need to clean up the options usage count. The options
318 // are currently global, and they might have been used previously by the
320 llvm::cl::ResetAllOptionOccurrences();
322 llvm::BumpPtrAllocator A;
323 llvm::StringSaver Saver(A);
324 llvm::cl::ExpandResponseFiles(Saver, &llvm::cl::TokenizeGNUCommandLine, ArgV,
326 StringRef Tool = ArgV[1];
327 void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath;
329 return cc1_main(makeArrayRef(ArgV).slice(2), ArgV[0], GetExecutablePathVP);
330 if (Tool == "-cc1as")
331 return cc1as_main(makeArrayRef(ArgV).slice(2), ArgV[0],
332 GetExecutablePathVP);
333 if (Tool == "-cc1gen-reproducer")
334 return cc1gen_reproducer_main(makeArrayRef(ArgV).slice(2), ArgV[0],
335 GetExecutablePathVP);
336 // Reject unknown tools.
337 llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
338 << "Valid tools include '-cc1' and '-cc1as'.\n";
342 int main(int argc_, const char **argv_) {
344 llvm::InitLLVM X(argc_, argv_);
345 SmallVector<const char *, 256> argv(argv_, argv_ + argc_);
347 if (llvm::sys::Process::FixupStandardFileDescriptors())
350 llvm::InitializeAllTargets();
351 auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(argv[0]);
353 llvm::BumpPtrAllocator A;
354 llvm::StringSaver Saver(A);
356 // Parse response files using the GNU syntax, unless we're in CL mode. There
357 // are two ways to put clang in CL compatibility mode: argv[0] is either
358 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
359 // command line parsing can't happen until after response file parsing, so we
360 // have to manually search for a --driver-mode=cl argument the hard way.
361 // Finally, our -cc1 tools don't care which tokenization mode we use because
362 // response files written by clang will tokenize the same way in either mode.
363 bool ClangCLMode = false;
364 if (StringRef(TargetAndMode.DriverMode).equals("--driver-mode=cl") ||
365 llvm::find_if(argv, [](const char *F) {
366 return F && strcmp(F, "--driver-mode=cl") == 0;
370 enum { Default, POSIX, Windows } RSPQuoting = Default;
371 for (const char *F : argv) {
372 if (strcmp(F, "--rsp-quoting=posix") == 0)
374 else if (strcmp(F, "--rsp-quoting=windows") == 0)
375 RSPQuoting = Windows;
378 // Determines whether we want nullptr markers in argv to indicate response
379 // files end-of-lines. We only use this for the /LINK driver argument with
380 // clang-cl.exe on Windows.
381 bool MarkEOLs = ClangCLMode;
383 llvm::cl::TokenizerCallback Tokenizer;
384 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
385 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
387 Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
389 if (MarkEOLs && argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
391 llvm::cl::ExpandResponseFiles(Saver, Tokenizer, argv, MarkEOLs);
393 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
395 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
396 [](const char *A) { return A != nullptr; });
397 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
398 // If -cc1 came from a response file, remove the EOL sentinels.
400 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
401 argv.resize(newEnd - argv.begin());
403 return ExecuteCC1Tool(argv);
406 // Handle options that need handling before the real command line parsing in
407 // Driver::BuildCompilation()
408 bool CanonicalPrefixes = true;
409 for (int i = 1, size = argv.size(); i < size; ++i) {
410 // Skip end-of-line response file markers
411 if (argv[i] == nullptr)
413 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
414 CanonicalPrefixes = false;
419 // Handle CL and _CL_ which permits additional command line options to be
420 // prepended or appended.
422 // Arguments in "CL" are prepended.
423 llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
424 if (OptCL.hasValue()) {
425 SmallVector<const char *, 8> PrependedOpts;
426 getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
428 // Insert right after the program name to prepend to the argument list.
429 argv.insert(argv.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
431 // Arguments in "_CL_" are appended.
432 llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
433 if (Opt_CL_.hasValue()) {
434 SmallVector<const char *, 8> AppendedOpts;
435 getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
437 // Insert at the end of the argument list to append.
438 argv.append(AppendedOpts.begin(), AppendedOpts.end());
442 std::set<std::string> SavedStrings;
443 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
445 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
446 // FIXME: Driver shouldn't take extra initial argument.
447 ApplyQAOverride(argv, OverrideStr, SavedStrings);
450 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
452 // Whether the cc1 tool should be called inside the current process, or if we
453 // should spawn a new clang subprocess (old behavior).
454 // Not having an additional process saves some execution time of Windows,
455 // and makes debugging and profiling easier.
456 bool UseNewCC1Process;
458 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
459 CreateAndPopulateDiagOpts(argv, UseNewCC1Process);
461 TextDiagnosticPrinter *DiagClient
462 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
463 FixupDiagPrefixExeName(DiagClient, Path);
465 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
467 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
469 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
470 auto SerializedConsumer =
471 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
472 &*DiagOpts, /*MergeChildRecords=*/true);
473 Diags.setClient(new ChainedDiagnosticConsumer(
474 Diags.takeClient(), std::move(SerializedConsumer)));
477 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
479 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
480 SetInstallDir(argv, TheDriver, CanonicalPrefixes);
481 TheDriver.setTargetAndMode(TargetAndMode);
483 insertTargetAndModeArgs(TargetAndMode, argv, SavedStrings);
485 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
487 if (!UseNewCC1Process) {
488 TheDriver.CC1Main = &ExecuteCC1Tool;
489 // Ensure the CC1Command actually catches cc1 crashes
490 llvm::CrashRecoveryContext::Enable();
493 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
495 bool IsCrash = false;
496 if (C && !C->containsError()) {
497 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
498 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
500 // Force a crash to test the diagnostics.
501 if (TheDriver.GenReproducer) {
502 Diags.Report(diag::err_drv_force_crash)
503 << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
505 // Pretend that every command failed.
506 FailingCommands.clear();
507 for (const auto &J : C->getJobs())
508 if (const Command *C = dyn_cast<Command>(&J))
509 FailingCommands.push_back(std::make_pair(-1, C));
512 for (const auto &P : FailingCommands) {
513 int CommandRes = P.first;
514 const Command *FailingCommand = P.second;
518 // If result status is < 0, then the driver command signalled an error.
519 // If result status is 70, then the driver command reported a fatal error.
520 // On Windows, abort will return an exit code of 3. In these cases,
521 // generate additional diagnostic information if possible.
522 IsCrash = CommandRes < 0 || CommandRes == 70;
524 IsCrash |= CommandRes == 3;
527 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
533 Diags.getClient()->finish();
535 if (!UseNewCC1Process && IsCrash) {
536 // When crashing in -fintegrated-cc1 mode, bury the timer pointers, because
537 // the internal linked list might point to already released stack frames.
538 llvm::BuryPointer(llvm::TimerGroup::aquireDefaultGroup());
540 // If any timers were active but haven't been destroyed yet, print their
541 // results now. This happens in -disable-free mode.
542 llvm::TimerGroup::printAll(llvm::errs());
543 llvm::TimerGroup::clearAll();
547 // Exit status should not be negative on Win32, unless abnormal termination.
548 // Once abnormal termination was caught, negative status should not be
554 // If we have multiple failing commands, we return the result of the first