1 //===--- Job.cpp - Command to Execute -------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Job.h"
11 #include "InputInfo.h"
12 #include "clang/Driver/Driver.h"
13 #include "clang/Driver/DriverDiagnostic.h"
14 #include "clang/Driver/Tool.h"
15 #include "clang/Driver/ToolChain.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang::driver;
29 using llvm::raw_ostream;
30 using llvm::StringRef;
33 Command::Command(const Action &Source, const Tool &Creator,
34 const char *Executable, const ArgStringList &Arguments,
35 ArrayRef<InputInfo> Inputs)
36 : Source(Source), Creator(Creator), Executable(Executable),
37 Arguments(Arguments), ResponseFile(nullptr) {
38 for (const auto &II : Inputs)
40 InputFilenames.push_back(II.getFilename());
43 /// @brief 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,
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)
60 // Some include flags shouldn't be skipped if we have a crash VFS
61 IsInclude = llvm::StringSwitch<bool>(Flag)
62 .Cases("-include", "-header-include-file", true)
63 .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
64 .Cases("-internal-externc-isystem", "-iprefix", true)
65 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
66 .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
67 .Cases("-iframework", "-include-pch", true)
70 return HaveCrashVFS ? false : true;
72 // The remaining flags are treated as a single argument.
74 // These flags are all of the form -Flag and have no second argument.
75 ShouldSkip = llvm::StringSwitch<bool>(Flag)
76 .Cases("-M", "-MM", "-MG", "-MP", "-MD", 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");
89 return HaveCrashVFS ? false : true;
90 if (FlagRef.startswith("-fmodules-cache-path="))
97 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
98 const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
100 if (!Quote && !Escape) {
105 // Quote and escape. This isn't really complete, but good enough.
107 for (const char c : Arg) {
108 if (c == '"' || c == '\\' || c == '$')
115 void Command::writeResponseFile(raw_ostream &OS) const {
116 // In a file list, we only write the set of inputs to the response file
117 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
118 for (const char *Arg : InputFileList) {
124 // In regular response files, we send all arguments to the response file.
125 // Wrapping all arguments in double quotes ensures that both Unix tools and
126 // Windows tools understand the response file.
127 for (const char *Arg : Arguments) {
130 for (; *Arg != '\0'; Arg++) {
131 if (*Arg == '\"' || *Arg == '\\') {
141 void Command::buildArgvForResponseFile(
142 llvm::SmallVectorImpl<const char *> &Out) const {
143 // When not a file list, all arguments are sent to the response file.
144 // This leaves us to set the argv to a single parameter, requesting the tool
145 // to read the response file.
146 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
147 Out.push_back(Executable);
148 Out.push_back(ResponseFileFlag.c_str());
152 llvm::StringSet<> Inputs;
153 for (const char *InputName : InputFileList)
154 Inputs.insert(InputName);
155 Out.push_back(Executable);
156 // In a file list, build args vector ignoring parameters that will go in the
157 // response file (elements of the InputFileList vector)
158 bool FirstInput = true;
159 for (const char *Arg : Arguments) {
160 if (Inputs.count(Arg) == 0) {
162 } else if (FirstInput) {
164 Out.push_back(Creator.getResponseFileFlag());
165 Out.push_back(ResponseFile);
170 /// @brief Rewrite relative include-like flag paths to absolute ones.
172 rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
174 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
175 using namespace llvm;
177 auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
178 if (path::is_absolute(InInc)) // Nothing to do here...
180 std::error_code EC = fs::current_path(OutInc);
183 path::append(OutInc, InInc);
187 SmallString<128> NewInc;
189 StringRef FlagRef(Args[Idx + NumArgs - 1]);
190 assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
191 "Expecting -I or -F");
192 StringRef Inc = FlagRef.slice(2, StringRef::npos);
193 if (getAbsPath(Inc, NewInc)) {
194 SmallString<128> NewArg(FlagRef.slice(0, 2));
196 IncFlags.push_back(std::move(NewArg));
201 assert(NumArgs == 2 && "Not expecting more than two arguments");
202 StringRef Inc(Args[Idx + NumArgs - 1]);
203 if (!getAbsPath(Inc, NewInc))
205 IncFlags.push_back(SmallString<128>(Args[Idx]));
206 IncFlags.push_back(std::move(NewInc));
209 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
210 CrashReportInfo *CrashInfo) const {
211 // Always quote the exe.
213 printArg(OS, Executable, /*Quote=*/true);
215 llvm::ArrayRef<const char *> Args = Arguments;
216 llvm::SmallVector<const char *, 128> ArgsRespFile;
217 if (ResponseFile != nullptr) {
218 buildArgvForResponseFile(ArgsRespFile);
219 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
222 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
223 for (size_t i = 0, e = Args.size(); i < e; ++i) {
224 const char *const Arg = Args[i];
228 bool IsInclude = false;
229 if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
234 // Relative includes need to be expanded to absolute paths.
235 if (HaveCrashVFS && IsInclude) {
236 SmallVector<SmallString<128>, 2> NewIncFlags;
237 rewriteIncludes(Args, i, NumArgs, NewIncFlags);
238 if (!NewIncFlags.empty()) {
239 for (auto &F : NewIncFlags) {
241 printArg(OS, F.c_str(), Quote);
248 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
249 [&Arg](StringRef IF) { return IF == Arg; });
250 if (Found != InputFilenames.end() &&
251 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
252 // Replace the input file name with the crashinfo's file name.
254 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
255 printArg(OS, ShortName.str(), Quote);
261 printArg(OS, Arg, Quote);
264 if (CrashInfo && HaveCrashVFS) {
266 printArg(OS, "-ivfsoverlay", Quote);
268 printArg(OS, CrashInfo->VFSPath.str(), Quote);
270 // The leftover modules from the crash are stored in
271 // <name>.cache/vfs/modules
272 // Leave it untouched for pcm inspection and provide a clean/empty dir
273 // path to contain the future generated module cache:
274 // <name>.cache/vfs/repro-modules
275 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
276 llvm::sys::path::parent_path(CrashInfo->VFSPath));
277 llvm::sys::path::append(RelModCacheDir, "repro-modules");
279 std::string ModCachePath = "-fmodules-cache-path=";
280 ModCachePath.append(RelModCacheDir.c_str());
283 printArg(OS, ModCachePath, Quote);
286 if (ResponseFile != nullptr) {
287 OS << "\n Arguments passed via response file:\n";
288 writeResponseFile(OS);
289 // Avoiding duplicated newline terminator, since FileLists are
290 // newline-separated.
291 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
293 OS << " (end of response file)";
299 void Command::setResponseFile(const char *FileName) {
300 ResponseFile = FileName;
301 ResponseFileFlag = Creator.getResponseFileFlag();
302 ResponseFileFlag += FileName;
305 void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
306 Environment.reserve(NewEnvironment.size() + 1);
307 Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
308 Environment.push_back(nullptr);
311 int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
312 std::string *ErrMsg, bool *ExecutionFailed) const {
313 SmallVector<const char*, 128> Argv;
316 if (Environment.empty()) {
319 assert(Environment.back() == nullptr &&
320 "Environment vector should be null-terminated by now");
321 Envp = const_cast<const char **>(Environment.data());
324 if (ResponseFile == nullptr) {
325 Argv.push_back(Executable);
326 Argv.append(Arguments.begin(), Arguments.end());
327 Argv.push_back(nullptr);
329 return llvm::sys::ExecuteAndWait(
330 Executable, Argv.data(), Envp, Redirects, /*secondsToWait*/ 0,
331 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
334 // We need to put arguments in a response file (command is too large)
335 // Open stream to store the response file contents
336 std::string RespContents;
337 llvm::raw_string_ostream SS(RespContents);
339 // Write file contents and build the Argv vector
340 writeResponseFile(SS);
341 buildArgvForResponseFile(Argv);
342 Argv.push_back(nullptr);
345 // Save the response file in the appropriate encoding
346 if (std::error_code EC = writeFileWithEncoding(
347 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
349 *ErrMsg = EC.message();
351 *ExecutionFailed = true;
355 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), Envp, Redirects,
357 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
360 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
361 const char *Executable_,
362 const ArgStringList &Arguments_,
363 ArrayRef<InputInfo> Inputs,
364 std::unique_ptr<Command> Fallback_)
365 : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
366 Fallback(std::move(Fallback_)) {}
368 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
369 bool Quote, CrashReportInfo *CrashInfo) const {
370 Command::Print(OS, "", Quote, CrashInfo);
372 Fallback->Print(OS, Terminator, Quote, CrashInfo);
375 static bool ShouldFallback(int ExitCode) {
376 // FIXME: We really just want to fall back for internal errors, such
377 // as when some symbol cannot be mangled, when we should be able to
378 // parse something but can't, etc.
379 return ExitCode != 0;
382 int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
383 std::string *ErrMsg, bool *ExecutionFailed) const {
384 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
385 if (!ShouldFallback(PrimaryStatus))
386 return PrimaryStatus;
388 // Clear ExecutionFailed and ErrMsg before falling back.
392 *ExecutionFailed = false;
394 const Driver &D = getCreator().getToolChain().getDriver();
395 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
397 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
398 return SecondaryStatus;
401 ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
402 const Tool &Creator_,
403 const char *Executable_,
404 const ArgStringList &Arguments_,
405 ArrayRef<InputInfo> Inputs)
406 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
408 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
409 bool Quote, CrashReportInfo *CrashInfo) const {
410 Command::Print(OS, "", Quote, CrashInfo);
411 OS << " || (exit 0)" << Terminator;
414 int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
416 bool *ExecutionFailed) const {
417 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
420 *ExecutionFailed = false;
424 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
425 CrashReportInfo *CrashInfo) const {
426 for (const auto &Job : *this)
427 Job.Print(OS, Terminator, Quote, CrashInfo);
430 void JobList::clear() { Jobs.clear(); }