1 //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
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 // This is the entry point to the clang driver; it is a thin wrapper
10 // for functionality in the Driver clang library.
11 //
12 //===----------------------------------------------------------------------===//
13
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/PrettyStackTrace.h"
42 #include "llvm/Support/Process.h"
43 #include "llvm/Support/Program.h"
44 #include "llvm/Support/Regex.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/StringSaver.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <memory>
51 #include <set>
52 #include <system_error>
53 using namespace clang;
54 using namespace clang::driver;
55 using namespace llvm::opt;
56
GetExecutablePath(const char * Argv0,bool CanonicalPrefixes)57 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
58 if (!CanonicalPrefixes) {
59 SmallString<128> ExecutablePath(Argv0);
60 // Do a PATH lookup if Argv0 isn't a valid path.
61 if (!llvm::sys::fs::exists(ExecutablePath))
62 if (llvm::ErrorOr<std::string> P =
63 llvm::sys::findProgramByName(ExecutablePath))
64 ExecutablePath = *P;
65 return std::string(ExecutablePath.str());
66 }
67
68 // This just needs to be some symbol in the binary; C++ doesn't
69 // allow taking the address of ::main however.
70 void *P = (void*) (intptr_t) GetExecutablePath;
71 return llvm::sys::fs::getMainExecutable(Argv0, P);
72 }
73
GetStableCStr(std::set<std::string> & SavedStrings,StringRef S)74 static const char *GetStableCStr(std::set<std::string> &SavedStrings,
75 StringRef S) {
76 return SavedStrings.insert(std::string(S)).first->c_str();
77 }
78
79 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
80 ///
81 /// The input string is a space separate list of edits to perform,
82 /// they are applied in order to the input argument lists. Edits
83 /// should be one of the following forms:
84 ///
85 /// '#': Silence information about the changes to the command line arguments.
86 ///
87 /// '^': Add FOO as a new argument at the beginning of the command line.
88 ///
89 /// '+': Add FOO as a new argument at the end of the command line.
90 ///
91 /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
92 /// line.
93 ///
94 /// 'xOPTION': Removes all instances of the literal argument OPTION.
95 ///
96 /// 'XOPTION': Removes all instances of the literal argument OPTION,
97 /// and the following argument.
98 ///
99 /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
100 /// at the end of the command line.
101 ///
102 /// \param OS - The stream to write edit information to.
103 /// \param Args - The vector of command line arguments.
104 /// \param Edit - The override command to perform.
105 /// \param SavedStrings - Set to use for storing string representations.
ApplyOneQAOverride(raw_ostream & OS,SmallVectorImpl<const char * > & Args,StringRef Edit,std::set<std::string> & SavedStrings)106 static void ApplyOneQAOverride(raw_ostream &OS,
107 SmallVectorImpl<const char*> &Args,
108 StringRef Edit,
109 std::set<std::string> &SavedStrings) {
110 // This does not need to be efficient.
111
112 if (Edit[0] == '^') {
113 const char *Str =
114 GetStableCStr(SavedStrings, Edit.substr(1));
115 OS << "### Adding argument " << Str << " at beginning\n";
116 Args.insert(Args.begin() + 1, Str);
117 } else if (Edit[0] == '+') {
118 const char *Str =
119 GetStableCStr(SavedStrings, Edit.substr(1));
120 OS << "### Adding argument " << Str << " at end\n";
121 Args.push_back(Str);
122 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
123 Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
124 StringRef MatchPattern = Edit.substr(2).split('/').first;
125 StringRef ReplPattern = Edit.substr(2).split('/').second;
126 ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
127
128 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
129 // Ignore end-of-line response file markers
130 if (Args[i] == nullptr)
131 continue;
132 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
133
134 if (Repl != Args[i]) {
135 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
136 Args[i] = GetStableCStr(SavedStrings, Repl);
137 }
138 }
139 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
140 auto Option = Edit.substr(1);
141 for (unsigned i = 1; i < Args.size();) {
142 if (Option == Args[i]) {
143 OS << "### Deleting argument " << Args[i] << '\n';
144 Args.erase(Args.begin() + i);
145 if (Edit[0] == 'X') {
146 if (i < Args.size()) {
147 OS << "### Deleting argument " << Args[i] << '\n';
148 Args.erase(Args.begin() + i);
149 } else
150 OS << "### Invalid X edit, end of command line!\n";
151 }
152 } else
153 ++i;
154 }
155 } else if (Edit[0] == 'O') {
156 for (unsigned i = 1; i < Args.size();) {
157 const char *A = Args[i];
158 // Ignore end-of-line response file markers
159 if (A == nullptr)
160 continue;
161 if (A[0] == '-' && A[1] == 'O' &&
162 (A[2] == '\0' ||
163 (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
164 ('0' <= A[2] && A[2] <= '9'))))) {
165 OS << "### Deleting argument " << Args[i] << '\n';
166 Args.erase(Args.begin() + i);
167 } else
168 ++i;
169 }
170 OS << "### Adding argument " << Edit << " at end\n";
171 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
172 } else {
173 OS << "### Unrecognized edit: " << Edit << "\n";
174 }
175 }
176
177 /// ApplyQAOverride - Apply a comma separate list of edits to the
178 /// input argument lists. See ApplyOneQAOverride.
ApplyQAOverride(SmallVectorImpl<const char * > & Args,const char * OverrideStr,std::set<std::string> & SavedStrings)179 static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
180 const char *OverrideStr,
181 std::set<std::string> &SavedStrings) {
182 raw_ostream *OS = &llvm::errs();
183
184 if (OverrideStr[0] == '#') {
185 ++OverrideStr;
186 OS = &llvm::nulls();
187 }
188
189 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
190
191 // This does not need to be efficient.
192
193 const char *S = OverrideStr;
194 while (*S) {
195 const char *End = ::strchr(S, ' ');
196 if (!End)
197 End = S + strlen(S);
198 if (End != S)
199 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
200 S = End;
201 if (*S != '\0')
202 ++S;
203 }
204 }
205
206 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
207 void *MainAddr);
208 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
209 void *MainAddr);
210
insertTargetAndModeArgs(const ParsedClangName & NameParts,SmallVectorImpl<const char * > & ArgVector,std::set<std::string> & SavedStrings)211 static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
212 SmallVectorImpl<const char *> &ArgVector,
213 std::set<std::string> &SavedStrings) {
214 // Put target and mode arguments at the start of argument list so that
215 // arguments specified in command line could override them. Avoid putting
216 // them at index 0, as an option like '-cc1' must remain the first.
217 int InsertionPoint = 0;
218 if (ArgVector.size() > 0)
219 ++InsertionPoint;
220
221 if (NameParts.DriverMode) {
222 // Add the mode flag to the arguments.
223 ArgVector.insert(ArgVector.begin() + InsertionPoint,
224 GetStableCStr(SavedStrings, NameParts.DriverMode));
225 }
226
227 if (NameParts.TargetIsValid) {
228 const char *arr[] = {"-target", GetStableCStr(SavedStrings,
229 NameParts.TargetPrefix)};
230 ArgVector.insert(ArgVector.begin() + InsertionPoint,
231 std::begin(arr), std::end(arr));
232 }
233 }
234
getCLEnvVarOptions(std::string & EnvValue,llvm::StringSaver & Saver,SmallVectorImpl<const char * > & Opts)235 static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
236 SmallVectorImpl<const char *> &Opts) {
237 llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
238 // The first instance of '#' should be replaced with '=' in each option.
239 for (const char *Opt : Opts)
240 if (char *NumberSignPtr = const_cast<char *>(::strchr(Opt, '#')))
241 *NumberSignPtr = '=';
242 }
243
SetBackdoorDriverOutputsFromEnvVars(Driver & TheDriver)244 static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
245 auto CheckEnvVar = [](const char *EnvOptSet, const char *EnvOptFile,
246 std::string &OptFile) {
247 bool OptSet = !!::getenv(EnvOptSet);
248 if (OptSet) {
249 if (const char *Var = ::getenv(EnvOptFile))
250 OptFile = Var;
251 }
252 return OptSet;
253 };
254
255 TheDriver.CCPrintOptions =
256 CheckEnvVar("CC_PRINT_OPTIONS", "CC_PRINT_OPTIONS_FILE",
257 TheDriver.CCPrintOptionsFilename);
258 TheDriver.CCPrintHeaders =
259 CheckEnvVar("CC_PRINT_HEADERS", "CC_PRINT_HEADERS_FILE",
260 TheDriver.CCPrintHeadersFilename);
261 TheDriver.CCLogDiagnostics =
262 CheckEnvVar("CC_LOG_DIAGNOSTICS", "CC_LOG_DIAGNOSTICS_FILE",
263 TheDriver.CCLogDiagnosticsFilename);
264 TheDriver.CCPrintProcessStats =
265 CheckEnvVar("CC_PRINT_PROC_STAT", "CC_PRINT_PROC_STAT_FILE",
266 TheDriver.CCPrintStatReportFilename);
267 }
268
FixupDiagPrefixExeName(TextDiagnosticPrinter * DiagClient,const std::string & Path)269 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
270 const std::string &Path) {
271 // If the clang binary happens to be named cl.exe for compatibility reasons,
272 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
273 StringRef ExeBasename(llvm::sys::path::stem(Path));
274 if (ExeBasename.equals_insensitive("cl"))
275 ExeBasename = "clang-cl";
276 DiagClient->setPrefix(std::string(ExeBasename));
277 }
278
279 // This lets us create the DiagnosticsEngine with a properly-filled-out
280 // DiagnosticOptions instance.
281 static DiagnosticOptions *
CreateAndPopulateDiagOpts(ArrayRef<const char * > argv,bool & UseNewCC1Process)282 CreateAndPopulateDiagOpts(ArrayRef<const char *> argv, bool &UseNewCC1Process) {
283 auto *DiagOpts = new DiagnosticOptions;
284 unsigned MissingArgIndex, MissingArgCount;
285 InputArgList Args = getDriverOptTable().ParseArgs(
286 argv.slice(1), MissingArgIndex, MissingArgCount);
287 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
288 // Any errors that would be diagnosed here will also be diagnosed later,
289 // when the DiagnosticsEngine actually exists.
290 (void)ParseDiagnosticArgs(*DiagOpts, Args);
291
292 UseNewCC1Process =
293 Args.hasFlag(clang::driver::options::OPT_fno_integrated_cc1,
294 clang::driver::options::OPT_fintegrated_cc1,
295 /*Default=*/CLANG_SPAWN_CC1);
296
297 return DiagOpts;
298 }
299
SetInstallDir(SmallVectorImpl<const char * > & argv,Driver & TheDriver,bool CanonicalPrefixes)300 static void SetInstallDir(SmallVectorImpl<const char *> &argv,
301 Driver &TheDriver, bool CanonicalPrefixes) {
302 // Attempt to find the original path used to invoke the driver, to determine
303 // the installed path. We do this manually, because we want to support that
304 // path being a symlink.
305 SmallString<128> InstalledPath(argv[0]);
306
307 // Do a PATH lookup, if there are no directory components.
308 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
309 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
310 llvm::sys::path::filename(InstalledPath.str())))
311 InstalledPath = *Tmp;
312
313 // FIXME: We don't actually canonicalize this, we just make it absolute.
314 if (CanonicalPrefixes)
315 llvm::sys::fs::make_absolute(InstalledPath);
316
317 StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath));
318 if (llvm::sys::fs::exists(InstalledPathParent))
319 TheDriver.setInstalledDir(InstalledPathParent);
320 }
321
ExecuteCC1Tool(SmallVectorImpl<const char * > & ArgV)322 static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV) {
323 // If we call the cc1 tool from the clangDriver library (through
324 // Driver::CC1Main), we need to clean up the options usage count. The options
325 // are currently global, and they might have been used previously by the
326 // driver.
327 llvm::cl::ResetAllOptionOccurrences();
328
329 llvm::BumpPtrAllocator A;
330 llvm::StringSaver Saver(A);
331 llvm::cl::ExpandResponseFiles(Saver, &llvm::cl::TokenizeGNUCommandLine, ArgV,
332 /*MarkEOLs=*/false);
333 StringRef Tool = ArgV[1];
334 void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath;
335 if (Tool == "-cc1")
336 return cc1_main(makeArrayRef(ArgV).slice(1), ArgV[0], GetExecutablePathVP);
337 if (Tool == "-cc1as")
338 return cc1as_main(makeArrayRef(ArgV).slice(2), ArgV[0],
339 GetExecutablePathVP);
340 // Reject unknown tools.
341 llvm::errs() << "error: unknown integrated tool '" << Tool << "'. "
342 << "Valid tools include '-cc1' and '-cc1as'.\n";
343 return 1;
344 }
345
346 extern "C" int ZigClang_main(int Argc, const char **Argv);
ZigClang_main(int Argc,const char ** Argv)347 int ZigClang_main(int Argc, const char **Argv) {
348 noteBottomOfStack();
349 // ZIG PATCH: On Windows, InitLLVM calls GetCommandLineW(),
350 // and overwrites the args. We don't want it to do that,
351 // and we also don't need the signal handlers it installs
352 // (we have our own already), so we just use llvm_shutdown_obj
353 // instead.
354 // llvm::InitLLVM X(Argc, Argv);
355 llvm::llvm_shutdown_obj X;
356
357 llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
358 " and include the crash backtrace, preprocessed "
359 "source, and associated run script.\n");
360 size_t argv_offset = (strcmp(Argv[1], "-cc1") == 0 || strcmp(Argv[1], "-cc1as") == 0) ? 0 : 1;
361 SmallVector<const char *, 256> Args(Argv + argv_offset, Argv + Argc);
362
363 if (llvm::sys::Process::FixupStandardFileDescriptors())
364 return 1;
365
366 llvm::InitializeAllTargets();
367
368 llvm::BumpPtrAllocator A;
369 llvm::StringSaver Saver(A);
370
371 // Parse response files using the GNU syntax, unless we're in CL mode. There
372 // are two ways to put clang in CL compatibility mode: Args[0] is either
373 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
374 // command line parsing can't happen until after response file parsing, so we
375 // have to manually search for a --driver-mode=cl argument the hard way.
376 // Finally, our -cc1 tools don't care which tokenization mode we use because
377 // response files written by clang will tokenize the same way in either mode.
378 bool ClangCLMode =
379 IsClangCL(getDriverMode(Args[0], llvm::makeArrayRef(Args).slice(1)));
380 enum { Default, POSIX, Windows } RSPQuoting = Default;
381 for (const char *F : Args) {
382 if (strcmp(F, "--rsp-quoting=posix") == 0)
383 RSPQuoting = POSIX;
384 else if (strcmp(F, "--rsp-quoting=windows") == 0)
385 RSPQuoting = Windows;
386 }
387
388 // Determines whether we want nullptr markers in Args to indicate response
389 // files end-of-lines. We only use this for the /LINK driver argument with
390 // clang-cl.exe on Windows.
391 bool MarkEOLs = ClangCLMode;
392
393 llvm::cl::TokenizerCallback Tokenizer;
394 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
395 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
396 else
397 Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
398
399 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).startswith("-cc1"))
400 MarkEOLs = false;
401 llvm::cl::ExpandResponseFiles(Saver, Tokenizer, Args, MarkEOLs);
402
403 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
404 // file.
405 auto FirstArg = std::find_if(Args.begin() + 1, Args.end(),
406 [](const char *A) { return A != nullptr; });
407 if (FirstArg != Args.end() && StringRef(*FirstArg).startswith("-cc1")) {
408 // If -cc1 came from a response file, remove the EOL sentinels.
409 if (MarkEOLs) {
410 auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
411 Args.resize(newEnd - Args.begin());
412 }
413 return ExecuteCC1Tool(Args);
414 }
415
416 // Handle options that need handling before the real command line parsing in
417 // Driver::BuildCompilation()
418 bool CanonicalPrefixes = true;
419 for (int i = 1, size = Args.size(); i < size; ++i) {
420 // Skip end-of-line response file markers
421 if (Args[i] == nullptr)
422 continue;
423 if (StringRef(Args[i]) == "-no-canonical-prefixes") {
424 CanonicalPrefixes = false;
425 break;
426 }
427 }
428
429 // Handle CL and _CL_ which permits additional command line options to be
430 // prepended or appended.
431 if (ClangCLMode) {
432 // Arguments in "CL" are prepended.
433 llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
434 if (OptCL.hasValue()) {
435 SmallVector<const char *, 8> PrependedOpts;
436 getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
437
438 // Insert right after the program name to prepend to the argument list.
439 Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
440 }
441 // Arguments in "_CL_" are appended.
442 llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
443 if (Opt_CL_.hasValue()) {
444 SmallVector<const char *, 8> AppendedOpts;
445 getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
446
447 // Insert at the end of the argument list to append.
448 Args.append(AppendedOpts.begin(), AppendedOpts.end());
449 }
450 }
451
452 std::set<std::string> SavedStrings;
453 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
454 // scenes.
455 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
456 // FIXME: Driver shouldn't take extra initial argument.
457 ApplyQAOverride(Args, OverrideStr, SavedStrings);
458 }
459
460 // Pass local param `Argv[0]` as fallback.
461 // See https://github.com/ziglang/zig/pull/3292 .
462 std::string Path = GetExecutablePath(Argv[0], CanonicalPrefixes);
463
464 // Whether the cc1 tool should be called inside the current process, or if we
465 // should spawn a new clang subprocess (old behavior).
466 // Not having an additional process saves some execution time of Windows,
467 // and makes debugging and profiling easier.
468 bool UseNewCC1Process;
469
470 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
471 CreateAndPopulateDiagOpts(Args, UseNewCC1Process);
472
473 TextDiagnosticPrinter *DiagClient
474 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
475 FixupDiagPrefixExeName(DiagClient, Path);
476
477 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
478
479 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
480
481 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
482 auto SerializedConsumer =
483 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
484 &*DiagOpts, /*MergeChildRecords=*/true);
485 Diags.setClient(new ChainedDiagnosticConsumer(
486 Diags.takeClient(), std::move(SerializedConsumer)));
487 }
488
489 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
490
491 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
492 SetInstallDir(Args, TheDriver, CanonicalPrefixes);
493 auto TargetAndMode = ToolChain::getTargetAndModeFromProgramName(Args[0]);
494 TheDriver.setTargetAndMode(TargetAndMode);
495
496 insertTargetAndModeArgs(TargetAndMode, Args, SavedStrings);
497
498 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
499
500 if (!UseNewCC1Process) {
501 TheDriver.CC1Main = &ExecuteCC1Tool;
502 // Ensure the CC1Command actually catches cc1 crashes
503 llvm::CrashRecoveryContext::Enable();
504 }
505
506 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
507 int Res = 1;
508 bool IsCrash = false;
509 if (C && !C->containsError()) {
510 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
511 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
512
513 // Force a crash to test the diagnostics.
514 if (TheDriver.GenReproducer) {
515 Diags.Report(diag::err_drv_force_crash)
516 << !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
517
518 // Pretend that every command failed.
519 FailingCommands.clear();
520 for (const auto &J : C->getJobs())
521 if (const Command *C = dyn_cast<Command>(&J))
522 FailingCommands.push_back(std::make_pair(-1, C));
523
524 // Print the bug report message that would be printed if we did actually
525 // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
526 if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
527 llvm::dbgs() << llvm::getBugReportMsg();
528 }
529
530 for (const auto &P : FailingCommands) {
531 int CommandRes = P.first;
532 const Command *FailingCommand = P.second;
533 if (!Res)
534 Res = CommandRes;
535
536 // If result status is < 0, then the driver command signalled an error.
537 // If result status is 70, then the driver command reported a fatal error.
538 // On Windows, abort will return an exit code of 3. In these cases,
539 // generate additional diagnostic information if possible.
540 IsCrash = CommandRes < 0 || CommandRes == 70;
541 #ifdef _WIN32
542 IsCrash |= CommandRes == 3;
543 #endif
544 #if LLVM_ON_UNIX
545 // When running in integrated-cc1 mode, the CrashRecoveryContext returns
546 // the same codes as if the program crashed. See section "Exit Status for
547 // Commands":
548 // https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html
549 IsCrash |= CommandRes > 128;
550 #endif
551 if (IsCrash) {
552 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
553 break;
554 }
555 }
556 }
557
558 Diags.getClient()->finish();
559
560 if (!UseNewCC1Process && IsCrash) {
561 // When crashing in -fintegrated-cc1 mode, bury the timer pointers, because
562 // the internal linked list might point to already released stack frames.
563 llvm::BuryPointer(llvm::TimerGroup::aquireDefaultGroup());
564 } else {
565 // If any timers were active but haven't been destroyed yet, print their
566 // results now. This happens in -disable-free mode.
567 llvm::TimerGroup::printAll(llvm::errs());
568 llvm::TimerGroup::clearAll();
569 }
570
571 #ifdef _WIN32
572 // Exit status should not be negative on Win32, unless abnormal termination.
573 // Once abnormal termination was caught, negative status should not be
574 // propagated.
575 if (Res < 0)
576 Res = 1;
577 #endif
578
579 // If we have multiple failing commands, we return the result of the first
580 // failing command.
581 return Res;
582 }
583