driver.cpp 24 KB

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