blob: 8d5e302ae6ff15de1015c477cac684043e207cca [file] [log] [blame]
Nick Lewycky6da90772010-12-31 17:31:54 +00001//===--- Job.cpp - Command to Execute -------------------------------------===//
Daniel Dunbar313c2912009-03-13 23:36:33 +00002//
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
Mehdi Amini9670f842016-07-18 19:02:11 +000010#include "clang/Driver/Job.h"
Justin Bognerd3371d82015-07-17 03:35:54 +000011#include "InputInfo.h"
Hans Wennborgc5afd062014-02-18 21:42:51 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
Hans Wennborgc5afd062014-02-18 21:42:51 +000014#include "clang/Driver/Tool.h"
15#include "clang/Driver/ToolChain.h"
Reid Kleckner0290c9c2014-09-15 17:45:39 +000016#include "llvm/ADT/ArrayRef.h"
Chad Rosierbe10f982011-08-02 17:58:04 +000017#include "llvm/ADT/STLExtras.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000018#include "llvm/ADT/SmallString.h"
Hans Wennborgb212b342013-09-12 18:23:34 +000019#include "llvm/ADT/StringRef.h"
Reid Kleckner0290c9c2014-09-15 17:45:39 +000020#include "llvm/ADT/StringSet.h"
Hans Wennborgb212b342013-09-12 18:23:34 +000021#include "llvm/ADT/StringSwitch.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000022#include "llvm/Support/Path.h"
Hans Wennborge8677ef2013-09-12 18:35:08 +000023#include "llvm/Support/Program.h"
Hans Wennborgb212b342013-09-12 18:23:34 +000024#include "llvm/Support/raw_ostream.h"
Daniel Dunbar313c2912009-03-13 23:36:33 +000025#include <cassert>
26using namespace clang::driver;
Hans Wennborgb212b342013-09-12 18:23:34 +000027using llvm::raw_ostream;
28using llvm::StringRef;
Reid Kleckner0290c9c2014-09-15 17:45:39 +000029using llvm::ArrayRef;
Daniel Dunbar313c2912009-03-13 23:36:33 +000030
Justin Bogner94817612015-07-02 22:52:04 +000031Command::Command(const Action &Source, const Tool &Creator,
Justin Bognerd3371d82015-07-17 03:35:54 +000032 const char *Executable, const ArgStringList &Arguments,
33 ArrayRef<InputInfo> Inputs)
Justin Bogner0cd92482015-07-02 22:52:08 +000034 : Source(Source), Creator(Creator), Executable(Executable),
Justin Bognerd3371d82015-07-17 03:35:54 +000035 Arguments(Arguments), ResponseFile(nullptr) {
36 for (const auto &II : Inputs)
37 if (II.isFilename())
38 InputFilenames.push_back(II.getFilename());
39}
Daniel Dunbar313c2912009-03-13 23:36:33 +000040
Justin Bogner0cb14752015-03-12 00:52:56 +000041static int skipArgs(const char *Flag, bool HaveCrashVFS) {
Hans Wennborgb212b342013-09-12 18:23:34 +000042 // These flags are all of the form -Flag <Arg> and are treated as two
43 // arguments. Therefore, we need to skip the flag and the next argument.
44 bool Res = llvm::StringSwitch<bool>(Flag)
Bruno Cardoso Lopesb810b022016-04-04 20:26:57 +000045 .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
Hans Wennborgb212b342013-09-12 18:23:34 +000046 .Cases("-o", "-coverage-file", "-dependency-file", true)
47 .Cases("-fdebug-compilation-dir", "-idirafter", true)
48 .Cases("-include", "-include-pch", "-internal-isystem", true)
49 .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
Justin Bogner0cb14752015-03-12 00:52:56 +000050 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
Justin Bogner61c0e432014-06-22 20:35:10 +000051 .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
Justin Bognere03437c2015-08-05 23:49:44 +000052 .Cases("-header-include-file", "-diagnostic-log-file", true)
Justin Bogner0cb14752015-03-12 00:52:56 +000053 // Some include flags shouldn't be skipped if we have a crash VFS
Bruno Cardoso Lopesb810b022016-04-04 20:26:57 +000054 .Cases("-isysroot", "-I", "-F", "-resource-dir", !HaveCrashVFS)
Hans Wennborgb212b342013-09-12 18:23:34 +000055 .Default(false);
56
57 // Match found.
58 if (Res)
59 return 2;
60
61 // The remaining flags are treated as a single argument.
62
63 // These flags are all of the form -Flag and have no second argument.
64 Res = llvm::StringSwitch<bool>(Flag)
65 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
66 .Case("-MMD", true)
67 .Default(false);
68
69 // Match found.
70 if (Res)
71 return 1;
72
73 // These flags are treated as a single argument (e.g., -F<Dir>).
74 StringRef FlagRef(Flag);
Bruno Cardoso Lopesb810b022016-04-04 20:26:57 +000075 if ((!HaveCrashVFS &&
76 (FlagRef.startswith("-F") || FlagRef.startswith("-I"))) ||
Justin Bognerf893a652014-04-22 21:30:17 +000077 FlagRef.startswith("-fmodules-cache-path="))
Hans Wennborgb212b342013-09-12 18:23:34 +000078 return 1;
79
80 return 0;
81}
82
Justin Bognered9cbe02015-07-09 06:58:31 +000083void Command::printArg(raw_ostream &OS, const char *Arg, bool Quote) {
Hans Wennborgb212b342013-09-12 18:23:34 +000084 const bool Escape = std::strpbrk(Arg, "\"\\$");
85
86 if (!Quote && !Escape) {
87 OS << Arg;
88 return;
89 }
90
91 // Quote and escape. This isn't really complete, but good enough.
92 OS << '"';
93 while (const char c = *Arg++) {
94 if (c == '"' || c == '\\' || c == '$')
95 OS << '\\';
96 OS << c;
97 }
98 OS << '"';
99}
100
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000101void Command::writeResponseFile(raw_ostream &OS) const {
102 // In a file list, we only write the set of inputs to the response file
103 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
104 for (const char *Arg : InputFileList) {
105 OS << Arg << '\n';
106 }
107 return;
108 }
109
Reid Klecknere2d03442015-07-15 22:42:37 +0000110 // In regular response files, we send all arguments to the response file.
111 // Wrapping all arguments in double quotes ensures that both Unix tools and
112 // Windows tools understand the response file.
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000113 for (const char *Arg : Arguments) {
114 OS << '"';
115
116 for (; *Arg != '\0'; Arg++) {
117 if (*Arg == '\"' || *Arg == '\\') {
118 OS << '\\';
119 }
120 OS << *Arg;
121 }
122
123 OS << "\" ";
124 }
125}
126
127void Command::buildArgvForResponseFile(
128 llvm::SmallVectorImpl<const char *> &Out) const {
129 // When not a file list, all arguments are sent to the response file.
130 // This leaves us to set the argv to a single parameter, requesting the tool
131 // to read the response file.
132 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
133 Out.push_back(Executable);
134 Out.push_back(ResponseFileFlag.c_str());
135 return;
136 }
137
138 llvm::StringSet<> Inputs;
139 for (const char *InputName : InputFileList)
140 Inputs.insert(InputName);
141 Out.push_back(Executable);
142 // In a file list, build args vector ignoring parameters that will go in the
143 // response file (elements of the InputFileList vector)
144 bool FirstInput = true;
145 for (const char *Arg : Arguments) {
146 if (Inputs.count(Arg) == 0) {
147 Out.push_back(Arg);
148 } else if (FirstInput) {
149 FirstInput = false;
150 Out.push_back(Creator.getResponseFileFlag());
151 Out.push_back(ResponseFile);
152 }
153 }
154}
155
Hans Wennborgb212b342013-09-12 18:23:34 +0000156void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Justin Bogner25645152014-10-21 17:24:44 +0000157 CrashReportInfo *CrashInfo) const {
Reid Kleckner822434d2014-08-05 20:49:12 +0000158 // Always quote the exe.
Reid Kleckner4f1fc352014-08-07 00:05:00 +0000159 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000160 printArg(OS, Executable, /*Quote=*/true);
Hans Wennborgb212b342013-09-12 18:23:34 +0000161
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000162 llvm::ArrayRef<const char *> Args = Arguments;
163 llvm::SmallVector<const char *, 128> ArgsRespFile;
164 if (ResponseFile != nullptr) {
165 buildArgvForResponseFile(ArgsRespFile);
166 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
167 }
168
Justin Bogner0cb14752015-03-12 00:52:56 +0000169 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000170 for (size_t i = 0, e = Args.size(); i < e; ++i) {
171 const char *const Arg = Args[i];
Hans Wennborgb212b342013-09-12 18:23:34 +0000172
Justin Bogner25645152014-10-21 17:24:44 +0000173 if (CrashInfo) {
Justin Bogner0cb14752015-03-12 00:52:56 +0000174 if (int Skip = skipArgs(Arg, HaveCrashVFS)) {
Hans Wennborgb212b342013-09-12 18:23:34 +0000175 i += Skip - 1;
176 continue;
Justin Bognerd3371d82015-07-17 03:35:54 +0000177 }
178 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
179 [&Arg](StringRef IF) { return IF == Arg; });
180 if (Found != InputFilenames.end() &&
181 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
Justin Bogner25645152014-10-21 17:24:44 +0000182 // Replace the input file name with the crashinfo's file name.
183 OS << ' ';
184 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
Justin Bognered9cbe02015-07-09 06:58:31 +0000185 printArg(OS, ShortName.str().c_str(), Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000186 continue;
Hans Wennborgb212b342013-09-12 18:23:34 +0000187 }
188 }
189
190 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000191 printArg(OS, Arg, Quote);
Hans Wennborgb212b342013-09-12 18:23:34 +0000192 }
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000193
Justin Bogner0cb14752015-03-12 00:52:56 +0000194 if (CrashInfo && HaveCrashVFS) {
Justin Bogner25645152014-10-21 17:24:44 +0000195 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000196 printArg(OS, "-ivfsoverlay", Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000197 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000198 printArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
Bruno Cardoso Lopesf854b042016-04-01 17:39:08 +0000199
200 // Insert -fmodules-cache-path and use the relative module directory
201 // <name>.cache/vfs/modules where we already dumped the modules.
202 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
203 llvm::sys::path::parent_path(CrashInfo->VFSPath));
204 llvm::sys::path::append(RelModCacheDir, "modules");
205
206 std::string ModCachePath = "-fmodules-cache-path=";
207 ModCachePath.append(RelModCacheDir.c_str());
208
209 OS << ' ';
210 printArg(OS, ModCachePath.c_str(), Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000211 }
212
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000213 if (ResponseFile != nullptr) {
214 OS << "\n Arguments passed via response file:\n";
215 writeResponseFile(OS);
216 // Avoiding duplicated newline terminator, since FileLists are
217 // newline-separated.
218 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
219 OS << "\n";
220 OS << " (end of response file)";
221 }
222
Hans Wennborgb212b342013-09-12 18:23:34 +0000223 OS << Terminator;
224}
225
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000226void Command::setResponseFile(const char *FileName) {
227 ResponseFile = FileName;
228 ResponseFileFlag = Creator.getResponseFileFlag();
229 ResponseFileFlag += FileName;
230}
231
Hans Wennborge693e842013-09-18 00:41:15 +0000232int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
Hans Wennborge8677ef2013-09-12 18:35:08 +0000233 bool *ExecutionFailed) const {
234 SmallVector<const char*, 128> Argv;
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000235
236 if (ResponseFile == nullptr) {
237 Argv.push_back(Executable);
Benjamin Kramerf9890422015-02-17 16:48:30 +0000238 Argv.append(Arguments.begin(), Arguments.end());
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000239 Argv.push_back(nullptr);
240
241 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
242 Redirects, /*secondsToWait*/ 0,
243 /*memoryLimit*/ 0, ErrMsg,
244 ExecutionFailed);
245 }
246
247 // We need to put arguments in a response file (command is too large)
248 // Open stream to store the response file contents
249 std::string RespContents;
250 llvm::raw_string_ostream SS(RespContents);
251
252 // Write file contents and build the Argv vector
253 writeResponseFile(SS);
254 buildArgvForResponseFile(Argv);
Craig Topper92fc2df2014-05-17 16:56:41 +0000255 Argv.push_back(nullptr);
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000256 SS.flush();
257
258 // Save the response file in the appropriate encoding
259 if (std::error_code EC = writeFileWithEncoding(
260 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
261 if (ErrMsg)
262 *ErrMsg = EC.message();
263 if (ExecutionFailed)
264 *ExecutionFailed = true;
265 return -1;
266 }
Hans Wennborge8677ef2013-09-12 18:35:08 +0000267
Craig Topper92fc2df2014-05-17 16:56:41 +0000268 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
Hans Wennborge8677ef2013-09-12 18:35:08 +0000269 Redirects, /*secondsToWait*/ 0,
270 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
271}
272
Hans Wennborg87cfa712013-09-19 20:32:16 +0000273FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
274 const char *Executable_,
275 const ArgStringList &Arguments_,
Justin Bognerd3371d82015-07-17 03:35:54 +0000276 ArrayRef<InputInfo> Inputs,
David Blaikiec11bf802014-09-04 16:04:28 +0000277 std::unique_ptr<Command> Fallback_)
Justin Bognerd3371d82015-07-17 03:35:54 +0000278 : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
David Blaikiec11bf802014-09-04 16:04:28 +0000279 Fallback(std::move(Fallback_)) {}
Hans Wennborg87cfa712013-09-19 20:32:16 +0000280
281void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
Justin Bogner25645152014-10-21 17:24:44 +0000282 bool Quote, CrashReportInfo *CrashInfo) const {
283 Command::Print(OS, "", Quote, CrashInfo);
Hans Wennborg87cfa712013-09-19 20:32:16 +0000284 OS << " ||";
Justin Bogner25645152014-10-21 17:24:44 +0000285 Fallback->Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborg87cfa712013-09-19 20:32:16 +0000286}
287
288static bool ShouldFallback(int ExitCode) {
289 // FIXME: We really just want to fall back for internal errors, such
290 // as when some symbol cannot be mangled, when we should be able to
291 // parse something but can't, etc.
292 return ExitCode != 0;
293}
294
295int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
296 bool *ExecutionFailed) const {
297 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
298 if (!ShouldFallback(PrimaryStatus))
299 return PrimaryStatus;
300
301 // Clear ExecutionFailed and ErrMsg before falling back.
302 if (ErrMsg)
303 ErrMsg->clear();
304 if (ExecutionFailed)
305 *ExecutionFailed = false;
306
Hans Wennborgc5afd062014-02-18 21:42:51 +0000307 const Driver &D = getCreator().getToolChain().getDriver();
Hans Wennborg897a69b2014-02-19 02:10:19 +0000308 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
Hans Wennborgc5afd062014-02-18 21:42:51 +0000309
Hans Wennborg87cfa712013-09-19 20:32:16 +0000310 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
311 return SecondaryStatus;
312}
313
Nico Weber2ca4be92016-03-01 23:16:44 +0000314ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
315 const Tool &Creator_,
316 const char *Executable_,
317 const ArgStringList &Arguments_,
318 ArrayRef<InputInfo> Inputs)
319 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
320
321void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
322 bool Quote, CrashReportInfo *CrashInfo) const {
323 Command::Print(OS, "", Quote, CrashInfo);
324 OS << " || (exit 0)" << Terminator;
325}
326
327int ForceSuccessCommand::Execute(const StringRef **Redirects,
328 std::string *ErrMsg,
329 bool *ExecutionFailed) const {
330 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
331 (void)Status;
332 if (ExecutionFailed)
333 *ExecutionFailed = false;
334 return 0;
335}
336
Hans Wennborgb212b342013-09-12 18:23:34 +0000337void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Justin Bogner25645152014-10-21 17:24:44 +0000338 CrashReportInfo *CrashInfo) const {
Justin Bogneraab97922014-10-03 01:04:53 +0000339 for (const auto &Job : *this)
Justin Bogner25645152014-10-21 17:24:44 +0000340 Job.Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborgb212b342013-09-12 18:23:34 +0000341}
342
David Blaikiec11bf802014-09-04 16:04:28 +0000343void JobList::clear() { Jobs.clear(); }