clang  6.0.0svn
Job.cpp
Go to the documentation of this file.
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/Job.h"
11 #include "InputInfo.h"
12 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/Tool.h"
15 #include "clang/Driver/ToolChain.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cassert>
28 using namespace clang::driver;
29 using llvm::raw_ostream;
30 using llvm::StringRef;
31 using llvm::ArrayRef;
32 
33 Command::Command(const Action &Source, const Tool &Creator,
34  const char *Executable, const ArgStringList &Arguments,
35  ArrayRef<InputInfo> Inputs)
36  : Source(Source), Creator(Creator), Executable(Executable),
37  Arguments(Arguments), ResponseFile(nullptr) {
38  for (const auto &II : Inputs)
39  if (II.isFilename())
40  InputFilenames.push_back(II.getFilename());
41 }
42 
43 /// @brief Check if the compiler flag in question should be skipped when
44 /// emitting a reproducer. Also track how many arguments it has and if the
45 /// option is some kind of include path.
46 static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
47  bool &IsInclude) {
48  SkipNum = 2;
49  // These flags are all of the form -Flag <Arg> and are treated as two
50  // arguments. Therefore, we need to skip the flag and the next argument.
51  bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
52  .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
53  .Cases("-o", "-dependency-file", true)
54  .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
55  .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
56  .Default(false);
57  if (ShouldSkip)
58  return true;
59 
60  // 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  .Cases("-iframework", "-include-pch", true)
68  .Default(false);
69  if (IsInclude)
70  return HaveCrashVFS ? false : true;
71 
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.
75  ShouldSkip = llvm::StringSwitch<bool>(Flag)
76  .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
77  .Case("-MMD", true)
78  .Default(false);
79 
80  // Match found.
81  SkipNum = 1;
82  if (ShouldSkip)
83  return true;
84 
85  // These flags are treated as a single argument (e.g., -F<Dir>).
86  StringRef FlagRef(Flag);
87  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;
92 
93  SkipNum = 0;
94  return false;
95 }
96 
97 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
98  const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
99 
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 << '"';
107  for (const char c : Arg) {
108  if (c == '"' || c == '\\' || c == '$')
109  OS << '\\';
110  OS << c;
111  }
112  OS << '"';
113 }
114 
115 void 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 
124  // 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.
127  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 
141 void Command::buildArgvForResponseFile(
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 
170 /// @brief Rewrite relative include-like flag paths to absolute ones.
171 static void
173  size_t NumArgs,
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 
209 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
210  CrashReportInfo *CrashInfo) const {
211  // Always quote the exe.
212  OS << ' ';
213  printArg(OS, Executable, /*Quote=*/true);
214 
215  llvm::ArrayRef<const char *> Args = Arguments;
217  if (ResponseFile != nullptr) {
218  buildArgvForResponseFile(ArgsRespFile);
219  Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
220  }
221 
222  bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
223  for (size_t i = 0, e = Args.size(); i < e; ++i) {
224  const char *const Arg = Args[i];
225 
226  if (CrashInfo) {
227  int NumArgs = 0;
228  bool IsInclude = false;
229  if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
230  i += NumArgs - 1;
231  continue;
232  }
233 
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 
248  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")) {
252  // Replace the input file name with the crashinfo's file name.
253  OS << ' ';
254  StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
255  printArg(OS, ShortName.str(), Quote);
256  continue;
257  }
258  }
259 
260  OS << ' ';
261  printArg(OS, Arg, Quote);
262  }
263 
264  if (CrashInfo && HaveCrashVFS) {
265  OS << ' ';
266  printArg(OS, "-ivfsoverlay", Quote);
267  OS << ' ';
268  printArg(OS, CrashInfo->VFSPath.str(), Quote);
269 
270  // The leftover modules from the crash are stored in
271  // <name>.cache/vfs/modules
272  // Leave it untouched for pcm inspection and provide a clean/empty dir
273  // path to contain the future generated module cache:
274  // <name>.cache/vfs/repro-modules
275  SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
276  llvm::sys::path::parent_path(CrashInfo->VFSPath));
277  llvm::sys::path::append(RelModCacheDir, "repro-modules");
278 
279  std::string ModCachePath = "-fmodules-cache-path=";
280  ModCachePath.append(RelModCacheDir.c_str());
281 
282  OS << ' ';
283  printArg(OS, ModCachePath, Quote);
284  }
285 
286  if (ResponseFile != nullptr) {
287  OS << "\n Arguments passed via response file:\n";
288  writeResponseFile(OS);
289  // Avoiding duplicated newline terminator, since FileLists are
290  // newline-separated.
292  OS << "\n";
293  OS << " (end of response file)";
294  }
295 
296  OS << Terminator;
297 }
298 
299 void Command::setResponseFile(const char *FileName) {
300  ResponseFile = FileName;
301  ResponseFileFlag = Creator.getResponseFileFlag();
302  ResponseFileFlag += FileName;
303 }
304 
306  Environment.reserve(NewEnvironment.size() + 1);
307  Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
308  Environment.push_back(nullptr);
309 }
310 
312  std::string *ErrMsg, bool *ExecutionFailed) const {
314 
315  const char **Envp;
316  if (Environment.empty()) {
317  Envp = nullptr;
318  } else {
319  assert(Environment.back() == nullptr &&
320  "Environment vector should be null-terminated by now");
321  Envp = const_cast<const char **>(Environment.data());
322  }
323 
324  if (ResponseFile == nullptr) {
325  Argv.push_back(Executable);
326  Argv.append(Arguments.begin(), Arguments.end());
327  Argv.push_back(nullptr);
328 
329  return llvm::sys::ExecuteAndWait(
330  Executable, Argv.data(), Envp, Redirects, /*secondsToWait*/ 0,
331  /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
332  }
333 
334  // We need to put arguments in a response file (command is too large)
335  // Open stream to store the response file contents
336  std::string RespContents;
337  llvm::raw_string_ostream SS(RespContents);
338 
339  // Write file contents and build the Argv vector
340  writeResponseFile(SS);
341  buildArgvForResponseFile(Argv);
342  Argv.push_back(nullptr);
343  SS.flush();
344 
345  // Save the response file in the appropriate encoding
346  if (std::error_code EC = writeFileWithEncoding(
347  ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
348  if (ErrMsg)
349  *ErrMsg = EC.message();
350  if (ExecutionFailed)
351  *ExecutionFailed = true;
352  return -1;
353  }
354 
355  return llvm::sys::ExecuteAndWait(Executable, Argv.data(), Envp, Redirects,
356  /*secondsToWait*/ 0,
357  /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
358 }
359 
360 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
361  const char *Executable_,
362  const ArgStringList &Arguments_,
363  ArrayRef<InputInfo> Inputs,
364  std::unique_ptr<Command> Fallback_)
365  : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
366  Fallback(std::move(Fallback_)) {}
367 
368 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
369  bool Quote, CrashReportInfo *CrashInfo) const {
370  Command::Print(OS, "", Quote, CrashInfo);
371  OS << " ||";
372  Fallback->Print(OS, Terminator, Quote, CrashInfo);
373 }
374 
375 static bool ShouldFallback(int ExitCode) {
376  // FIXME: We really just want to fall back for internal errors, such
377  // as when some symbol cannot be mangled, when we should be able to
378  // parse something but can't, etc.
379  return ExitCode != 0;
380 }
381 
383  std::string *ErrMsg, bool *ExecutionFailed) const {
384  int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
385  if (!ShouldFallback(PrimaryStatus))
386  return PrimaryStatus;
387 
388  // Clear ExecutionFailed and ErrMsg before falling back.
389  if (ErrMsg)
390  ErrMsg->clear();
391  if (ExecutionFailed)
392  *ExecutionFailed = false;
393 
394  const Driver &D = getCreator().getToolChain().getDriver();
395  D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
396 
397  int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
398  return SecondaryStatus;
399 }
400 
402  const Tool &Creator_,
403  const char *Executable_,
404  const ArgStringList &Arguments_,
405  ArrayRef<InputInfo> Inputs)
406  : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
407 
408 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
409  bool Quote, CrashReportInfo *CrashInfo) const {
410  Command::Print(OS, "", Quote, CrashInfo);
411  OS << " || (exit 0)" << Terminator;
412 }
413 
415  std::string *ErrMsg,
416  bool *ExecutionFailed) const {
417  int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
418  (void)Status;
419  if (ExecutionFailed)
420  *ExecutionFailed = false;
421  return 0;
422 }
423 
424 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
425  CrashReportInfo *CrashInfo) const {
426  for (const auto &Job : *this)
427  Job.Print(OS, Terminator, Quote, CrashInfo);
428 }
429 
430 void JobList::clear() { Jobs.clear(); }
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:26
const char * getResponseFileFlag() const
Returns which prefix to use when passing the name of a response file as a parameter to this tool...
Definition: Tool.h:113
void setResponseFile(const char *FileName)
Set to pass arguments via a response file when launching the command.
Definition: Job.cpp:299
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:116
static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum, bool &IsInclude)
Check if the compiler flag in question should be skipped when emitting a reproducer.
Definition: Job.cpp:46
ResponseFileSupport getResponseFilesSupport() const
Returns the level of support for response files of this tool, whether it accepts arguments to be pass...
Definition: Tool.h:93
Definition: Format.h:1900
Action - Represent an abstract compilation step to perform.
Definition: Action.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:65
int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const override
Definition: Job.cpp:414
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
Definition: Job.h:107
void setEnvironment(llvm::ArrayRef< const char *> NewEnvironment)
Sets the environment to be used by the new process.
Definition: Job.cpp:305
static void rewriteIncludes(const llvm::ArrayRef< const char *> &Args, size_t Idx, size_t NumArgs, llvm::SmallVectorImpl< llvm::SmallString< 128 >> &IncFlags)
Rewrite relative include-like flag paths to absolute ones.
Definition: Job.cpp:172
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
Definition: Job.cpp:424
static bool ShouldFallback(int ExitCode)
Definition: Job.cpp:375
static void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote)
Print a command argument, and optionally quote it.
Definition: Job.cpp:97
#define false
Definition: stdbool.h:33
void clear()
Clear the job list.
Definition: Job.cpp:430
Command(const Action &Source, const Tool &Creator, const char *Executable, const llvm::opt::ArgStringList &Arguments, ArrayRef< InputInfo > Inputs)
Command - An executable path/name and argument vector to execute.
Definition: Job.h:44
const Driver & getDriver() const
Definition: ToolChain.h:167
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const override
Definition: Job.cpp:368
llvm::sys::WindowsEncodingMethod getResponseFileEncoding() const
Returns which encoding the response file should use.
Definition: Tool.h:108
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const override
Definition: Job.cpp:408
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
const ToolChain & getToolChain() const
Definition: Tool.h:84
ForceSuccessCommand(const Action &Source_, const Tool &Creator_, const char *Executable_, const ArgStringList &Arguments_, ArrayRef< InputInfo > Inputs)
Definition: Job.cpp:401
int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const override
Definition: Job.cpp:382
virtual void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
Definition: Job.cpp:209
FallbackCommand(const Action &Source_, const Tool &Creator_, const char *Executable_, const ArgStringList &Arguments_, ArrayRef< InputInfo > Inputs, std::unique_ptr< Command > Fallback_)
Definition: Job.cpp:360
virtual int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const
Definition: Job.cpp:311