Job.cpp 15 KB

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