]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Job.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Job.cpp
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/Basic/LLVM.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Tool.h"
16 #include "clang/Driver/ToolChain.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.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 <algorithm>
28 #include <cassert>
29 #include <cstddef>
30 #include <string>
31 #include <system_error>
32 #include <utility>
33
34 using namespace clang;
35 using namespace driver;
36
37 Command::Command(const Action &Source, const Tool &Creator,
38                  const char *Executable, const ArgStringList &Arguments,
39                  ArrayRef<InputInfo> Inputs)
40     : Source(Source), Creator(Creator), Executable(Executable),
41       Arguments(Arguments) {
42   for (const auto &II : Inputs)
43     if (II.isFilename())
44       InputFilenames.push_back(II.getFilename());
45 }
46
47 /// Check if the compiler flag in question should be skipped when
48 /// emitting a reproducer. Also track how many arguments it has and if the
49 /// option is some kind of include path.
50 static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
51                      bool &IsInclude) {
52   SkipNum = 2;
53   // These flags are all of the form -Flag <Arg> and are treated as two
54   // arguments.  Therefore, we need to skip the flag and the next argument.
55   bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
56     .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
57     .Cases("-o", "-dependency-file", true)
58     .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
59     .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
60     .Default(false);
61   if (ShouldSkip)
62     return true;
63
64   // Some include flags shouldn't be skipped if we have a crash VFS
65   IsInclude = llvm::StringSwitch<bool>(Flag)
66     .Cases("-include", "-header-include-file", true)
67     .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
68     .Cases("-internal-externc-isystem", "-iprefix", true)
69     .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
70     .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
71     .Cases("-iframework", "-include-pch", true)
72     .Default(false);
73   if (IsInclude)
74     return !HaveCrashVFS;
75
76   // The remaining flags are treated as a single argument.
77
78   // These flags are all of the form -Flag and have no second argument.
79   ShouldSkip = llvm::StringSwitch<bool>(Flag)
80     .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
81     .Case("-MMD", true)
82     .Default(false);
83
84   // Match found.
85   SkipNum = 1;
86   if (ShouldSkip)
87     return true;
88
89   // These flags are treated as a single argument (e.g., -F<Dir>).
90   StringRef FlagRef(Flag);
91   IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
92   if (IsInclude)
93     return !HaveCrashVFS;
94   if (FlagRef.startswith("-fmodules-cache-path="))
95     return true;
96
97   SkipNum = 0;
98   return false;
99 }
100
101 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
102   const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos;
103
104   if (!Quote && !Escape) {
105     OS << Arg;
106     return;
107   }
108
109   // Quote and escape. This isn't really complete, but good enough.
110   OS << '"';
111   for (const auto c : Arg) {
112     if (c == '"' || c == '\\' || c == '$')
113       OS << '\\';
114     OS << c;
115   }
116   OS << '"';
117 }
118
119 void Command::writeResponseFile(raw_ostream &OS) const {
120   // In a file list, we only write the set of inputs to the response file
121   if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
122     for (const auto *Arg : InputFileList) {
123       OS << Arg << '\n';
124     }
125     return;
126   }
127
128   // In regular response files, we send all arguments to the response file.
129   // Wrapping all arguments in double quotes ensures that both Unix tools and
130   // Windows tools understand the response file.
131   for (const auto *Arg : Arguments) {
132     OS << '"';
133
134     for (; *Arg != '\0'; Arg++) {
135       if (*Arg == '\"' || *Arg == '\\') {
136         OS << '\\';
137       }
138       OS << *Arg;
139     }
140
141     OS << "\" ";
142   }
143 }
144
145 void Command::buildArgvForResponseFile(
146     llvm::SmallVectorImpl<const char *> &Out) const {
147   // When not a file list, all arguments are sent to the response file.
148   // This leaves us to set the argv to a single parameter, requesting the tool
149   // to read the response file.
150   if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
151     Out.push_back(Executable);
152     Out.push_back(ResponseFileFlag.c_str());
153     return;
154   }
155
156   llvm::StringSet<> Inputs;
157   for (const auto *InputName : InputFileList)
158     Inputs.insert(InputName);
159   Out.push_back(Executable);
160   // In a file list, build args vector ignoring parameters that will go in the
161   // response file (elements of the InputFileList vector)
162   bool FirstInput = true;
163   for (const auto *Arg : Arguments) {
164     if (Inputs.count(Arg) == 0) {
165       Out.push_back(Arg);
166     } else if (FirstInput) {
167       FirstInput = false;
168       Out.push_back(Creator.getResponseFileFlag());
169       Out.push_back(ResponseFile);
170     }
171   }
172 }
173
174 /// Rewrite relative include-like flag paths to absolute ones.
175 static void
176 rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
177                 size_t NumArgs,
178                 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
179   using namespace llvm;
180   using namespace sys;
181
182   auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
183     if (path::is_absolute(InInc)) // Nothing to do here...
184       return false;
185     std::error_code EC = fs::current_path(OutInc);
186     if (EC)
187       return false;
188     path::append(OutInc, InInc);
189     return true;
190   };
191
192   SmallString<128> NewInc;
193   if (NumArgs == 1) {
194     StringRef FlagRef(Args[Idx + NumArgs - 1]);
195     assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
196             "Expecting -I or -F");
197     StringRef Inc = FlagRef.slice(2, StringRef::npos);
198     if (getAbsPath(Inc, NewInc)) {
199       SmallString<128> NewArg(FlagRef.slice(0, 2));
200       NewArg += NewInc;
201       IncFlags.push_back(std::move(NewArg));
202     }
203     return;
204   }
205
206   assert(NumArgs == 2 && "Not expecting more than two arguments");
207   StringRef Inc(Args[Idx + NumArgs - 1]);
208   if (!getAbsPath(Inc, NewInc))
209     return;
210   IncFlags.push_back(SmallString<128>(Args[Idx]));
211   IncFlags.push_back(std::move(NewInc));
212 }
213
214 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
215                     CrashReportInfo *CrashInfo) const {
216   // Always quote the exe.
217   OS << ' ';
218   printArg(OS, Executable, /*Quote=*/true);
219
220   ArrayRef<const char *> Args = Arguments;
221   SmallVector<const char *, 128> ArgsRespFile;
222   if (ResponseFile != nullptr) {
223     buildArgvForResponseFile(ArgsRespFile);
224     Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
225   }
226
227   bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
228   for (size_t i = 0, e = Args.size(); i < e; ++i) {
229     const char *const Arg = Args[i];
230
231     if (CrashInfo) {
232       int NumArgs = 0;
233       bool IsInclude = false;
234       if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
235         i += NumArgs - 1;
236         continue;
237       }
238
239       // Relative includes need to be expanded to absolute paths.
240       if (HaveCrashVFS && IsInclude) {
241         SmallVector<SmallString<128>, 2> NewIncFlags;
242         rewriteIncludes(Args, i, NumArgs, NewIncFlags);
243         if (!NewIncFlags.empty()) {
244           for (auto &F : NewIncFlags) {
245             OS << ' ';
246             printArg(OS, F.c_str(), Quote);
247           }
248           i += NumArgs - 1;
249           continue;
250         }
251       }
252
253       auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
254                                 [&Arg](StringRef IF) { return IF == Arg; });
255       if (Found != InputFilenames.end() &&
256           (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
257         // Replace the input file name with the crashinfo's file name.
258         OS << ' ';
259         StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
260         printArg(OS, ShortName.str(), Quote);
261         continue;
262       }
263     }
264
265     OS << ' ';
266     printArg(OS, Arg, Quote);
267   }
268
269   if (CrashInfo && HaveCrashVFS) {
270     OS << ' ';
271     printArg(OS, "-ivfsoverlay", Quote);
272     OS << ' ';
273     printArg(OS, CrashInfo->VFSPath.str(), Quote);
274
275     // The leftover modules from the crash are stored in
276     //  <name>.cache/vfs/modules
277     // Leave it untouched for pcm inspection and provide a clean/empty dir
278     // path to contain the future generated module cache:
279     //  <name>.cache/vfs/repro-modules
280     SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
281         llvm::sys::path::parent_path(CrashInfo->VFSPath));
282     llvm::sys::path::append(RelModCacheDir, "repro-modules");
283
284     std::string ModCachePath = "-fmodules-cache-path=";
285     ModCachePath.append(RelModCacheDir.c_str());
286
287     OS << ' ';
288     printArg(OS, ModCachePath, Quote);
289   }
290
291   if (ResponseFile != nullptr) {
292     OS << "\n Arguments passed via response file:\n";
293     writeResponseFile(OS);
294     // Avoiding duplicated newline terminator, since FileLists are
295     // newline-separated.
296     if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
297       OS << "\n";
298     OS << " (end of response file)";
299   }
300
301   OS << Terminator;
302 }
303
304 void Command::setResponseFile(const char *FileName) {
305   ResponseFile = FileName;
306   ResponseFileFlag = Creator.getResponseFileFlag();
307   ResponseFileFlag += FileName;
308 }
309
310 void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
311   Environment.reserve(NewEnvironment.size() + 1);
312   Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
313   Environment.push_back(nullptr);
314 }
315
316 int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
317                      std::string *ErrMsg, bool *ExecutionFailed) const {
318   SmallVector<const char*, 128> Argv;
319
320   Optional<ArrayRef<StringRef>> Env;
321   std::vector<StringRef> ArgvVectorStorage;
322   if (!Environment.empty()) {
323     assert(Environment.back() == nullptr &&
324            "Environment vector should be null-terminated by now");
325     ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
326     Env = makeArrayRef(ArgvVectorStorage);
327   }
328
329   if (ResponseFile == nullptr) {
330     Argv.push_back(Executable);
331     Argv.append(Arguments.begin(), Arguments.end());
332     Argv.push_back(nullptr);
333
334     auto Args = llvm::toStringRefArray(Argv.data());
335     return llvm::sys::ExecuteAndWait(
336         Executable, Args, Env, Redirects, /*secondsToWait*/ 0,
337         /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
338   }
339
340   // We need to put arguments in a response file (command is too large)
341   // Open stream to store the response file contents
342   std::string RespContents;
343   llvm::raw_string_ostream SS(RespContents);
344
345   // Write file contents and build the Argv vector
346   writeResponseFile(SS);
347   buildArgvForResponseFile(Argv);
348   Argv.push_back(nullptr);
349   SS.flush();
350
351   // Save the response file in the appropriate encoding
352   if (std::error_code EC = writeFileWithEncoding(
353           ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
354     if (ErrMsg)
355       *ErrMsg = EC.message();
356     if (ExecutionFailed)
357       *ExecutionFailed = true;
358     return -1;
359   }
360
361   auto Args = llvm::toStringRefArray(Argv.data());
362   return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
363                                    /*secondsToWait*/ 0,
364                                    /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
365 }
366
367 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
368                                  const char *Executable_,
369                                  const ArgStringList &Arguments_,
370                                  ArrayRef<InputInfo> Inputs,
371                                  std::unique_ptr<Command> Fallback_)
372     : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
373       Fallback(std::move(Fallback_)) {}
374
375 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
376                             bool Quote, CrashReportInfo *CrashInfo) const {
377   Command::Print(OS, "", Quote, CrashInfo);
378   OS << " ||";
379   Fallback->Print(OS, Terminator, Quote, CrashInfo);
380 }
381
382 static bool ShouldFallback(int ExitCode) {
383   // FIXME: We really just want to fall back for internal errors, such
384   // as when some symbol cannot be mangled, when we should be able to
385   // parse something but can't, etc.
386   return ExitCode != 0;
387 }
388
389 int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
390                              std::string *ErrMsg, bool *ExecutionFailed) const {
391   int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
392   if (!ShouldFallback(PrimaryStatus))
393     return PrimaryStatus;
394
395   // Clear ExecutionFailed and ErrMsg before falling back.
396   if (ErrMsg)
397     ErrMsg->clear();
398   if (ExecutionFailed)
399     *ExecutionFailed = false;
400
401   const Driver &D = getCreator().getToolChain().getDriver();
402   D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
403
404   int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
405   return SecondaryStatus;
406 }
407
408 ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
409                                          const Tool &Creator_,
410                                          const char *Executable_,
411                                          const ArgStringList &Arguments_,
412                                          ArrayRef<InputInfo> Inputs)
413     : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
414
415 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
416                             bool Quote, CrashReportInfo *CrashInfo) const {
417   Command::Print(OS, "", Quote, CrashInfo);
418   OS << " || (exit 0)" << Terminator;
419 }
420
421 int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
422                                  std::string *ErrMsg,
423                                  bool *ExecutionFailed) const {
424   int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
425   (void)Status;
426   if (ExecutionFailed)
427     *ExecutionFailed = false;
428   return 0;
429 }
430
431 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
432                     CrashReportInfo *CrashInfo) const {
433   for (const auto &Job : *this)
434     Job.Print(OS, Terminator, Quote, CrashInfo);
435 }
436
437 void JobList::clear() { Jobs.clear(); }