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/Driver.h"
11 #include "clang/Driver/DriverDiagnostic.h"
12 #include "clang/Driver/Job.h"
13 #include "clang/Driver/Tool.h"
14 #include "clang/Driver/ToolChain.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/raw_ostream.h"
23 using namespace clang::driver;
24 using llvm::raw_ostream;
25 using llvm::StringRef;
30 Command::Command(const Action &_Source, const Tool &_Creator,
31 const char *_Executable,
32 const ArgStringList &_Arguments)
33 : Job(CommandClass), Source(_Source), Creator(_Creator),
34 Executable(_Executable), Arguments(_Arguments),
35 ResponseFile(nullptr) {}
37 static int skipArgs(const char *Flag) {
38 // These flags are all of the form -Flag <Arg> and are treated as two
39 // arguments. Therefore, we need to skip the flag and the next argument.
40 bool Res = llvm::StringSwitch<bool>(Flag)
41 .Cases("-I", "-MF", "-MT", "-MQ", true)
42 .Cases("-o", "-coverage-file", "-dependency-file", true)
43 .Cases("-fdebug-compilation-dir", "-idirafter", true)
44 .Cases("-include", "-include-pch", "-internal-isystem", true)
45 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
46 .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
47 .Cases("-resource-dir", "-serialize-diagnostic-file", true)
48 .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
55 // The remaining flags are treated as a single argument.
57 // These flags are all of the form -Flag and have no second argument.
58 Res = llvm::StringSwitch<bool>(Flag)
59 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
67 // These flags are treated as a single argument (e.g., -F<Dir>).
68 StringRef FlagRef(Flag);
69 if (FlagRef.startswith("-F") || FlagRef.startswith("-I") ||
70 FlagRef.startswith("-fmodules-cache-path="))
76 static void PrintArg(raw_ostream &OS, const char *Arg, bool Quote) {
77 const bool Escape = std::strpbrk(Arg, "\"\\$");
79 if (!Quote && !Escape) {
84 // Quote and escape. This isn't really complete, but good enough.
86 while (const char c = *Arg++) {
87 if (c == '"' || c == '\\' || c == '$')
94 void Command::writeResponseFile(raw_ostream &OS) const {
95 // In a file list, we only write the set of inputs to the response file
96 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
97 for (const char *Arg : InputFileList) {
103 // In regular response files, we send all arguments to the response file
104 for (const char *Arg : Arguments) {
107 for (; *Arg != '\0'; Arg++) {
108 if (*Arg == '\"' || *Arg == '\\') {
118 void Command::buildArgvForResponseFile(
119 llvm::SmallVectorImpl<const char *> &Out) const {
120 // When not a file list, all arguments are sent to the response file.
121 // This leaves us to set the argv to a single parameter, requesting the tool
122 // to read the response file.
123 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
124 Out.push_back(Executable);
125 Out.push_back(ResponseFileFlag.c_str());
129 llvm::StringSet<> Inputs;
130 for (const char *InputName : InputFileList)
131 Inputs.insert(InputName);
132 Out.push_back(Executable);
133 // In a file list, build args vector ignoring parameters that will go in the
134 // response file (elements of the InputFileList vector)
135 bool FirstInput = true;
136 for (const char *Arg : Arguments) {
137 if (Inputs.count(Arg) == 0) {
139 } else if (FirstInput) {
141 Out.push_back(Creator.getResponseFileFlag());
142 Out.push_back(ResponseFile);
147 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
148 CrashReportInfo *CrashInfo) const {
149 // Always quote the exe.
151 PrintArg(OS, Executable, /*Quote=*/true);
153 llvm::ArrayRef<const char *> Args = Arguments;
154 llvm::SmallVector<const char *, 128> ArgsRespFile;
155 if (ResponseFile != nullptr) {
156 buildArgvForResponseFile(ArgsRespFile);
157 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
160 StringRef MainFilename;
161 // We'll need the argument to -main-file-name to find the input file name.
163 for (size_t I = 0, E = Args.size(); I + 1 < E; ++I)
164 if (StringRef(Args[I]).equals("-main-file-name"))
165 MainFilename = Args[I + 1];
167 for (size_t i = 0, e = Args.size(); i < e; ++i) {
168 const char *const Arg = Args[i];
171 if (int Skip = skipArgs(Arg)) {
174 } else if (llvm::sys::path::filename(Arg) == MainFilename &&
175 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
176 // Replace the input file name with the crashinfo's file name.
178 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
179 PrintArg(OS, ShortName.str().c_str(), Quote);
185 PrintArg(OS, Arg, Quote);
188 if (CrashInfo && !CrashInfo->VFSPath.empty()) {
190 PrintArg(OS, "-ivfsoverlay", Quote);
192 PrintArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
195 if (ResponseFile != nullptr) {
196 OS << "\n Arguments passed via response file:\n";
197 writeResponseFile(OS);
198 // Avoiding duplicated newline terminator, since FileLists are
199 // newline-separated.
200 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
202 OS << " (end of response file)";
208 void Command::setResponseFile(const char *FileName) {
209 ResponseFile = FileName;
210 ResponseFileFlag = Creator.getResponseFileFlag();
211 ResponseFileFlag += FileName;
214 int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
215 bool *ExecutionFailed) const {
216 SmallVector<const char*, 128> Argv;
218 if (ResponseFile == nullptr) {
219 Argv.push_back(Executable);
220 for (size_t i = 0, e = Arguments.size(); i != e; ++i)
221 Argv.push_back(Arguments[i]);
222 Argv.push_back(nullptr);
224 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
225 Redirects, /*secondsToWait*/ 0,
226 /*memoryLimit*/ 0, ErrMsg,
230 // We need to put arguments in a response file (command is too large)
231 // Open stream to store the response file contents
232 std::string RespContents;
233 llvm::raw_string_ostream SS(RespContents);
235 // Write file contents and build the Argv vector
236 writeResponseFile(SS);
237 buildArgvForResponseFile(Argv);
238 Argv.push_back(nullptr);
241 // Save the response file in the appropriate encoding
242 if (std::error_code EC = writeFileWithEncoding(
243 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
245 *ErrMsg = EC.message();
247 *ExecutionFailed = true;
251 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
252 Redirects, /*secondsToWait*/ 0,
253 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
256 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
257 const char *Executable_,
258 const ArgStringList &Arguments_,
259 std::unique_ptr<Command> Fallback_)
260 : Command(Source_, Creator_, Executable_, Arguments_),
261 Fallback(std::move(Fallback_)) {}
263 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
264 bool Quote, CrashReportInfo *CrashInfo) const {
265 Command::Print(OS, "", Quote, CrashInfo);
267 Fallback->Print(OS, Terminator, Quote, CrashInfo);
270 static bool ShouldFallback(int ExitCode) {
271 // FIXME: We really just want to fall back for internal errors, such
272 // as when some symbol cannot be mangled, when we should be able to
273 // parse something but can't, etc.
274 return ExitCode != 0;
277 int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
278 bool *ExecutionFailed) const {
279 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
280 if (!ShouldFallback(PrimaryStatus))
281 return PrimaryStatus;
283 // Clear ExecutionFailed and ErrMsg before falling back.
287 *ExecutionFailed = false;
289 const Driver &D = getCreator().getToolChain().getDriver();
290 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
292 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
293 return SecondaryStatus;
296 JobList::JobList() : Job(JobListClass) {}
298 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
299 CrashReportInfo *CrashInfo) const {
300 for (const auto &Job : *this)
301 Job.Print(OS, Terminator, Quote, CrashInfo);
304 void JobList::clear() { Jobs.clear(); }