Job.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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::PrintFileNames() const {
  269. if (PrintInputFilenames) {
  270. for (const auto &Arg : InputInfoList)
  271. llvm::outs() << llvm::sys::path::filename(Arg.getFilename()) << "\n";
  272. llvm::outs().flush();
  273. }
  274. }
  275. int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
  276. std::string *ErrMsg, bool *ExecutionFailed) const {
  277. PrintFileNames();
  278. SmallVector<const char *, 128> Argv;
  279. if (ResponseFile == nullptr) {
  280. Argv.push_back(Executable);
  281. Argv.append(Arguments.begin(), Arguments.end());
  282. Argv.push_back(nullptr);
  283. } else {
  284. // If the command is too large, we need to put arguments in a response file.
  285. std::string RespContents;
  286. llvm::raw_string_ostream SS(RespContents);
  287. // Write file contents and build the Argv vector
  288. writeResponseFile(SS);
  289. buildArgvForResponseFile(Argv);
  290. Argv.push_back(nullptr);
  291. SS.flush();
  292. // Save the response file in the appropriate encoding
  293. if (std::error_code EC = writeFileWithEncoding(
  294. ResponseFile, RespContents, ResponseSupport.ResponseEncoding)) {
  295. if (ErrMsg)
  296. *ErrMsg = EC.message();
  297. if (ExecutionFailed)
  298. *ExecutionFailed = true;
  299. // Return -1 by convention (see llvm/include/llvm/Support/Program.h) to
  300. // indicate the requested executable cannot be started.
  301. return -1;
  302. }
  303. }
  304. Optional<ArrayRef<StringRef>> Env;
  305. std::vector<StringRef> ArgvVectorStorage;
  306. if (!Environment.empty()) {
  307. assert(Environment.back() == nullptr &&
  308. "Environment vector should be null-terminated by now");
  309. ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
  310. Env = makeArrayRef(ArgvVectorStorage);
  311. }
  312. auto Args = llvm::toStringRefArray(Argv.data());
  313. return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
  314. /*secondsToWait*/ 0, /*memoryLimit*/ 0,
  315. ErrMsg, ExecutionFailed, &ProcStat);
  316. }
  317. CC1Command::CC1Command(const Action &Source, const Tool &Creator,
  318. ResponseFileSupport ResponseSupport,
  319. const char *Executable,
  320. const llvm::opt::ArgStringList &Arguments,
  321. ArrayRef<InputInfo> Inputs, ArrayRef<InputInfo> Outputs)
  322. : Command(Source, Creator, ResponseSupport, Executable, Arguments, Inputs,
  323. Outputs) {
  324. InProcess = true;
  325. }
  326. void CC1Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
  327. CrashReportInfo *CrashInfo) const {
  328. if (InProcess)
  329. OS << " (in-process)\n";
  330. Command::Print(OS, Terminator, Quote, CrashInfo);
  331. }
  332. int CC1Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
  333. std::string *ErrMsg, bool *ExecutionFailed) const {
  334. // FIXME: Currently, if there're more than one job, we disable
  335. // -fintegrate-cc1. If we're no longer a integrated-cc1 job, fallback to
  336. // out-of-process execution. See discussion in https://reviews.llvm.org/D74447
  337. if (!InProcess)
  338. return Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  339. PrintFileNames();
  340. SmallVector<const char *, 128> Argv;
  341. Argv.push_back(getExecutable());
  342. Argv.append(getArguments().begin(), getArguments().end());
  343. Argv.push_back(nullptr);
  344. Argv.pop_back(); // The terminating null element shall not be part of the
  345. // slice (main() behavior).
  346. // This flag simply indicates that the program couldn't start, which isn't
  347. // applicable here.
  348. if (ExecutionFailed)
  349. *ExecutionFailed = false;
  350. llvm::CrashRecoveryContext CRC;
  351. CRC.DumpStackAndCleanupOnFailure = true;
  352. const void *PrettyState = llvm::SavePrettyStackState();
  353. const Driver &D = getCreator().getToolChain().getDriver();
  354. int R = 0;
  355. // Enter ExecuteCC1Tool() instead of starting up a new process
  356. if (!CRC.RunSafely([&]() { R = D.CC1Main(Argv); })) {
  357. llvm::RestorePrettyStackState(PrettyState);
  358. return CRC.RetCode;
  359. }
  360. return R;
  361. }
  362. void CC1Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
  363. // We don't support set a new environment when calling into ExecuteCC1Tool()
  364. llvm_unreachable(
  365. "The CC1Command doesn't support changing the environment vars!");
  366. }
  367. ForceSuccessCommand::ForceSuccessCommand(
  368. const Action &Source_, const Tool &Creator_,
  369. ResponseFileSupport ResponseSupport, const char *Executable_,
  370. const llvm::opt::ArgStringList &Arguments_, ArrayRef<InputInfo> Inputs,
  371. ArrayRef<InputInfo> Outputs)
  372. : Command(Source_, Creator_, ResponseSupport, Executable_, Arguments_,
  373. Inputs, Outputs) {}
  374. void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
  375. bool Quote, CrashReportInfo *CrashInfo) const {
  376. Command::Print(OS, "", Quote, CrashInfo);
  377. OS << " || (exit 0)" << Terminator;
  378. }
  379. int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
  380. std::string *ErrMsg,
  381. bool *ExecutionFailed) const {
  382. int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  383. (void)Status;
  384. if (ExecutionFailed)
  385. *ExecutionFailed = false;
  386. return 0;
  387. }
  388. void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
  389. CrashReportInfo *CrashInfo) const {
  390. for (const auto &Job : *this)
  391. Job.Print(OS, Terminator, Quote, CrashInfo);
  392. }
  393. void JobList::clear() { Jobs.clear(); }