Job.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. //===- Job.cpp - Command to Execute ---------------------------------------===//
  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. #include "clang/Driver/Job.h"
  9. #include "clang/Basic/LLVM.h"
  10. #include "clang/Driver/Driver.h"
  11. #include "clang/Driver/DriverDiagnostic.h"
  12. #include "clang/Driver/InputInfo.h"
  13. #include "clang/Driver/Tool.h"
  14. #include "clang/Driver/ToolChain.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/StringSet.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/Support/CrashRecoveryContext.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/Path.h"
  24. #include "llvm/Support/PrettyStackTrace.h"
  25. #include "llvm/Support/Program.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <string>
  31. #include <system_error>
  32. #include <utility>
  33. using namespace clang;
  34. using namespace driver;
  35. Command::Command(const Action &Source, const Tool &Creator,
  36. ResponseFileSupport ResponseSupport, const char *Executable,
  37. const llvm::opt::ArgStringList &Arguments,
  38. ArrayRef<InputInfo> Inputs, ArrayRef<InputInfo> Outputs)
  39. : Source(Source), Creator(Creator), ResponseSupport(ResponseSupport),
  40. Executable(Executable), Arguments(Arguments) {
  41. for (const auto &II : Inputs)
  42. if (II.isFilename())
  43. InputInfoList.push_back(II);
  44. for (const auto &II : Outputs)
  45. if (II.isFilename())
  46. OutputFilenames.push_back(II.getFilename());
  47. }
  48. /// Check if the compiler flag in question should be skipped when
  49. /// emitting a reproducer. Also track how many arguments it has and if the
  50. /// option is some kind of include path.
  51. static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
  52. bool &IsInclude) {
  53. SkipNum = 2;
  54. // These flags are all of the form -Flag <Arg> and are treated as two
  55. // arguments. Therefore, we need to skip the flag and the next argument.
  56. bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
  57. .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
  58. .Cases("-o", "-dependency-file", true)
  59. .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
  60. .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
  61. .Default(false);
  62. if (ShouldSkip)
  63. return true;
  64. // Some include flags shouldn't be skipped if we have a crash VFS
  65. IsInclude = llvm::StringSwitch<bool>(Flag)
  66. .Cases("-include", "-header-include-file", true)
  67. .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
  68. .Cases("-internal-externc-isystem", "-iprefix", true)
  69. .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
  70. .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
  71. .Cases("-iframework", "-include-pch", true)
  72. .Default(false);
  73. if (IsInclude)
  74. return !HaveCrashVFS;
  75. // The remaining flags are treated as a single argument.
  76. // These flags are all of the form -Flag and have no second argument.
  77. ShouldSkip = llvm::StringSwitch<bool>(Flag)
  78. .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
  79. .Case("-MMD", true)
  80. .Default(false);
  81. // Match found.
  82. SkipNum = 1;
  83. if (ShouldSkip)
  84. return true;
  85. // These flags are treated as a single argument (e.g., -F<Dir>).
  86. StringRef FlagRef(Flag);
  87. IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
  88. if (IsInclude)
  89. return !HaveCrashVFS;
  90. if (FlagRef.startswith("-fmodules-cache-path="))
  91. return true;
  92. SkipNum = 0;
  93. return false;
  94. }
  95. void Command::writeResponseFile(raw_ostream &OS) const {
  96. // In a file list, we only write the set of inputs to the response file
  97. if (ResponseSupport.ResponseKind == ResponseFileSupport::RF_FileList) {
  98. for (const auto *Arg : InputFileList) {
  99. OS << Arg << '\n';
  100. }
  101. return;
  102. }
  103. // In regular response files, we send all arguments to the response file.
  104. // Wrapping all arguments in double quotes ensures that both Unix tools and
  105. // Windows tools understand the response file.
  106. for (const auto *Arg : Arguments) {
  107. OS << '"';
  108. for (; *Arg != '\0'; Arg++) {
  109. if (*Arg == '\"' || *Arg == '\\') {
  110. OS << '\\';
  111. }
  112. OS << *Arg;
  113. }
  114. OS << "\" ";
  115. }
  116. }
  117. void Command::buildArgvForResponseFile(
  118. llvm::SmallVectorImpl<const char *> &Out) const {
  119. // When not a file list, all arguments are sent to the response file.
  120. // This leaves us to set the argv to a single parameter, requesting the tool
  121. // to read the response file.
  122. if (ResponseSupport.ResponseKind != ResponseFileSupport::RF_FileList) {
  123. Out.push_back(Executable);
  124. Out.push_back(ResponseFileFlag.c_str());
  125. return;
  126. }
  127. llvm::StringSet<> Inputs;
  128. for (const auto *InputName : InputFileList)
  129. Inputs.insert(InputName);
  130. Out.push_back(Executable);
  131. // In a file list, build args vector ignoring parameters that will go in the
  132. // response file (elements of the InputFileList vector)
  133. bool FirstInput = true;
  134. for (const auto *Arg : Arguments) {
  135. if (Inputs.count(Arg) == 0) {
  136. Out.push_back(Arg);
  137. } else if (FirstInput) {
  138. FirstInput = false;
  139. Out.push_back(ResponseSupport.ResponseFlag);
  140. Out.push_back(ResponseFile);
  141. }
  142. }
  143. }
  144. /// Rewrite relative include-like flag paths to absolute ones.
  145. static void
  146. rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
  147. size_t NumArgs,
  148. llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
  149. using namespace llvm;
  150. using namespace sys;
  151. auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
  152. if (path::is_absolute(InInc)) // Nothing to do here...
  153. return false;
  154. std::error_code EC = fs::current_path(OutInc);
  155. if (EC)
  156. return false;
  157. path::append(OutInc, InInc);
  158. return true;
  159. };
  160. SmallString<128> NewInc;
  161. if (NumArgs == 1) {
  162. StringRef FlagRef(Args[Idx + NumArgs - 1]);
  163. assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
  164. "Expecting -I or -F");
  165. StringRef Inc = FlagRef.slice(2, StringRef::npos);
  166. if (getAbsPath(Inc, NewInc)) {
  167. SmallString<128> NewArg(FlagRef.slice(0, 2));
  168. NewArg += NewInc;
  169. IncFlags.push_back(std::move(NewArg));
  170. }
  171. return;
  172. }
  173. assert(NumArgs == 2 && "Not expecting more than two arguments");
  174. StringRef Inc(Args[Idx + NumArgs - 1]);
  175. if (!getAbsPath(Inc, NewInc))
  176. return;
  177. IncFlags.push_back(SmallString<128>(Args[Idx]));
  178. IncFlags.push_back(std::move(NewInc));
  179. }
  180. void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
  181. CrashReportInfo *CrashInfo) const {
  182. // Always quote the exe.
  183. OS << ' ';
  184. llvm::sys::printArg(OS, Executable, /*Quote=*/true);
  185. ArrayRef<const char *> Args = Arguments;
  186. SmallVector<const char *, 128> ArgsRespFile;
  187. if (ResponseFile != nullptr) {
  188. buildArgvForResponseFile(ArgsRespFile);
  189. Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
  190. }
  191. bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
  192. for (size_t i = 0, e = Args.size(); i < e; ++i) {
  193. const char *const Arg = Args[i];
  194. if (CrashInfo) {
  195. int NumArgs = 0;
  196. bool IsInclude = false;
  197. if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
  198. i += NumArgs - 1;
  199. continue;
  200. }
  201. // Relative includes need to be expanded to absolute paths.
  202. if (HaveCrashVFS && IsInclude) {
  203. SmallVector<SmallString<128>, 2> NewIncFlags;
  204. rewriteIncludes(Args, i, NumArgs, NewIncFlags);
  205. if (!NewIncFlags.empty()) {
  206. for (auto &F : NewIncFlags) {
  207. OS << ' ';
  208. llvm::sys::printArg(OS, F.c_str(), Quote);
  209. }
  210. i += NumArgs - 1;
  211. continue;
  212. }
  213. }
  214. auto Found = llvm::find_if(InputInfoList, [&Arg](const InputInfo &II) {
  215. return II.getFilename() == Arg;
  216. });
  217. if (Found != InputInfoList.end() &&
  218. (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
  219. // Replace the input file name with the crashinfo's file name.
  220. OS << ' ';
  221. StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
  222. llvm::sys::printArg(OS, ShortName.str(), Quote);
  223. continue;
  224. }
  225. }
  226. OS << ' ';
  227. llvm::sys::printArg(OS, Arg, Quote);
  228. }
  229. if (CrashInfo && HaveCrashVFS) {
  230. OS << ' ';
  231. llvm::sys::printArg(OS, "-ivfsoverlay", Quote);
  232. OS << ' ';
  233. llvm::sys::printArg(OS, CrashInfo->VFSPath.str(), Quote);
  234. // The leftover modules from the crash are stored in
  235. // <name>.cache/vfs/modules
  236. // Leave it untouched for pcm inspection and provide a clean/empty dir
  237. // path to contain the future generated module cache:
  238. // <name>.cache/vfs/repro-modules
  239. SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
  240. llvm::sys::path::parent_path(CrashInfo->VFSPath));
  241. llvm::sys::path::append(RelModCacheDir, "repro-modules");
  242. std::string ModCachePath = "-fmodules-cache-path=";
  243. ModCachePath.append(RelModCacheDir.c_str());
  244. OS << ' ';
  245. llvm::sys::printArg(OS, ModCachePath, Quote);
  246. }
  247. if (ResponseFile != nullptr) {
  248. OS << "\n Arguments passed via response file:\n";
  249. writeResponseFile(OS);
  250. // Avoiding duplicated newline terminator, since FileLists are
  251. // newline-separated.
  252. if (ResponseSupport.ResponseKind != ResponseFileSupport::RF_FileList)
  253. OS << "\n";
  254. OS << " (end of response file)";
  255. }
  256. OS << Terminator;
  257. }
  258. void Command::setResponseFile(const char *FileName) {
  259. ResponseFile = FileName;
  260. ResponseFileFlag = ResponseSupport.ResponseFlag;
  261. ResponseFileFlag += FileName;
  262. }
  263. void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
  264. Environment.reserve(NewEnvironment.size() + 1);
  265. Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
  266. Environment.push_back(nullptr);
  267. }
  268. void Command::setRedirectFiles(
  269. const std::vector<std::optional<std::string>> &Redirects) {
  270. RedirectFiles = Redirects;
  271. }
  272. void Command::PrintFileNames() const {
  273. if (PrintInputFilenames) {
  274. for (const auto &Arg : InputInfoList)
  275. llvm::outs() << llvm::sys::path::filename(Arg.getFilename()) << "\n";
  276. llvm::outs().flush();
  277. }
  278. }
  279. int Command::Execute(ArrayRef<std::optional<StringRef>> Redirects,
  280. std::string *ErrMsg, bool *ExecutionFailed) const {
  281. PrintFileNames();
  282. SmallVector<const char *, 128> Argv;
  283. if (ResponseFile == nullptr) {
  284. Argv.push_back(Executable);
  285. Argv.append(Arguments.begin(), Arguments.end());
  286. Argv.push_back(nullptr);
  287. } else {
  288. // If the command is too large, we need to put arguments in a response file.
  289. std::string RespContents;
  290. llvm::raw_string_ostream SS(RespContents);
  291. // Write file contents and build the Argv vector
  292. writeResponseFile(SS);
  293. buildArgvForResponseFile(Argv);
  294. Argv.push_back(nullptr);
  295. SS.flush();
  296. // Save the response file in the appropriate encoding
  297. if (std::error_code EC = writeFileWithEncoding(
  298. ResponseFile, RespContents, ResponseSupport.ResponseEncoding)) {
  299. if (ErrMsg)
  300. *ErrMsg = EC.message();
  301. if (ExecutionFailed)
  302. *ExecutionFailed = true;
  303. // Return -1 by convention (see llvm/include/llvm/Support/Program.h) to
  304. // indicate the requested executable cannot be started.
  305. return -1;
  306. }
  307. }
  308. std::optional<ArrayRef<StringRef>> Env;
  309. std::vector<StringRef> ArgvVectorStorage;
  310. if (!Environment.empty()) {
  311. assert(Environment.back() == nullptr &&
  312. "Environment vector should be null-terminated by now");
  313. ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
  314. Env = ArrayRef(ArgvVectorStorage);
  315. }
  316. auto Args = llvm::toStringRefArray(Argv.data());
  317. // Use Job-specific redirect files if they are present.
  318. if (!RedirectFiles.empty()) {
  319. std::vector<std::optional<StringRef>> RedirectFilesOptional;
  320. for (const auto &Ele : RedirectFiles)
  321. if (Ele)
  322. RedirectFilesOptional.push_back(std::optional<StringRef>(*Ele));
  323. else
  324. RedirectFilesOptional.push_back(std::nullopt);
  325. return llvm::sys::ExecuteAndWait(Executable, Args, Env,
  326. ArrayRef(RedirectFilesOptional),
  327. /*secondsToWait=*/0, /*memoryLimit=*/0,
  328. ErrMsg, ExecutionFailed, &ProcStat);
  329. }
  330. return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
  331. /*secondsToWait*/ 0, /*memoryLimit*/ 0,
  332. ErrMsg, ExecutionFailed, &ProcStat);
  333. }
  334. CC1Command::CC1Command(const Action &Source, const Tool &Creator,
  335. ResponseFileSupport ResponseSupport,
  336. const char *Executable,
  337. const llvm::opt::ArgStringList &Arguments,
  338. ArrayRef<InputInfo> Inputs, ArrayRef<InputInfo> Outputs)
  339. : Command(Source, Creator, ResponseSupport, Executable, Arguments, Inputs,
  340. Outputs) {
  341. InProcess = true;
  342. }
  343. void CC1Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
  344. CrashReportInfo *CrashInfo) const {
  345. if (InProcess)
  346. OS << " (in-process)\n";
  347. Command::Print(OS, Terminator, Quote, CrashInfo);
  348. }
  349. int CC1Command::Execute(ArrayRef<std::optional<StringRef>> Redirects,
  350. std::string *ErrMsg, bool *ExecutionFailed) const {
  351. // FIXME: Currently, if there're more than one job, we disable
  352. // -fintegrate-cc1. If we're no longer a integrated-cc1 job, fallback to
  353. // out-of-process execution. See discussion in https://reviews.llvm.org/D74447
  354. if (!InProcess)
  355. return Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  356. PrintFileNames();
  357. SmallVector<const char *, 128> Argv;
  358. Argv.push_back(getExecutable());
  359. Argv.append(getArguments().begin(), getArguments().end());
  360. Argv.push_back(nullptr);
  361. Argv.pop_back(); // The terminating null element shall not be part of the
  362. // slice (main() behavior).
  363. // This flag simply indicates that the program couldn't start, which isn't
  364. // applicable here.
  365. if (ExecutionFailed)
  366. *ExecutionFailed = false;
  367. llvm::CrashRecoveryContext CRC;
  368. CRC.DumpStackAndCleanupOnFailure = true;
  369. const void *PrettyState = llvm::SavePrettyStackState();
  370. const Driver &D = getCreator().getToolChain().getDriver();
  371. int R = 0;
  372. // Enter ExecuteCC1Tool() instead of starting up a new process
  373. if (!CRC.RunSafely([&]() { R = D.CC1Main(Argv); })) {
  374. llvm::RestorePrettyStackState(PrettyState);
  375. return CRC.RetCode;
  376. }
  377. return R;
  378. }
  379. void CC1Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
  380. // We don't support set a new environment when calling into ExecuteCC1Tool()
  381. llvm_unreachable(
  382. "The CC1Command doesn't support changing the environment vars!");
  383. }
  384. ForceSuccessCommand::ForceSuccessCommand(
  385. const Action &Source_, const Tool &Creator_,
  386. ResponseFileSupport ResponseSupport, const char *Executable_,
  387. const llvm::opt::ArgStringList &Arguments_, ArrayRef<InputInfo> Inputs,
  388. ArrayRef<InputInfo> Outputs)
  389. : Command(Source_, Creator_, ResponseSupport, Executable_, Arguments_,
  390. Inputs, Outputs) {}
  391. void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
  392. bool Quote, CrashReportInfo *CrashInfo) const {
  393. Command::Print(OS, "", Quote, CrashInfo);
  394. OS << " || (exit 0)" << Terminator;
  395. }
  396. int ForceSuccessCommand::Execute(ArrayRef<std::optional<StringRef>> Redirects,
  397. std::string *ErrMsg,
  398. bool *ExecutionFailed) const {
  399. int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  400. (void)Status;
  401. if (ExecutionFailed)
  402. *ExecutionFailed = false;
  403. return 0;
  404. }
  405. void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
  406. CrashReportInfo *CrashInfo) const {
  407. for (const auto &Job : *this)
  408. Job.Print(OS, Terminator, Quote, CrashInfo);
  409. }
  410. void JobList::clear() { Jobs.clear(); }