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/Basic/LLVM.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Tool.h"
16 #include "clang/Driver/ToolChain.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.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"
31 #include <system_error>
34 using namespace clang;
35 using namespace driver;
37 Command::Command(const Action &Source, const Tool &Creator,
38 const char *Executable,
39 const llvm::opt::ArgStringList &Arguments,
40 ArrayRef<InputInfo> Inputs)
41 : Source(Source), Creator(Creator), Executable(Executable),
42 Arguments(Arguments) {
43 for (const auto &II : Inputs)
45 InputFilenames.push_back(II.getFilename());
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,
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)
65 // Some include flags shouldn't be skipped if we have a crash VFS
66 IsInclude = llvm::StringSwitch<bool>(Flag)
67 .Cases("-include", "-header-include-file", true)
68 .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
69 .Cases("-internal-externc-isystem", "-iprefix", true)
70 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
71 .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
72 .Cases("-iframework", "-include-pch", true)
77 // The remaining flags are treated as a single argument.
79 // These flags are all of the form -Flag and have no second argument.
80 ShouldSkip = llvm::StringSwitch<bool>(Flag)
81 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
90 // These flags are treated as a single argument (e.g., -F<Dir>).
91 StringRef FlagRef(Flag);
92 IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
95 if (FlagRef.startswith("-fmodules-cache-path="))
102 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
103 const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
105 if (!Quote && !Escape) {
110 // Quote and escape. This isn't really complete, but good enough.
112 for (const auto c : Arg) {
113 if (c == '"' || c == '\\' || c == '$')
120 void Command::writeResponseFile(raw_ostream &OS) const {
121 // In a file list, we only write the set of inputs to the response file
122 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
123 for (const auto *Arg : InputFileList) {
129 // In regular response files, we send all arguments to the response file.
130 // Wrapping all arguments in double quotes ensures that both Unix tools and
131 // Windows tools understand the response file.
132 for (const auto *Arg : Arguments) {
135 for (; *Arg != '\0'; Arg++) {
136 if (*Arg == '\"' || *Arg == '\\') {
146 void Command::buildArgvForResponseFile(
147 llvm::SmallVectorImpl<const char *> &Out) const {
148 // When not a file list, all arguments are sent to the response file.
149 // This leaves us to set the argv to a single parameter, requesting the tool
150 // to read the response file.
151 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
152 Out.push_back(Executable);
153 Out.push_back(ResponseFileFlag.c_str());
157 llvm::StringSet<> Inputs;
158 for (const auto *InputName : InputFileList)
159 Inputs.insert(InputName);
160 Out.push_back(Executable);
161 // In a file list, build args vector ignoring parameters that will go in the
162 // response file (elements of the InputFileList vector)
163 bool FirstInput = true;
164 for (const auto *Arg : Arguments) {
165 if (Inputs.count(Arg) == 0) {
167 } else if (FirstInput) {
169 Out.push_back(Creator.getResponseFileFlag());
170 Out.push_back(ResponseFile);
175 /// Rewrite relative include-like flag paths to absolute ones.
177 rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
179 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
180 using namespace llvm;
183 auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
184 if (path::is_absolute(InInc)) // Nothing to do here...
186 std::error_code EC = fs::current_path(OutInc);
189 path::append(OutInc, InInc);
193 SmallString<128> NewInc;
195 StringRef FlagRef(Args[Idx + NumArgs - 1]);
196 assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
197 "Expecting -I or -F");
198 StringRef Inc = FlagRef.slice(2, StringRef::npos);
199 if (getAbsPath(Inc, NewInc)) {
200 SmallString<128> NewArg(FlagRef.slice(0, 2));
202 IncFlags.push_back(std::move(NewArg));
207 assert(NumArgs == 2 && "Not expecting more than two arguments");
208 StringRef Inc(Args[Idx + NumArgs - 1]);
209 if (!getAbsPath(Inc, NewInc))
211 IncFlags.push_back(SmallString<128>(Args[Idx]));
212 IncFlags.push_back(std::move(NewInc));
215 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
216 CrashReportInfo *CrashInfo) const {
217 // Always quote the exe.
219 printArg(OS, Executable, /*Quote=*/true);
221 ArrayRef<const char *> Args = Arguments;
222 SmallVector<const char *, 128> ArgsRespFile;
223 if (ResponseFile != nullptr) {
224 buildArgvForResponseFile(ArgsRespFile);
225 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
228 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
229 for (size_t i = 0, e = Args.size(); i < e; ++i) {
230 const char *const Arg = Args[i];
234 bool IsInclude = false;
235 if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
240 // Relative includes need to be expanded to absolute paths.
241 if (HaveCrashVFS && IsInclude) {
242 SmallVector<SmallString<128>, 2> NewIncFlags;
243 rewriteIncludes(Args, i, NumArgs, NewIncFlags);
244 if (!NewIncFlags.empty()) {
245 for (auto &F : NewIncFlags) {
247 printArg(OS, F.c_str(), Quote);
254 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
255 [&Arg](StringRef IF) { return IF == Arg; });
256 if (Found != InputFilenames.end() &&
257 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
258 // Replace the input file name with the crashinfo's file name.
260 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
261 printArg(OS, ShortName.str(), Quote);
267 printArg(OS, Arg, Quote);
270 if (CrashInfo && HaveCrashVFS) {
272 printArg(OS, "-ivfsoverlay", Quote);
274 printArg(OS, CrashInfo->VFSPath.str(), Quote);
276 // The leftover modules from the crash are stored in
277 // <name>.cache/vfs/modules
278 // Leave it untouched for pcm inspection and provide a clean/empty dir
279 // path to contain the future generated module cache:
280 // <name>.cache/vfs/repro-modules
281 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
282 llvm::sys::path::parent_path(CrashInfo->VFSPath));
283 llvm::sys::path::append(RelModCacheDir, "repro-modules");
285 std::string ModCachePath = "-fmodules-cache-path=";
286 ModCachePath.append(RelModCacheDir.c_str());
289 printArg(OS, ModCachePath, Quote);
292 if (ResponseFile != nullptr) {
293 OS << "\n Arguments passed via response file:\n";
294 writeResponseFile(OS);
295 // Avoiding duplicated newline terminator, since FileLists are
296 // newline-separated.
297 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
299 OS << " (end of response file)";
305 void Command::setResponseFile(const char *FileName) {
306 ResponseFile = FileName;
307 ResponseFileFlag = Creator.getResponseFileFlag();
308 ResponseFileFlag += FileName;
311 void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
312 Environment.reserve(NewEnvironment.size() + 1);
313 Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
314 Environment.push_back(nullptr);
317 int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
318 std::string *ErrMsg, bool *ExecutionFailed) const {
319 if (PrintInputFilenames) {
320 for (const char *Arg : InputFilenames)
321 llvm::outs() << llvm::sys::path::filename(Arg) << "\n";
322 llvm::outs().flush();
325 SmallVector<const char*, 128> Argv;
327 Optional<ArrayRef<StringRef>> Env;
328 std::vector<StringRef> ArgvVectorStorage;
329 if (!Environment.empty()) {
330 assert(Environment.back() == nullptr &&
331 "Environment vector should be null-terminated by now");
332 ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
333 Env = makeArrayRef(ArgvVectorStorage);
336 if (ResponseFile == nullptr) {
337 Argv.push_back(Executable);
338 Argv.append(Arguments.begin(), Arguments.end());
339 Argv.push_back(nullptr);
341 auto Args = llvm::toStringRefArray(Argv.data());
342 return llvm::sys::ExecuteAndWait(
343 Executable, Args, Env, Redirects, /*secondsToWait*/ 0,
344 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
347 // We need to put arguments in a response file (command is too large)
348 // Open stream to store the response file contents
349 std::string RespContents;
350 llvm::raw_string_ostream SS(RespContents);
352 // Write file contents and build the Argv vector
353 writeResponseFile(SS);
354 buildArgvForResponseFile(Argv);
355 Argv.push_back(nullptr);
358 // Save the response file in the appropriate encoding
359 if (std::error_code EC = writeFileWithEncoding(
360 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
362 *ErrMsg = EC.message();
364 *ExecutionFailed = true;
368 auto Args = llvm::toStringRefArray(Argv.data());
369 return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
371 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
374 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
375 const char *Executable_,
376 const llvm::opt::ArgStringList &Arguments_,
377 ArrayRef<InputInfo> Inputs,
378 std::unique_ptr<Command> Fallback_)
379 : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
380 Fallback(std::move(Fallback_)) {}
382 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
383 bool Quote, CrashReportInfo *CrashInfo) const {
384 Command::Print(OS, "", Quote, CrashInfo);
386 Fallback->Print(OS, Terminator, Quote, CrashInfo);
389 static bool ShouldFallback(int ExitCode) {
390 // FIXME: We really just want to fall back for internal errors, such
391 // as when some symbol cannot be mangled, when we should be able to
392 // parse something but can't, etc.
393 return ExitCode != 0;
396 int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
397 std::string *ErrMsg, bool *ExecutionFailed) const {
398 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
399 if (!ShouldFallback(PrimaryStatus))
400 return PrimaryStatus;
402 // Clear ExecutionFailed and ErrMsg before falling back.
406 *ExecutionFailed = false;
408 const Driver &D = getCreator().getToolChain().getDriver();
409 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
411 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
412 return SecondaryStatus;
415 ForceSuccessCommand::ForceSuccessCommand(
416 const Action &Source_, const Tool &Creator_, const char *Executable_,
417 const llvm::opt::ArgStringList &Arguments_, ArrayRef<InputInfo> Inputs)
418 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
420 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
421 bool Quote, CrashReportInfo *CrashInfo) const {
422 Command::Print(OS, "", Quote, CrashInfo);
423 OS << " || (exit 0)" << Terminator;
426 int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
428 bool *ExecutionFailed) const {
429 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
432 *ExecutionFailed = false;
436 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
437 CrashReportInfo *CrashInfo) const {
438 for (const auto &Job : *this)
439 Job.Print(OS, Terminator, Quote, CrashInfo);
442 void JobList::clear() { Jobs.clear(); }