16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSet.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Support/CrashRecoveryContext.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/Path.h" 25 #include "llvm/Support/PrettyStackTrace.h" 26 #include "llvm/Support/Program.h" 27 #include "llvm/Support/raw_ostream.h" 32 #include <system_error> 35 using namespace clang;
36 using namespace driver;
39 const char *Executable,
40 const llvm::opt::ArgStringList &Arguments,
42 : Source(Source), Creator(Creator), Executable(Executable),
43 Arguments(Arguments) {
44 for (
const auto &II : Inputs)
46 InputFilenames.push_back(II.getFilename());
52 static bool skipArgs(
const char *Flag,
bool HaveCrashVFS,
int &SkipNum,
57 bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
58 .Cases(
"-MF",
"-MT",
"-MQ",
"-serialize-diagnostic-file",
true)
59 .Cases(
"-o",
"-dependency-file",
true)
60 .Cases(
"-fdebug-compilation-dir",
"-diagnostic-log-file",
true)
61 .Cases(
"-dwarf-debug-flags",
"-ivfsoverlay",
true)
67 IsInclude = llvm::StringSwitch<bool>(Flag)
68 .Cases(
"-include",
"-header-include-file",
true)
69 .Cases(
"-idirafter",
"-internal-isystem",
"-iwithprefix",
true)
70 .Cases(
"-internal-externc-isystem",
"-iprefix",
true)
71 .Cases(
"-iwithprefixbefore",
"-isystem",
"-iquote",
true)
72 .Cases(
"-isysroot",
"-I",
"-F",
"-resource-dir",
true)
73 .Cases(
"-iframework",
"-include-pch",
true)
81 ShouldSkip = llvm::StringSwitch<bool>(Flag)
82 .Cases(
"-M",
"-MM",
"-MG",
"-MP",
"-MD",
true)
92 StringRef FlagRef(Flag);
93 IsInclude = FlagRef.startswith(
"-F") || FlagRef.startswith(
"-I");
96 if (FlagRef.startswith(
"-fmodules-cache-path="))
104 const bool Escape = Arg.find_first_of(
" \"\\$") != StringRef::npos;
106 if (!Quote && !Escape) {
113 for (
const auto c : Arg) {
114 if (c ==
'"' || c ==
'\\' || c ==
'$')
121 void Command::writeResponseFile(raw_ostream &OS)
const {
124 for (
const auto *Arg : InputFileList) {
133 for (
const auto *Arg : Arguments) {
136 for (; *Arg !=
'\0'; Arg++) {
137 if (*Arg ==
'\"' || *Arg ==
'\\') {
147 void Command::buildArgvForResponseFile(
153 Out.push_back(Executable);
154 Out.push_back(ResponseFileFlag.c_str());
158 llvm::StringSet<> Inputs;
159 for (
const auto *InputName : InputFileList)
160 Inputs.insert(InputName);
161 Out.push_back(Executable);
164 bool FirstInput =
true;
165 for (
const auto *Arg : Arguments) {
166 if (Inputs.count(Arg) == 0) {
168 }
else if (FirstInput) {
171 Out.push_back(ResponseFile);
181 using namespace llvm;
185 if (path::is_absolute(InInc))
187 std::error_code EC = fs::current_path(OutInc);
190 path::append(OutInc, InInc);
196 StringRef FlagRef(Args[Idx + NumArgs - 1]);
197 assert((FlagRef.startswith(
"-F") || FlagRef.startswith(
"-I")) &&
198 "Expecting -I or -F");
199 StringRef Inc = FlagRef.slice(2, StringRef::npos);
200 if (getAbsPath(Inc, NewInc)) {
203 IncFlags.push_back(std::move(NewArg));
208 assert(NumArgs == 2 &&
"Not expecting more than two arguments");
209 StringRef Inc(Args[Idx + NumArgs - 1]);
210 if (!getAbsPath(Inc, NewInc))
213 IncFlags.push_back(std::move(NewInc));
224 if (ResponseFile !=
nullptr) {
225 buildArgvForResponseFile(ArgsRespFile);
229 bool HaveCrashVFS = CrashInfo && !CrashInfo->
VFSPath.empty();
230 for (
size_t i = 0, e = Args.size(); i < e; ++i) {
231 const char *
const Arg = Args[i];
235 bool IsInclude =
false;
236 if (
skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
242 if (HaveCrashVFS && IsInclude) {
245 if (!NewIncFlags.empty()) {
246 for (
auto &F : NewIncFlags) {
255 auto Found = llvm::find_if(InputFilenames,
256 [&Arg](StringRef IF) {
return IF == Arg; });
257 if (Found != InputFilenames.end() &&
258 (i == 0 || StringRef(Args[i - 1]) !=
"-main-file-name")) {
261 StringRef ShortName = llvm::sys::path::filename(CrashInfo->
Filename);
262 printArg(OS, ShortName.str(), Quote);
271 if (CrashInfo && HaveCrashVFS) {
273 printArg(OS,
"-ivfsoverlay", Quote);
283 llvm::sys::path::parent_path(CrashInfo->
VFSPath));
284 llvm::sys::path::append(RelModCacheDir,
"repro-modules");
286 std::string ModCachePath =
"-fmodules-cache-path=";
287 ModCachePath.append(RelModCacheDir.c_str());
293 if (ResponseFile !=
nullptr) {
294 OS <<
"\n Arguments passed via response file:\n";
295 writeResponseFile(OS);
300 OS <<
" (end of response file)";
307 ResponseFile = FileName;
308 ResponseFileFlag = Creator.getResponseFileFlag();
309 ResponseFileFlag += FileName;
313 Environment.reserve(NewEnvironment.size() + 1);
314 Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
315 Environment.push_back(
nullptr);
320 for (
const char *Arg : InputFilenames)
321 llvm::outs() << llvm::sys::path::filename(Arg) <<
"\n";
322 llvm::outs().flush();
327 std::string *ErrMsg,
bool *ExecutionFailed)
const {
331 if (ResponseFile ==
nullptr) {
332 Argv.push_back(Executable);
333 Argv.append(Arguments.begin(), Arguments.end());
334 Argv.push_back(
nullptr);
337 std::string RespContents;
338 llvm::raw_string_ostream SS(RespContents);
341 writeResponseFile(SS);
342 buildArgvForResponseFile(Argv);
343 Argv.push_back(
nullptr);
347 if (std::error_code EC = writeFileWithEncoding(
348 ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
350 *ErrMsg = EC.message();
352 *ExecutionFailed =
true;
360 std::vector<StringRef> ArgvVectorStorage;
361 if (!Environment.empty()) {
362 assert(Environment.back() ==
nullptr &&
363 "Environment vector should be null-terminated by now");
364 ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
365 Env = makeArrayRef(ArgvVectorStorage);
368 auto Args = llvm::toStringRefArray(Argv.data());
369 return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
371 0, ErrMsg, ExecutionFailed);
375 const char *Executable,
376 const llvm::opt::ArgStringList &Arguments,
378 :
Command(Source, Creator, Executable, Arguments, Inputs) {
385 OS <<
" (in-process)\n";
390 std::string *ErrMsg,
bool *ExecutionFailed)
const {
402 Argv.push_back(
nullptr);
407 *ExecutionFailed =
false;
409 llvm::CrashRecoveryContext CRC;
410 CRC.DumpStackAndCleanupOnFailure =
true;
412 const void *PrettyState = llvm::SavePrettyStackState();
417 if (!CRC.RunSafely([&]() { R = D.CC1Main(Argv); })) {
418 llvm::RestorePrettyStackState(PrettyState);
427 "The CC1Command doesn't support changing the environment vars!");
431 const char *Executable_,
432 const llvm::opt::ArgStringList &Arguments_,
434 std::unique_ptr<Command> Fallback_)
435 :
Command(Source_, Creator_, Executable_, Arguments_, Inputs),
436 Fallback(
std::move(Fallback_)) {}
442 Fallback->Print(OS, Terminator, Quote, CrashInfo);
449 return ExitCode != 0;
453 std::string *ErrMsg,
bool *ExecutionFailed)
const {
456 return PrimaryStatus;
462 *ExecutionFailed =
false;
465 D.
Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
467 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
468 return SecondaryStatus;
472 const Action &Source_,
const Tool &Creator_,
const char *Executable_,
474 :
Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
479 OS <<
" || (exit 0)" << Terminator;
484 bool *ExecutionFailed)
const {
488 *ExecutionFailed =
false;
494 for (
const auto &Job : *
this)
495 Job.Print(OS, Terminator, Quote, CrashInfo);
int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const override
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
void setResponseFile(const char *FileName)
Set to pass arguments via a response file when launching the command.
DiagnosticBuilder Diag(unsigned DiagID) const
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.
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const override
Command(const Action &Source, const Tool &Creator, const char *Executable, const llvm::opt::ArgStringList &Arguments, ArrayRef< InputInfo > Inputs)
bool PrintInputFilenames
Whether to print the input filenames when executing.
Action - Represent an abstract compilation step to perform.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
FallbackCommand(const Action &Source_, const Tool &Creator_, const char *Executable_, const llvm::opt::ArgStringList &Arguments_, ArrayRef< InputInfo > Inputs, std::unique_ptr< Command > Fallback_)
CC1Command(const Action &Source, const Tool &Creator, const char *Executable, const llvm::opt::ArgStringList &Arguments, ArrayRef< InputInfo > Inputs)
int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const override
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
virtual void setEnvironment(llvm::ArrayRef< const char *> NewEnvironment)
Sets the environment to be used by the new process.
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.
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
static bool ShouldFallback(int ExitCode)
static void printArg(llvm::raw_ostream &OS, StringRef Arg, bool Quote)
Print a command argument, and optionally quote it.
void clear()
Clear the job list.
Command - An executable path/name and argument vector to execute.
bool InProcess
Whether the command will be executed in this process or not.
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const override
Dataflow Directional Tag Classes.
const char * getExecutable() const
const llvm::opt::ArgStringList & getArguments() const
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const override
void setEnvironment(llvm::ArrayRef< const char *> NewEnvironment) override
Sets the environment to be used by the new process.
void PrintFileNames() const
Optionally print the filenames to be compiled.
int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const override
ForceSuccessCommand(const Action &Source_, const Tool &Creator_, const char *Executable_, const llvm::opt::ArgStringList &Arguments_, ArrayRef< InputInfo > Inputs)
virtual void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
virtual int Execute(ArrayRef< Optional< StringRef >> Redirects, std::string *ErrMsg, bool *ExecutionFailed) const