blob: 66434cf7b011bb4bbb01bebc06cf3316239c4925 [file] [log] [blame]
Nick Lewycky3fdcc6f2010-12-31 17:31:54 +00001//===--- Job.cpp - Command to Execute -------------------------------------===//
Daniel Dunbar789e2202009-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
Stephen Hines651f13c2014-04-23 16:59:28 -070010#include "clang/Driver/Driver.h"
11#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbar789e2202009-03-13 23:36:33 +000012#include "clang/Driver/Job.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070013#include "clang/Driver/Tool.h"
14#include "clang/Driver/ToolChain.h"
Stephen Hines176edba2014-12-01 14:53:08 -080015#include "llvm/ADT/ArrayRef.h"
Chad Rosier2b819102011-08-02 17:58:04 +000016#include "llvm/ADT/STLExtras.h"
Hans Wennborgfc338972013-09-12 18:23:34 +000017#include "llvm/ADT/StringRef.h"
Stephen Hines176edba2014-12-01 14:53:08 -080018#include "llvm/ADT/StringSet.h"
Hans Wennborgfc338972013-09-12 18:23:34 +000019#include "llvm/ADT/StringSwitch.h"
Hans Wennborgaaaa2a12013-09-12 18:35:08 +000020#include "llvm/Support/Program.h"
Hans Wennborgfc338972013-09-12 18:23:34 +000021#include "llvm/Support/raw_ostream.h"
Daniel Dunbar789e2202009-03-13 23:36:33 +000022#include <cassert>
23using namespace clang::driver;
Hans Wennborgfc338972013-09-12 18:23:34 +000024using llvm::raw_ostream;
25using llvm::StringRef;
Stephen Hines176edba2014-12-01 14:53:08 -080026using llvm::ArrayRef;
Daniel Dunbar789e2202009-03-13 23:36:33 +000027
28Job::~Job() {}
29
Daniel Dunbardaab7b12009-12-02 03:23:25 +000030Command::Command(const Action &_Source, const Tool &_Creator,
Hans Wennborg5c6ecf52013-09-18 00:21:51 +000031 const char *_Executable,
Hans Wennborg64228b62013-09-18 00:41:15 +000032 const ArgStringList &_Arguments)
Reid Klecknerb1e25a12013-06-14 17:17:23 +000033 : Job(CommandClass), Source(_Source), Creator(_Creator),
Stephen Hines176edba2014-12-01 14:53:08 -080034 Executable(_Executable), Arguments(_Arguments),
35 ResponseFile(nullptr) {}
Daniel Dunbar789e2202009-03-13 23:36:33 +000036
Hans Wennborgfc338972013-09-12 18:23:34 +000037static 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)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070048 .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
Hans Wennborgfc338972013-09-12 18:23:34 +000049 .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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070069 if (FlagRef.startswith("-F") || FlagRef.startswith("-I") ||
70 FlagRef.startswith("-fmodules-cache-path="))
Hans Wennborgfc338972013-09-12 18:23:34 +000071 return 1;
72
73 return 0;
74}
75
Hans Wennborgfc338972013-09-12 18:23:34 +000076static 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
Stephen Hines176edba2014-12-01 14:53:08 -080094void 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
118void 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
Hans Wennborgfc338972013-09-12 18:23:34 +0000147void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Stephen Hines176edba2014-12-01 14:53:08 -0800148 CrashReportInfo *CrashInfo) const {
149 // Always quote the exe.
150 OS << ' ';
151 PrintArg(OS, Executable, /*Quote=*/true);
Hans Wennborgfc338972013-09-12 18:23:34 +0000152
Stephen Hines176edba2014-12-01 14:53:08 -0800153 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 }
Hans Wennborgfc338972013-09-12 18:23:34 +0000159
Stephen Hines176edba2014-12-01 14:53:08 -0800160 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) {
Hans Wennborgfc338972013-09-12 18:23:34 +0000171 if (int Skip = skipArgs(Arg)) {
172 i += Skip - 1;
173 continue;
Stephen Hines176edba2014-12-01 14:53:08 -0800174 } 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;
Hans Wennborgfc338972013-09-12 18:23:34 +0000181 }
182 }
183
184 OS << ' ';
185 PrintArg(OS, Arg, Quote);
Hans Wennborgfc338972013-09-12 18:23:34 +0000186 }
Stephen Hines176edba2014-12-01 14:53:08 -0800187
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
Hans Wennborgfc338972013-09-12 18:23:34 +0000205 OS << Terminator;
206}
207
Stephen Hines176edba2014-12-01 14:53:08 -0800208void Command::setResponseFile(const char *FileName) {
209 ResponseFile = FileName;
210 ResponseFileFlag = Creator.getResponseFileFlag();
211 ResponseFileFlag += FileName;
212}
213
Hans Wennborg64228b62013-09-18 00:41:15 +0000214int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
Hans Wennborgaaaa2a12013-09-12 18:35:08 +0000215 bool *ExecutionFailed) const {
216 SmallVector<const char*, 128> Argv;
Stephen Hines176edba2014-12-01 14:53:08 -0800217
218 if (ResponseFile == nullptr) {
219 Argv.push_back(Executable);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700220 Argv.append(Arguments.begin(), Arguments.end());
Stephen Hines176edba2014-12-01 14:53:08 -0800221 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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700237 Argv.push_back(nullptr);
Stephen Hines176edba2014-12-01 14:53:08 -0800238 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 }
Hans Wennborgaaaa2a12013-09-12 18:35:08 +0000249
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700250 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
Hans Wennborgaaaa2a12013-09-12 18:35:08 +0000251 Redirects, /*secondsToWait*/ 0,
252 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
253}
254
Hans Wennborgc8ba0a02013-09-19 20:32:16 +0000255FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
256 const char *Executable_,
257 const ArgStringList &Arguments_,
Stephen Hines176edba2014-12-01 14:53:08 -0800258 std::unique_ptr<Command> Fallback_)
259 : Command(Source_, Creator_, Executable_, Arguments_),
260 Fallback(std::move(Fallback_)) {}
Hans Wennborgc8ba0a02013-09-19 20:32:16 +0000261
262void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
Stephen Hines176edba2014-12-01 14:53:08 -0800263 bool Quote, CrashReportInfo *CrashInfo) const {
264 Command::Print(OS, "", Quote, CrashInfo);
Hans Wennborgc8ba0a02013-09-19 20:32:16 +0000265 OS << " ||";
Stephen Hines176edba2014-12-01 14:53:08 -0800266 Fallback->Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborgc8ba0a02013-09-19 20:32:16 +0000267}
268
269static 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
276int 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
Stephen Hines651f13c2014-04-23 16:59:28 -0700288 const Driver &D = getCreator().getToolChain().getDriver();
289 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
290
Hans Wennborgc8ba0a02013-09-19 20:32:16 +0000291 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
292 return SecondaryStatus;
293}
294
Daniel Dunbar789e2202009-03-13 23:36:33 +0000295JobList::JobList() : Job(JobListClass) {}
Daniel Dunbar871adcf2009-03-18 07:06:02 +0000296
Hans Wennborgfc338972013-09-12 18:23:34 +0000297void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
Stephen Hines176edba2014-12-01 14:53:08 -0800298 CrashReportInfo *CrashInfo) const {
299 for (const auto &Job : *this)
300 Job.Print(OS, Terminator, Quote, CrashInfo);
Hans Wennborgfc338972013-09-12 18:23:34 +0000301}
302
Stephen Hines176edba2014-12-01 14:53:08 -0800303void JobList::clear() { Jobs.clear(); }