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