blob: 94ea60663ab4b1f6fd68850138f3f62de56382b1 [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"
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000022#include "llvm/Support/FileSystem.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000023#include "llvm/Support/Path.h"
Hans Wennborge8677ef2013-09-12 18:35:08 +000024#include "llvm/Support/Program.h"
Hans Wennborgb212b342013-09-12 18:23:34 +000025#include "llvm/Support/raw_ostream.h"
Daniel Dunbar313c2912009-03-13 23:36:33 +000026#include <cassert>
27using namespace clang::driver;
Hans Wennborgb212b342013-09-12 18:23:34 +000028using llvm::raw_ostream;
29using llvm::StringRef;
Reid Kleckner0290c9c2014-09-15 17:45:39 +000030using llvm::ArrayRef;
Daniel Dunbar313c2912009-03-13 23:36:33 +000031
Justin Bogner94817612015-07-02 22:52:04 +000032Command::Command(const Action &Source, const Tool &Creator,
Justin Bognerd3371d82015-07-17 03:35:54 +000033 const char *Executable, const ArgStringList &Arguments,
34 ArrayRef<InputInfo> Inputs)
Justin Bogner0cd92482015-07-02 22:52:08 +000035 : Source(Source), Creator(Creator), Executable(Executable),
Justin Bognerd3371d82015-07-17 03:35:54 +000036 Arguments(Arguments), ResponseFile(nullptr) {
37 for (const auto &II : Inputs)
38 if (II.isFilename())
39 InputFilenames.push_back(II.getFilename());
40}
Daniel Dunbar313c2912009-03-13 23:36:33 +000041
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000042/// @brief Check if the compiler flag in question should be skipped when
43/// emitting a reproducer. Also track how many arguments it has and if the
44/// option is some kind of include path.
45static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
46 bool &IsInclude) {
47 SkipNum = 2;
Hans Wennborgb212b342013-09-12 18:23:34 +000048 // These flags are all of the form -Flag <Arg> and are treated as two
49 // arguments. Therefore, we need to skip the flag and the next argument.
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000050 bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
Bruno Cardoso Lopesb810b022016-04-04 20:26:57 +000051 .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
Hans Wennborgb212b342013-09-12 18:23:34 +000052 .Cases("-o", "-coverage-file", "-dependency-file", true)
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000053 .Cases("-fdebug-compilation-dir", "-include-pch", true)
Justin Bogner61c0e432014-06-22 20:35:10 +000054 .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000055 .Case("-diagnostic-log-file", true)
Hans Wennborgb212b342013-09-12 18:23:34 +000056 .Default(false);
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000057 if (ShouldSkip)
58 return true;
Hans Wennborgb212b342013-09-12 18:23:34 +000059
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000060 // Some include flags shouldn't be skipped if we have a crash VFS
61 IsInclude = llvm::StringSwitch<bool>(Flag)
62 .Cases("-include", "-header-include-file", true)
63 .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
64 .Cases("-internal-externc-isystem", "-iprefix", true)
65 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
66 .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
67 .Case("-iframework", true)
68 .Default(false);
69 if (IsInclude)
70 return HaveCrashVFS ? false : true;
Hans Wennborgb212b342013-09-12 18:23:34 +000071
72 // The remaining flags are treated as a single argument.
73
74 // These flags are all of the form -Flag and have no second argument.
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000075 ShouldSkip = llvm::StringSwitch<bool>(Flag)
Hans Wennborgb212b342013-09-12 18:23:34 +000076 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
77 .Case("-MMD", true)
78 .Default(false);
79
80 // Match found.
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000081 SkipNum = 1;
82 if (ShouldSkip)
83 return true;
Hans Wennborgb212b342013-09-12 18:23:34 +000084
85 // These flags are treated as a single argument (e.g., -F<Dir>).
86 StringRef FlagRef(Flag);
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000087 IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
88 if (IsInclude)
89 return HaveCrashVFS ? false : true;
90 if (FlagRef.startswith("-fmodules-cache-path="))
91 return true;
Hans Wennborgb212b342013-09-12 18:23:34 +000092
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +000093 SkipNum = 0;
94 return false;
Hans Wennborgb212b342013-09-12 18:23:34 +000095}
96
Mehdi Amini5bf825b2016-10-08 01:38:43 +000097void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
98 const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
Hans Wennborgb212b342013-09-12 18:23:34 +000099
100 if (!Quote && !Escape) {
101 OS << Arg;
102 return;
103 }
104
105 // Quote and escape. This isn't really complete, but good enough.
106 OS << '"';
Mehdi Amini5bf825b2016-10-08 01:38:43 +0000107 for (const char c : Arg) {
Hans Wennborgb212b342013-09-12 18:23:34 +0000108 if (c == '"' || c == '\\' || c == '$')
109 OS << '\\';
110 OS << c;
111 }
112 OS << '"';
113}
114
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000115void Command::writeResponseFile(raw_ostream &OS) const {
116 // In a file list, we only write the set of inputs to the response file
117 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
118 for (const char *Arg : InputFileList) {
119 OS << Arg << '\n';
120 }
121 return;
122 }
123
Reid Klecknere2d03442015-07-15 22:42:37 +0000124 // In regular response files, we send all arguments to the response file.
125 // Wrapping all arguments in double quotes ensures that both Unix tools and
126 // Windows tools understand the response file.
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000127 for (const char *Arg : Arguments) {
128 OS << '"';
129
130 for (; *Arg != '\0'; Arg++) {
131 if (*Arg == '\"' || *Arg == '\\') {
132 OS << '\\';
133 }
134 OS << *Arg;
135 }
136
137 OS << "\" ";
138 }
139}
140
141void Command::buildArgvForResponseFile(
142 llvm::SmallVectorImpl<const char *> &Out) const {
143 // When not a file list, all arguments are sent to the response file.
144 // This leaves us to set the argv to a single parameter, requesting the tool
145 // to read the response file.
146 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
147 Out.push_back(Executable);
148 Out.push_back(ResponseFileFlag.c_str());
149 return;
150 }
151
152 llvm::StringSet<> Inputs;
153 for (const char *InputName : InputFileList)
154 Inputs.insert(InputName);
155 Out.push_back(Executable);
156 // In a file list, build args vector ignoring parameters that will go in the
157 // response file (elements of the InputFileList vector)
158 bool FirstInput = true;
159 for (const char *Arg : Arguments) {
160 if (Inputs.count(Arg) == 0) {
161 Out.push_back(Arg);
162 } else if (FirstInput) {
163 FirstInput = false;
164 Out.push_back(Creator.getResponseFileFlag());
165 Out.push_back(ResponseFile);
166 }
167 }
168}
169
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +0000170/// @brief Rewrite relative include-like flag paths to absolute ones.
171static void
172rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
173 size_t NumArgs,
174 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
175 using namespace llvm;
176 using namespace sys;
177 auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
178 if (path::is_absolute(InInc)) // Nothing to do here...
179 return false;
180 std::error_code EC = fs::current_path(OutInc);
181 if (EC)
182 return false;
183 path::append(OutInc, InInc);
184 return true;
185 };
186
187 SmallString<128> NewInc;
188 if (NumArgs == 1) {
189 StringRef FlagRef(Args[Idx + NumArgs - 1]);
190 assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
191 "Expecting -I or -F");
192 StringRef Inc = FlagRef.slice(2, StringRef::npos);
193 if (getAbsPath(Inc, NewInc)) {
194 SmallString<128> NewArg(FlagRef.slice(0, 2));
195 NewArg += NewInc;
196 IncFlags.push_back(std::move(NewArg));
197 }
198 return;
199 }
200
201 assert(NumArgs == 2 && "Not expecting more than two arguments");
202 StringRef Inc(Args[Idx + NumArgs - 1]);
203 if (!getAbsPath(Inc, NewInc))
204 return;
205 IncFlags.push_back(SmallString<128>(Args[Idx]));
206 IncFlags.push_back(std::move(NewInc));
207}
208
Hans Wennborgb212b342013-09-12 18:23:34 +0000209void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Justin Bogner25645152014-10-21 17:24:44 +0000210 CrashReportInfo *CrashInfo) const {
Reid Kleckner822434d2014-08-05 20:49:12 +0000211 // Always quote the exe.
Reid Kleckner4f1fc352014-08-07 00:05:00 +0000212 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000213 printArg(OS, Executable, /*Quote=*/true);
Hans Wennborgb212b342013-09-12 18:23:34 +0000214
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000215 llvm::ArrayRef<const char *> Args = Arguments;
216 llvm::SmallVector<const char *, 128> ArgsRespFile;
217 if (ResponseFile != nullptr) {
218 buildArgvForResponseFile(ArgsRespFile);
219 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
220 }
221
Justin Bogner0cb14752015-03-12 00:52:56 +0000222 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000223 for (size_t i = 0, e = Args.size(); i < e; ++i) {
224 const char *const Arg = Args[i];
Hans Wennborgb212b342013-09-12 18:23:34 +0000225
Justin Bogner25645152014-10-21 17:24:44 +0000226 if (CrashInfo) {
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +0000227 int NumArgs = 0;
228 bool IsInclude = false;
229 if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
230 i += NumArgs - 1;
Hans Wennborgb212b342013-09-12 18:23:34 +0000231 continue;
Justin Bognerd3371d82015-07-17 03:35:54 +0000232 }
Bruno Cardoso Lopese3a0aef2016-12-09 02:22:47 +0000233
234 // Relative includes need to be expanded to absolute paths.
235 if (HaveCrashVFS && IsInclude) {
236 SmallVector<SmallString<128>, 2> NewIncFlags;
237 rewriteIncludes(Args, i, NumArgs, NewIncFlags);
238 if (!NewIncFlags.empty()) {
239 for (auto &F : NewIncFlags) {
240 OS << ' ';
241 printArg(OS, F.c_str(), Quote);
242 }
243 i += NumArgs - 1;
244 continue;
245 }
246 }
247
Justin Bognerd3371d82015-07-17 03:35:54 +0000248 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
249 [&Arg](StringRef IF) { return IF == Arg; });
250 if (Found != InputFilenames.end() &&
251 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
Justin Bogner25645152014-10-21 17:24:44 +0000252 // Replace the input file name with the crashinfo's file name.
253 OS << ' ';
254 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000255 printArg(OS, ShortName.str(), Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000256 continue;
Hans Wennborgb212b342013-09-12 18:23:34 +0000257 }
258 }
259
260 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000261 printArg(OS, Arg, Quote);
Hans Wennborgb212b342013-09-12 18:23:34 +0000262 }
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000263
Justin Bogner0cb14752015-03-12 00:52:56 +0000264 if (CrashInfo && HaveCrashVFS) {
Justin Bogner25645152014-10-21 17:24:44 +0000265 OS << ' ';
Justin Bognered9cbe02015-07-09 06:58:31 +0000266 printArg(OS, "-ivfsoverlay", Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000267 OS << ' ';
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000268 printArg(OS, CrashInfo->VFSPath.str(), Quote);
Bruno Cardoso Lopesf854b042016-04-01 17:39:08 +0000269
270 // Insert -fmodules-cache-path and use the relative module directory
271 // <name>.cache/vfs/modules where we already dumped the modules.
272 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
273 llvm::sys::path::parent_path(CrashInfo->VFSPath));
274 llvm::sys::path::append(RelModCacheDir, "modules");
275
276 std::string ModCachePath = "-fmodules-cache-path=";
277 ModCachePath.append(RelModCacheDir.c_str());
278
279 OS << ' ';
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000280 printArg(OS, ModCachePath, Quote);
Justin Bogner25645152014-10-21 17:24:44 +0000281 }
282
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000283 if (ResponseFile != nullptr) {
284 OS << "\n Arguments passed via response file:\n";
285 writeResponseFile(OS);
286 // Avoiding duplicated newline terminator, since FileLists are
287 // newline-separated.
288 if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
289 OS << "\n";
290 OS << " (end of response file)";
291 }
292
Hans Wennborgb212b342013-09-12 18:23:34 +0000293 OS << Terminator;
294}
295
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000296void Command::setResponseFile(const char *FileName) {
297 ResponseFile = FileName;
298 ResponseFileFlag = Creator.getResponseFileFlag();
299 ResponseFileFlag += FileName;
300}
301
Hans Wennborge693e842013-09-18 00:41:15 +0000302int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
Hans Wennborge8677ef2013-09-12 18:35:08 +0000303 bool *ExecutionFailed) const {
304 SmallVector<const char*, 128> Argv;
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000305
306 if (ResponseFile == nullptr) {
307 Argv.push_back(Executable);
Benjamin Kramerf9890422015-02-17 16:48:30 +0000308 Argv.append(Arguments.begin(), Arguments.end());
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000309 Argv.push_back(nullptr);
310
311 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
312 Redirects, /*secondsToWait*/ 0,
313 /*memoryLimit*/ 0, ErrMsg,
314 ExecutionFailed);
315 }
316
317 // We need to put arguments in a response file (command is too large)
318 // Open stream to store the response file contents
319 std::string RespContents;
320 llvm::raw_string_ostream SS(RespContents);
321
322 // Write file contents and build the Argv vector
323 writeResponseFile(SS);
324 buildArgvForResponseFile(Argv);
Craig Topper92fc2df2014-05-17 16:56:41 +0000325 Argv.push_back(nullptr);
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000326 SS.flush();
327
328 // Save the response file in the appropriate encoding
329 if (std::error_code EC = writeFileWithEncoding(
330 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
331 if (ErrMsg)
332 *ErrMsg = EC.message();
333 if (ExecutionFailed)
334 *ExecutionFailed = true;
335 return -1;
336 }
Hans Wennborge8677ef2013-09-12 18:35:08 +0000337
Craig Topper92fc2df2014-05-17 16:56:41 +0000338 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
Hans Wennborge8677ef2013-09-12 18:35:08 +0000339 Redirects, /*secondsToWait*/ 0,
340 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
341}
342
Hans Wennborg87cfa712013-09-19 20:32:16 +0000343FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
344 const char *Executable_,
345 const ArgStringList &Arguments_,
Justin Bognerd3371d82015-07-17 03:35:54 +0000346 ArrayRef<InputInfo> Inputs,
David Blaikiec11bf802014-09-04 16:04:28 +0000347 std::unique_ptr<Command> Fallback_)
Justin Bognerd3371d82015-07-17 03:35:54 +0000348 : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
David Blaikiec11bf802014-09-04 16:04:28 +0000349 Fallback(std::move(Fallback_)) {}
Hans Wennborg87cfa712013-09-19 20:32:16 +0000350
351void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
Justin Bogner25645152014-10-21 17:24:44 +0000352 bool Quote, CrashReportInfo *CrashInfo) const {
353 Command::Print(OS, "", Quote, CrashInfo);
Hans Wennborg87cfa712013-09-19 20:32:16 +0000354 OS << " ||";
Justin Bogner25645152014-10-21 17:24:44 +0000355 Fallback->Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborg87cfa712013-09-19 20:32:16 +0000356}
357
358static bool ShouldFallback(int ExitCode) {
359 // FIXME: We really just want to fall back for internal errors, such
360 // as when some symbol cannot be mangled, when we should be able to
361 // parse something but can't, etc.
362 return ExitCode != 0;
363}
364
365int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
366 bool *ExecutionFailed) const {
367 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
368 if (!ShouldFallback(PrimaryStatus))
369 return PrimaryStatus;
370
371 // Clear ExecutionFailed and ErrMsg before falling back.
372 if (ErrMsg)
373 ErrMsg->clear();
374 if (ExecutionFailed)
375 *ExecutionFailed = false;
376
Hans Wennborgc5afd062014-02-18 21:42:51 +0000377 const Driver &D = getCreator().getToolChain().getDriver();
Hans Wennborg897a69b2014-02-19 02:10:19 +0000378 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
Hans Wennborgc5afd062014-02-18 21:42:51 +0000379
Hans Wennborg87cfa712013-09-19 20:32:16 +0000380 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
381 return SecondaryStatus;
382}
383
Nico Weber2ca4be92016-03-01 23:16:44 +0000384ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
385 const Tool &Creator_,
386 const char *Executable_,
387 const ArgStringList &Arguments_,
388 ArrayRef<InputInfo> Inputs)
389 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
390
391void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
392 bool Quote, CrashReportInfo *CrashInfo) const {
393 Command::Print(OS, "", Quote, CrashInfo);
394 OS << " || (exit 0)" << Terminator;
395}
396
397int ForceSuccessCommand::Execute(const StringRef **Redirects,
398 std::string *ErrMsg,
399 bool *ExecutionFailed) const {
400 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
401 (void)Status;
402 if (ExecutionFailed)
403 *ExecutionFailed = false;
404 return 0;
405}
406
Hans Wennborgb212b342013-09-12 18:23:34 +0000407void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Justin Bogner25645152014-10-21 17:24:44 +0000408 CrashReportInfo *CrashInfo) const {
Justin Bogneraab97922014-10-03 01:04:53 +0000409 for (const auto &Job : *this)
Justin Bogner25645152014-10-21 17:24:44 +0000410 Job.Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborgb212b342013-09-12 18:23:34 +0000411}
412
David Blaikiec11bf802014-09-04 16:04:28 +0000413void JobList::clear() { Jobs.clear(); }