driver.cpp 21 KB

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