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 "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"
22 #include <cassert>
23 using namespace clang::driver;
24 using llvm::raw_ostream;
25 using llvm::StringRef;
26 using llvm::ArrayRef;
27 
28 Job::~Job() {}
29 
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) {}
36 
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)
49     .Default(false);
50 
51   // Match found.
52   if (Res)
53     return 2;
54 
55   // The remaining flags are treated as a single argument.
56 
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)
60     .Case("-MMD", true)
61     .Default(false);
62 
63   // Match found.
64   if (Res)
65     return 1;
66 
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="))
71     return 1;
72 
73   return 0;
74 }
75 
76 static void PrintArg(raw_ostream &OS, const char *Arg, bool Quote) {
77   const bool Escape = std::strpbrk(Arg, "\"\\$");
78 
79   if (!Quote && !Escape) {
80     OS << Arg;
81     return;
82   }
83 
84   // Quote and escape. This isn't really complete, but good enough.
85   OS << '"';
86   while (const char c = *Arg++) {
87     if (c == '"' || c == '\\' || c == '$')
88       OS << '\\';
89     OS << c;
90   }
91   OS << '"';
92 }
93 
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) {
98       OS << Arg << '\n';
99     }
100     return;
101   }
102 
103   // In regular response files, we send all arguments to the response file
104   for (const char *Arg : Arguments) {
105     OS << '"';
106 
107     for (; *Arg != '\0'; Arg++) {
108       if (*Arg == '\"' || *Arg == '\\') {
109         OS << '\\';
110       }
111       OS << *Arg;
112     }
113 
114     OS << "\" ";
115   }
116 }
117 
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());
126     return;
127   }
128 
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) {
138       Out.push_back(Arg);
139     } else if (FirstInput) {
140       FirstInput = false;
141       Out.push_back(Creator.getResponseFileFlag());
142       Out.push_back(ResponseFile);
143     }
144   }
145 }
146 
147 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
148                     CrashReportInfo *CrashInfo) const {
149   // Always quote the exe.
150   OS << ' ';
151   PrintArg(OS, Executable, /*Quote=*/true);
152 
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
158   }
159 
160   StringRef MainFilename;
161   // We'll need the argument to -main-file-name to find the input file name.
162   if (CrashInfo)
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];
166 
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)) {
172         i += Skip - 1;
173         continue;
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.
177         OS << ' ';
178         StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
179         PrintArg(OS, ShortName.str().c_str(), Quote);
180         continue;
181       }
182     }
183 
184     OS << ' ';
185     PrintArg(OS, Arg, Quote);
186   }
187 
188   if (CrashInfo && !CrashInfo->VFSPath.empty()) {
189     OS << ' ';
190     PrintArg(OS, "-ivfsoverlay", Quote);
191     OS << ' ';
192     PrintArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
193   }
194 
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)
201       OS << "\n";
202     OS << " (end of response file)";
203   }
204 
205   OS << Terminator;
206 }
207 
208 void Command::setResponseFile(const char *FileName) {
209   ResponseFile = FileName;
210   ResponseFileFlag = Creator.getResponseFileFlag();
211   ResponseFileFlag += FileName;
212 }
213 
214 int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
215                      bool *ExecutionFailed) const {
216   SmallVector<const char*, 128> Argv;
217 
218   if (ResponseFile == nullptr) {
219     Argv.push_back(Executable);
220     Argv.append(Arguments.begin(), Arguments.end());
221     Argv.push_back(nullptr);
222 
223     return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
224                                      Redirects, /*secondsToWait*/ 0,
225                                      /*memoryLimit*/ 0, ErrMsg,
226                                      ExecutionFailed);
227   }
228 
229   // We need to put arguments in a response file (command is too large)
230   // Open stream to store the response file contents
231   std::string RespContents;
232   llvm::raw_string_ostream SS(RespContents);
233 
234   // Write file contents and build the Argv vector
235   writeResponseFile(SS);
236   buildArgvForResponseFile(Argv);
237   Argv.push_back(nullptr);
238   SS.flush();
239 
240   // Save the response file in the appropriate encoding
241   if (std::error_code EC = writeFileWithEncoding(
242           ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
243     if (ErrMsg)
244       *ErrMsg = EC.message();
245     if (ExecutionFailed)
246       *ExecutionFailed = true;
247     return -1;
248   }
249 
250   return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
251                                    Redirects, /*secondsToWait*/ 0,
252                                    /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
253 }
254 
255 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
256                                  const char *Executable_,
257                                  const ArgStringList &Arguments_,
258                                  std::unique_ptr<Command> Fallback_)
259     : Command(Source_, Creator_, Executable_, Arguments_),
260       Fallback(std::move(Fallback_)) {}
261 
262 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
263                             bool Quote, CrashReportInfo *CrashInfo) const {
264   Command::Print(OS, "", Quote, CrashInfo);
265   OS << " ||";
266   Fallback->Print(OS, Terminator, Quote, CrashInfo);
267 }
268 
269 static bool ShouldFallback(int ExitCode) {
270   // FIXME: We really just want to fall back for internal errors, such
271   // as when some symbol cannot be mangled, when we should be able to
272   // parse something but can't, etc.
273   return ExitCode != 0;
274 }
275 
276 int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
277                              bool *ExecutionFailed) const {
278   int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
279   if (!ShouldFallback(PrimaryStatus))
280     return PrimaryStatus;
281 
282   // Clear ExecutionFailed and ErrMsg before falling back.
283   if (ErrMsg)
284     ErrMsg->clear();
285   if (ExecutionFailed)
286     *ExecutionFailed = false;
287 
288   const Driver &D = getCreator().getToolChain().getDriver();
289   D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
290 
291   int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
292   return SecondaryStatus;
293 }
294 
295 JobList::JobList() : Job(JobListClass) {}
296 
297 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
298                     CrashReportInfo *CrashInfo) const {
299   for (const auto &Job : *this)
300     Job.Print(OS, Terminator, Quote, CrashInfo);
301 }
302 
303 void JobList::clear() { Jobs.clear(); }
304