1 //===--- Job.cpp - Command to Execute -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InputInfo.h"
11 #include "clang/Driver/Driver.h"
12 #include "clang/Driver/DriverDiagnostic.h"
13 #include "clang/Driver/Job.h"
14 #include "clang/Driver/Tool.h"
15 #include "clang/Driver/ToolChain.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSet.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Program.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <cassert>
24 using namespace clang::driver;
25 using llvm::raw_ostream;
26 using llvm::StringRef;
27 using llvm::ArrayRef;
28 
29 Command::Command(const Action &Source, const Tool &Creator,
30                  const char *Executable, const ArgStringList &Arguments,
31                  ArrayRef<InputInfo> Inputs)
32     : Source(Source), Creator(Creator), Executable(Executable),
33       Arguments(Arguments), ResponseFile(nullptr) {
34   for (const auto &II : Inputs)
35     if (II.isFilename())
36       InputFilenames.push_back(II.getFilename());
37 }
38 
39 static int skipArgs(const char *Flag, bool HaveCrashVFS) {
40   // These flags are all of the form -Flag <Arg> and are treated as two
41   // arguments.  Therefore, we need to skip the flag and the next argument.
42   bool Res = llvm::StringSwitch<bool>(Flag)
43     .Cases("-I", "-MF", "-MT", "-MQ", true)
44     .Cases("-o", "-coverage-file", "-dependency-file", true)
45     .Cases("-fdebug-compilation-dir", "-idirafter", true)
46     .Cases("-include", "-include-pch", "-internal-isystem", true)
47     .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
48     .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
49     .Cases("-resource-dir", "-serialize-diagnostic-file", true)
50     .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
51     // Some include flags shouldn't be skipped if we have a crash VFS
52     .Case("-isysroot", !HaveCrashVFS)
53     .Default(false);
54 
55   // Match found.
56   if (Res)
57     return 2;
58 
59   // The remaining flags are treated as a single argument.
60 
61   // These flags are all of the form -Flag and have no second argument.
62   Res = llvm::StringSwitch<bool>(Flag)
63     .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
64     .Case("-MMD", true)
65     .Default(false);
66 
67   // Match found.
68   if (Res)
69     return 1;
70 
71   // These flags are treated as a single argument (e.g., -F<Dir>).
72   StringRef FlagRef(Flag);
73   if (FlagRef.startswith("-F") || FlagRef.startswith("-I") ||
74       FlagRef.startswith("-fmodules-cache-path="))
75     return 1;
76 
77   return 0;
78 }
79 
80 void Command::printArg(raw_ostream &OS, const char *Arg, bool Quote) {
81   const bool Escape = std::strpbrk(Arg, "\"\\$");
82 
83   if (!Quote && !Escape) {
84     OS << Arg;
85     return;
86   }
87 
88   // Quote and escape. This isn't really complete, but good enough.
89   OS << '"';
90   while (const char c = *Arg++) {
91     if (c == '"' || c == '\\' || c == '$')
92       OS << '\\';
93     OS << c;
94   }
95   OS << '"';
96 }
97 
98 void Command::writeResponseFile(raw_ostream &OS) const {
99   // In a file list, we only write the set of inputs to the response file
100   if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
101     for (const char *Arg : InputFileList) {
102       OS << Arg << '\n';
103     }
104     return;
105   }
106 
107   // In regular response files, we send all arguments to the response file.
108   // Wrapping all arguments in double quotes ensures that both Unix tools and
109   // Windows tools understand the response file.
110   for (const char *Arg : Arguments) {
111     OS << '"';
112 
113     for (; *Arg != '\0'; Arg++) {
114       if (*Arg == '\"' || *Arg == '\\') {
115         OS << '\\';
116       }
117       OS << *Arg;
118     }
119 
120     OS << "\" ";
121   }
122 }
123 
124 void Command::buildArgvForResponseFile(
125     llvm::SmallVectorImpl<const char *> &Out) const {
126   // When not a file list, all arguments are sent to the response file.
127   // This leaves us to set the argv to a single parameter, requesting the tool
128   // to read the response file.
129   if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
130     Out.push_back(Executable);
131     Out.push_back(ResponseFileFlag.c_str());
132     return;
133   }
134 
135   llvm::StringSet<> Inputs;
136   for (const char *InputName : InputFileList)
137     Inputs.insert(InputName);
138   Out.push_back(Executable);
139   // In a file list, build args vector ignoring parameters that will go in the
140   // response file (elements of the InputFileList vector)
141   bool FirstInput = true;
142   for (const char *Arg : Arguments) {
143     if (Inputs.count(Arg) == 0) {
144       Out.push_back(Arg);
145     } else if (FirstInput) {
146       FirstInput = false;
147       Out.push_back(Creator.getResponseFileFlag());
148       Out.push_back(ResponseFile);
149     }
150   }
151 }
152 
153 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
154                     CrashReportInfo *CrashInfo) const {
155   // Always quote the exe.
156   OS << ' ';
157   printArg(OS, Executable, /*Quote=*/true);
158 
159   llvm::ArrayRef<const char *> Args = Arguments;
160   llvm::SmallVector<const char *, 128> ArgsRespFile;
161   if (ResponseFile != nullptr) {
162     buildArgvForResponseFile(ArgsRespFile);
163     Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
164   }
165 
166   bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
167   for (size_t i = 0, e = Args.size(); i < e; ++i) {
168     const char *const Arg = Args[i];
169 
170     if (CrashInfo) {
171       if (int Skip = skipArgs(Arg, HaveCrashVFS)) {
172         i += Skip - 1;
173         continue;
174       }
175       auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
176                                 [&Arg](StringRef IF) { return IF == Arg; });
177       if (Found != InputFilenames.end() &&
178           (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
179         // Replace the input file name with the crashinfo's file name.
180         OS << ' ';
181         StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
182         printArg(OS, ShortName.str().c_str(), Quote);
183         continue;
184       }
185     }
186 
187     OS << ' ';
188     printArg(OS, Arg, Quote);
189   }
190 
191   if (CrashInfo && HaveCrashVFS) {
192     OS << ' ';
193     printArg(OS, "-ivfsoverlay", Quote);
194     OS << ' ';
195     printArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
196   }
197 
198   if (ResponseFile != nullptr) {
199     OS << "\n Arguments passed via response file:\n";
200     writeResponseFile(OS);
201     // Avoiding duplicated newline terminator, since FileLists are
202     // newline-separated.
203     if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
204       OS << "\n";
205     OS << " (end of response file)";
206   }
207 
208   OS << Terminator;
209 }
210 
211 void Command::setResponseFile(const char *FileName) {
212   ResponseFile = FileName;
213   ResponseFileFlag = Creator.getResponseFileFlag();
214   ResponseFileFlag += FileName;
215 }
216 
217 int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
218                      bool *ExecutionFailed) const {
219   SmallVector<const char*, 128> Argv;
220 
221   if (ResponseFile == nullptr) {
222     Argv.push_back(Executable);
223     Argv.append(Arguments.begin(), Arguments.end());
224     Argv.push_back(nullptr);
225 
226     return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
227                                      Redirects, /*secondsToWait*/ 0,
228                                      /*memoryLimit*/ 0, ErrMsg,
229                                      ExecutionFailed);
230   }
231 
232   // We need to put arguments in a response file (command is too large)
233   // Open stream to store the response file contents
234   std::string RespContents;
235   llvm::raw_string_ostream SS(RespContents);
236 
237   // Write file contents and build the Argv vector
238   writeResponseFile(SS);
239   buildArgvForResponseFile(Argv);
240   Argv.push_back(nullptr);
241   SS.flush();
242 
243   // Save the response file in the appropriate encoding
244   if (std::error_code EC = writeFileWithEncoding(
245           ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
246     if (ErrMsg)
247       *ErrMsg = EC.message();
248     if (ExecutionFailed)
249       *ExecutionFailed = true;
250     return -1;
251   }
252 
253   return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
254                                    Redirects, /*secondsToWait*/ 0,
255                                    /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
256 }
257 
258 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
259                                  const char *Executable_,
260                                  const ArgStringList &Arguments_,
261                                  ArrayRef<InputInfo> Inputs,
262                                  std::unique_ptr<Command> Fallback_)
263     : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
264       Fallback(std::move(Fallback_)) {}
265 
266 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
267                             bool Quote, CrashReportInfo *CrashInfo) const {
268   Command::Print(OS, "", Quote, CrashInfo);
269   OS << " ||";
270   Fallback->Print(OS, Terminator, Quote, CrashInfo);
271 }
272 
273 static bool ShouldFallback(int ExitCode) {
274   // FIXME: We really just want to fall back for internal errors, such
275   // as when some symbol cannot be mangled, when we should be able to
276   // parse something but can't, etc.
277   return ExitCode != 0;
278 }
279 
280 int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
281                              bool *ExecutionFailed) const {
282   int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
283   if (!ShouldFallback(PrimaryStatus))
284     return PrimaryStatus;
285 
286   // Clear ExecutionFailed and ErrMsg before falling back.
287   if (ErrMsg)
288     ErrMsg->clear();
289   if (ExecutionFailed)
290     *ExecutionFailed = false;
291 
292   const Driver &D = getCreator().getToolChain().getDriver();
293   D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
294 
295   int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
296   return SecondaryStatus;
297 }
298 
299 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
300                     CrashReportInfo *CrashInfo) const {
301   for (const auto &Job : *this)
302     Job.Print(OS, Terminator, Quote, CrashInfo);
303 }
304 
305 void JobList::clear() { Jobs.clear(); }
306