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, const ArgStringList &Arguments,
39 ArrayRef<InputInfo> Inputs)
40 : Source(Source), Creator(Creator), Executable(Executable),
41 Arguments(Arguments) {
42 for (const auto &II : Inputs)
44 InputFilenames.push_back(II.getFilename());
47 /// Check if the compiler flag in question should be skipped when
48 /// emitting a reproducer. Also track how many arguments it has and if the
49 /// option is some kind of include path.
50 static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
53 // These flags are all of the form -Flag <Arg> and are treated as two
54 // arguments. Therefore, we need to skip the flag and the next argument.
55 bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
56 .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
57 .Cases("-o", "-dependency-file", true)
58 .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
59 .Cases("-dwarf-debug-flags", "-ivfsoverlay", 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)
76 // The remaining flags are treated as a single argument.
78 // These flags are all of the form -Flag and have no second argument.
79 ShouldSkip = llvm::StringSwitch<bool>(Flag)
80 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
89 // These flags are treated as a single argument (e.g., -F<Dir>).
90 StringRef FlagRef(Flag);
91 IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
94 if (FlagRef.startswith("-fmodules-cache-path="))
101 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
102 const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
104 if (!Quote && !Escape) {
109 // Quote and escape. This isn't really complete, but good enough.
111 for (const auto c : Arg) {
112 if (c == '"' || c == '\\' || c == '$')
119 void Command::writeResponseFile(raw_ostream &OS) const {
120 // In a file list, we only write the set of inputs to the response file
121 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
122 for (const auto *Arg : InputFileList) {
128 // In regular response files, we send all arguments to the response file.
129 // Wrapping all arguments in double quotes ensures that both Unix tools and
130 // Windows tools understand the response file.
131 for (const auto *Arg : Arguments) {
134 for (; *Arg != '\0'; Arg++) {
135 if (*Arg == '\"' || *Arg == '\\') {
145 void Command::buildArgvForResponseFile(
146 llvm::SmallVectorImpl<const char *> &Out) const {
147 // When not a file list, all arguments are sent to the response file.
148 // This leaves us to set the argv to a single parameter, requesting the tool
149 // to read the response file.
150 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
151 Out.push_back(Executable);
152 Out.push_back(ResponseFileFlag.c_str());
156 llvm::StringSet<> Inputs;
157 for (const auto *InputName : InputFileList)
158 Inputs.insert(InputName);
159 Out.push_back(Executable);
160 // In a file list, build args vector ignoring parameters that will go in the
161 // response file (elements of the InputFileList vector)
162 bool FirstInput = true;
163 for (const auto *Arg : Arguments) {
164 if (Inputs.count(Arg) == 0) {
166 } else if (FirstInput) {
168 Out.push_back(Creator.getResponseFileFlag());
169 Out.push_back(ResponseFile);
174 /// Rewrite relative include-like flag paths to absolute ones.
176 rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
178 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
179 using namespace llvm;
182 auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
183 if (path::is_absolute(InInc)) // Nothing to do here...
185 std::error_code EC = fs::current_path(OutInc);
188 path::append(OutInc, InInc);
192 SmallString<128> NewInc;
194 StringRef FlagRef(Args[Idx + NumArgs - 1]);
195 assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
196 "Expecting -I or -F");
197 StringRef Inc = FlagRef.slice(2, StringRef::npos);
198 if (getAbsPath(Inc, NewInc)) {
199 SmallString<128> NewArg(FlagRef.slice(0, 2));
201 IncFlags.push_back(std::move(NewArg));
206 assert(NumArgs == 2 && "Not expecting more than two arguments");
207 StringRef Inc(Args[Idx + NumArgs - 1]);
208 if (!getAbsPath(Inc, NewInc))
210 IncFlags.push_back(SmallString<128>(Args[Idx]));
211 IncFlags.push_back(std::move(NewInc));
214 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
215 CrashReportInfo *CrashInfo) const {
216 // Always quote the exe.
218 printArg(OS, Executable, /*Quote=*/true);
220 ArrayRef<const char *> Args = Arguments;
221 SmallVector<const char *, 128> ArgsRespFile;
222 if (ResponseFile != nullptr) {
223 buildArgvForResponseFile(ArgsRespFile);
224 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
227 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
228 for (size_t i = 0, e = Args.size(); i < e; ++i) {
229 const char *const Arg = Args[i];
233 bool IsInclude = false;
234 if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
239 // Relative includes need to be expanded to absolute paths.
240 if (HaveCrashVFS && IsInclude) {
241 SmallVector<SmallString<128>, 2> NewIncFlags;
242 rewriteIncludes(Args, i, NumArgs, NewIncFlags);
243 if (!NewIncFlags.empty()) {
244 for (auto &F : NewIncFlags) {
246 printArg(OS, F.c_str(), Quote);
253 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
254 [&Arg](StringRef IF) { return IF == Arg; });
255 if (Found != InputFilenames.end() &&
256 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
257 // Replace the input file name with the crashinfo's file name.
259 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
260 printArg(OS, ShortName.str(), Quote);
266 printArg(OS, Arg, Quote);
269 if (CrashInfo && HaveCrashVFS) {
271 printArg(OS, "-ivfsoverlay", Quote);
273 printArg(OS, CrashInfo->VFSPath.str(), Quote);
275 // The leftover modules from the crash are stored in
276 // <name>.cache/vfs/modules
277 // Leave it untouched for pcm inspection and provide a clean/empty dir
278 // path to contain the future generated module cache:
279 // <name>.cache/vfs/repro-modules
280 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
281 llvm::sys::path::parent_path(CrashInfo->VFSPath));
282 llvm::sys::path::append(RelModCacheDir, "repro-modules");
284 std::string ModCachePath = "-fmodules-cache-path=";
285 ModCachePath.append(RelModCacheDir.c_str());
288 printArg(OS, ModCachePath, Quote);
291 if (ResponseFile != nullptr) {
292 OS << "\n Arguments passed via response file:\n";
293 writeResponseFile(OS);
294 // Avoiding duplicated newline terminator, since FileLists are
295 // newline-separated.
296 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
298 OS << " (end of response file)";
304 void Command::setResponseFile(const char *FileName) {
305 ResponseFile = FileName;
306 ResponseFileFlag = Creator.getResponseFileFlag();
307 ResponseFileFlag += FileName;
310 void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
311 Environment.reserve(NewEnvironment.size() + 1);
312 Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
313 Environment.push_back(nullptr);
316 int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
317 std::string *ErrMsg, bool *ExecutionFailed) const {
318 SmallVector<const char*, 128> Argv;
320 Optional<ArrayRef<StringRef>> Env;
321 std::vector<StringRef> ArgvVectorStorage;
322 if (!Environment.empty()) {
323 assert(Environment.back() == nullptr &&
324 "Environment vector should be null-terminated by now");
325 ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
326 Env = makeArrayRef(ArgvVectorStorage);
329 if (ResponseFile == nullptr) {
330 Argv.push_back(Executable);
331 Argv.append(Arguments.begin(), Arguments.end());
332 Argv.push_back(nullptr);
334 auto Args = llvm::toStringRefArray(Argv.data());
335 return llvm::sys::ExecuteAndWait(
336 Executable, Args, Env, Redirects, /*secondsToWait*/ 0,
337 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
340 // We need to put arguments in a response file (command is too large)
341 // Open stream to store the response file contents
342 std::string RespContents;
343 llvm::raw_string_ostream SS(RespContents);
345 // Write file contents and build the Argv vector
346 writeResponseFile(SS);
347 buildArgvForResponseFile(Argv);
348 Argv.push_back(nullptr);
351 // Save the response file in the appropriate encoding
352 if (std::error_code EC = writeFileWithEncoding(
353 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
355 *ErrMsg = EC.message();
357 *ExecutionFailed = true;
361 auto Args = llvm::toStringRefArray(Argv.data());
362 return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
364 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
367 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
368 const char *Executable_,
369 const ArgStringList &Arguments_,
370 ArrayRef<InputInfo> Inputs,
371 std::unique_ptr<Command> Fallback_)
372 : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
373 Fallback(std::move(Fallback_)) {}
375 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
376 bool Quote, CrashReportInfo *CrashInfo) const {
377 Command::Print(OS, "", Quote, CrashInfo);
379 Fallback->Print(OS, Terminator, Quote, CrashInfo);
382 static bool ShouldFallback(int ExitCode) {
383 // FIXME: We really just want to fall back for internal errors, such
384 // as when some symbol cannot be mangled, when we should be able to
385 // parse something but can't, etc.
386 return ExitCode != 0;
389 int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
390 std::string *ErrMsg, bool *ExecutionFailed) const {
391 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
392 if (!ShouldFallback(PrimaryStatus))
393 return PrimaryStatus;
395 // Clear ExecutionFailed and ErrMsg before falling back.
399 *ExecutionFailed = false;
401 const Driver &D = getCreator().getToolChain().getDriver();
402 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
404 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
405 return SecondaryStatus;
408 ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
409 const Tool &Creator_,
410 const char *Executable_,
411 const ArgStringList &Arguments_,
412 ArrayRef<InputInfo> Inputs)
413 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
415 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
416 bool Quote, CrashReportInfo *CrashInfo) const {
417 Command::Print(OS, "", Quote, CrashInfo);
418 OS << " || (exit 0)" << Terminator;
421 int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
423 bool *ExecutionFailed) const {
424 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
427 *ExecutionFailed = false;
431 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
432 CrashReportInfo *CrashInfo) const {
433 for (const auto &Job : *this)
434 Job.Print(OS, Terminator, Quote, CrashInfo);
437 void JobList::clear() { Jobs.clear(); }