xref: /aosp_15_r20/external/clang/lib/Driver/Job.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- Job.cpp - Command to Execute -------------------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li 
10*67e74705SXin Li #include "InputInfo.h"
11*67e74705SXin Li #include "clang/Driver/Driver.h"
12*67e74705SXin Li #include "clang/Driver/DriverDiagnostic.h"
13*67e74705SXin Li #include "clang/Driver/Job.h"
14*67e74705SXin Li #include "clang/Driver/Tool.h"
15*67e74705SXin Li #include "clang/Driver/ToolChain.h"
16*67e74705SXin Li #include "llvm/ADT/ArrayRef.h"
17*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
18*67e74705SXin Li #include "llvm/ADT/StringRef.h"
19*67e74705SXin Li #include "llvm/ADT/StringSet.h"
20*67e74705SXin Li #include "llvm/ADT/StringSwitch.h"
21*67e74705SXin Li #include "llvm/Support/FileSystem.h"
22*67e74705SXin Li #include "llvm/Support/Program.h"
23*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
24*67e74705SXin Li #include <cassert>
25*67e74705SXin Li using namespace clang::driver;
26*67e74705SXin Li using llvm::raw_ostream;
27*67e74705SXin Li using llvm::StringRef;
28*67e74705SXin Li using llvm::ArrayRef;
29*67e74705SXin Li 
Command(const Action & Source,const Tool & Creator,const char * Executable,const ArgStringList & Arguments,ArrayRef<InputInfo> Inputs)30*67e74705SXin Li Command::Command(const Action &Source, const Tool &Creator,
31*67e74705SXin Li                  const char *Executable, const ArgStringList &Arguments,
32*67e74705SXin Li                  ArrayRef<InputInfo> Inputs)
33*67e74705SXin Li     : Source(Source), Creator(Creator), Executable(Executable),
34*67e74705SXin Li       Arguments(Arguments), ResponseFile(nullptr) {
35*67e74705SXin Li   for (const auto &II : Inputs)
36*67e74705SXin Li     if (II.isFilename())
37*67e74705SXin Li       InputFilenames.push_back(II.getFilename());
38*67e74705SXin Li }
39*67e74705SXin Li 
skipArgs(const char * Flag,bool HaveCrashVFS)40*67e74705SXin Li static int skipArgs(const char *Flag, bool HaveCrashVFS) {
41*67e74705SXin Li   // These flags are all of the form -Flag <Arg> and are treated as two
42*67e74705SXin Li   // arguments.  Therefore, we need to skip the flag and the next argument.
43*67e74705SXin Li   bool Res = llvm::StringSwitch<bool>(Flag)
44*67e74705SXin Li     .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
45*67e74705SXin Li     .Cases("-o", "-coverage-file", "-dependency-file", true)
46*67e74705SXin Li     .Cases("-fdebug-compilation-dir", "-idirafter", true)
47*67e74705SXin Li     .Cases("-include", "-include-pch", "-internal-isystem", true)
48*67e74705SXin Li     .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
49*67e74705SXin Li     .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
50*67e74705SXin Li     .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
51*67e74705SXin Li     .Cases("-header-include-file", "-diagnostic-log-file", true)
52*67e74705SXin Li     // Some include flags shouldn't be skipped if we have a crash VFS
53*67e74705SXin Li     .Cases("-isysroot", "-I", "-F", "-resource-dir", !HaveCrashVFS)
54*67e74705SXin Li     .Default(false);
55*67e74705SXin Li 
56*67e74705SXin Li   // Match found.
57*67e74705SXin Li   if (Res)
58*67e74705SXin Li     return 2;
59*67e74705SXin Li 
60*67e74705SXin Li   // The remaining flags are treated as a single argument.
61*67e74705SXin Li 
62*67e74705SXin Li   // These flags are all of the form -Flag and have no second argument.
63*67e74705SXin Li   Res = llvm::StringSwitch<bool>(Flag)
64*67e74705SXin Li     .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
65*67e74705SXin Li     .Case("-MMD", true)
66*67e74705SXin Li     .Default(false);
67*67e74705SXin Li 
68*67e74705SXin Li   // Match found.
69*67e74705SXin Li   if (Res)
70*67e74705SXin Li     return 1;
71*67e74705SXin Li 
72*67e74705SXin Li   // These flags are treated as a single argument (e.g., -F<Dir>).
73*67e74705SXin Li   StringRef FlagRef(Flag);
74*67e74705SXin Li   if ((!HaveCrashVFS &&
75*67e74705SXin Li        (FlagRef.startswith("-F") || FlagRef.startswith("-I"))) ||
76*67e74705SXin Li       FlagRef.startswith("-fmodules-cache-path="))
77*67e74705SXin Li     return 1;
78*67e74705SXin Li 
79*67e74705SXin Li   return 0;
80*67e74705SXin Li }
81*67e74705SXin Li 
printArg(raw_ostream & OS,const char * Arg,bool Quote)82*67e74705SXin Li void Command::printArg(raw_ostream &OS, const char *Arg, bool Quote) {
83*67e74705SXin Li   const bool Escape = std::strpbrk(Arg, "\"\\$");
84*67e74705SXin Li 
85*67e74705SXin Li   if (!Quote && !Escape) {
86*67e74705SXin Li     OS << Arg;
87*67e74705SXin Li     return;
88*67e74705SXin Li   }
89*67e74705SXin Li 
90*67e74705SXin Li   // Quote and escape. This isn't really complete, but good enough.
91*67e74705SXin Li   OS << '"';
92*67e74705SXin Li   while (const char c = *Arg++) {
93*67e74705SXin Li     if (c == '"' || c == '\\' || c == '$')
94*67e74705SXin Li       OS << '\\';
95*67e74705SXin Li     OS << c;
96*67e74705SXin Li   }
97*67e74705SXin Li   OS << '"';
98*67e74705SXin Li }
99*67e74705SXin Li 
writeResponseFile(raw_ostream & OS) const100*67e74705SXin Li void Command::writeResponseFile(raw_ostream &OS) const {
101*67e74705SXin Li   // In a file list, we only write the set of inputs to the response file
102*67e74705SXin Li   if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
103*67e74705SXin Li     for (const char *Arg : InputFileList) {
104*67e74705SXin Li       OS << Arg << '\n';
105*67e74705SXin Li     }
106*67e74705SXin Li     return;
107*67e74705SXin Li   }
108*67e74705SXin Li 
109*67e74705SXin Li   // In regular response files, we send all arguments to the response file.
110*67e74705SXin Li   // Wrapping all arguments in double quotes ensures that both Unix tools and
111*67e74705SXin Li   // Windows tools understand the response file.
112*67e74705SXin Li   for (const char *Arg : Arguments) {
113*67e74705SXin Li     OS << '"';
114*67e74705SXin Li 
115*67e74705SXin Li     for (; *Arg != '\0'; Arg++) {
116*67e74705SXin Li       if (*Arg == '\"' || *Arg == '\\') {
117*67e74705SXin Li         OS << '\\';
118*67e74705SXin Li       }
119*67e74705SXin Li       OS << *Arg;
120*67e74705SXin Li     }
121*67e74705SXin Li 
122*67e74705SXin Li     OS << "\" ";
123*67e74705SXin Li   }
124*67e74705SXin Li }
125*67e74705SXin Li 
buildArgvForResponseFile(llvm::SmallVectorImpl<const char * > & Out) const126*67e74705SXin Li void Command::buildArgvForResponseFile(
127*67e74705SXin Li     llvm::SmallVectorImpl<const char *> &Out) const {
128*67e74705SXin Li   // When not a file list, all arguments are sent to the response file.
129*67e74705SXin Li   // This leaves us to set the argv to a single parameter, requesting the tool
130*67e74705SXin Li   // to read the response file.
131*67e74705SXin Li   if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
132*67e74705SXin Li     Out.push_back(Executable);
133*67e74705SXin Li     Out.push_back(ResponseFileFlag.c_str());
134*67e74705SXin Li     return;
135*67e74705SXin Li   }
136*67e74705SXin Li 
137*67e74705SXin Li   llvm::StringSet<> Inputs;
138*67e74705SXin Li   for (const char *InputName : InputFileList)
139*67e74705SXin Li     Inputs.insert(InputName);
140*67e74705SXin Li   Out.push_back(Executable);
141*67e74705SXin Li   // In a file list, build args vector ignoring parameters that will go in the
142*67e74705SXin Li   // response file (elements of the InputFileList vector)
143*67e74705SXin Li   bool FirstInput = true;
144*67e74705SXin Li   for (const char *Arg : Arguments) {
145*67e74705SXin Li     if (Inputs.count(Arg) == 0) {
146*67e74705SXin Li       Out.push_back(Arg);
147*67e74705SXin Li     } else if (FirstInput) {
148*67e74705SXin Li       FirstInput = false;
149*67e74705SXin Li       Out.push_back(Creator.getResponseFileFlag());
150*67e74705SXin Li       Out.push_back(ResponseFile);
151*67e74705SXin Li     }
152*67e74705SXin Li   }
153*67e74705SXin Li }
154*67e74705SXin Li 
Print(raw_ostream & OS,const char * Terminator,bool Quote,CrashReportInfo * CrashInfo) const155*67e74705SXin Li void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
156*67e74705SXin Li                     CrashReportInfo *CrashInfo) const {
157*67e74705SXin Li   // Always quote the exe.
158*67e74705SXin Li   OS << ' ';
159*67e74705SXin Li   printArg(OS, Executable, /*Quote=*/true);
160*67e74705SXin Li 
161*67e74705SXin Li   llvm::ArrayRef<const char *> Args = Arguments;
162*67e74705SXin Li   llvm::SmallVector<const char *, 128> ArgsRespFile;
163*67e74705SXin Li   if (ResponseFile != nullptr) {
164*67e74705SXin Li     buildArgvForResponseFile(ArgsRespFile);
165*67e74705SXin Li     Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
166*67e74705SXin Li   }
167*67e74705SXin Li 
168*67e74705SXin Li   bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
169*67e74705SXin Li   for (size_t i = 0, e = Args.size(); i < e; ++i) {
170*67e74705SXin Li     const char *const Arg = Args[i];
171*67e74705SXin Li 
172*67e74705SXin Li     if (CrashInfo) {
173*67e74705SXin Li       if (int Skip = skipArgs(Arg, HaveCrashVFS)) {
174*67e74705SXin Li         i += Skip - 1;
175*67e74705SXin Li         continue;
176*67e74705SXin Li       }
177*67e74705SXin Li       auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
178*67e74705SXin Li                                 [&Arg](StringRef IF) { return IF == Arg; });
179*67e74705SXin Li       if (Found != InputFilenames.end() &&
180*67e74705SXin Li           (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
181*67e74705SXin Li         // Replace the input file name with the crashinfo's file name.
182*67e74705SXin Li         OS << ' ';
183*67e74705SXin Li         StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
184*67e74705SXin Li         printArg(OS, ShortName.str().c_str(), Quote);
185*67e74705SXin Li         continue;
186*67e74705SXin Li       }
187*67e74705SXin Li     }
188*67e74705SXin Li 
189*67e74705SXin Li     OS << ' ';
190*67e74705SXin Li     printArg(OS, Arg, Quote);
191*67e74705SXin Li   }
192*67e74705SXin Li 
193*67e74705SXin Li   if (CrashInfo && HaveCrashVFS) {
194*67e74705SXin Li     OS << ' ';
195*67e74705SXin Li     printArg(OS, "-ivfsoverlay", Quote);
196*67e74705SXin Li     OS << ' ';
197*67e74705SXin Li     printArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
198*67e74705SXin Li 
199*67e74705SXin Li     // Insert -fmodules-cache-path and use the relative module directory
200*67e74705SXin Li     // <name>.cache/vfs/modules where we already dumped the modules.
201*67e74705SXin Li     SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
202*67e74705SXin Li         llvm::sys::path::parent_path(CrashInfo->VFSPath));
203*67e74705SXin Li     llvm::sys::path::append(RelModCacheDir, "modules");
204*67e74705SXin Li 
205*67e74705SXin Li     std::string ModCachePath = "-fmodules-cache-path=";
206*67e74705SXin Li     ModCachePath.append(RelModCacheDir.c_str());
207*67e74705SXin Li 
208*67e74705SXin Li     OS << ' ';
209*67e74705SXin Li     printArg(OS, ModCachePath.c_str(), Quote);
210*67e74705SXin Li   }
211*67e74705SXin Li 
212*67e74705SXin Li   if (ResponseFile != nullptr) {
213*67e74705SXin Li     OS << "\n Arguments passed via response file:\n";
214*67e74705SXin Li     writeResponseFile(OS);
215*67e74705SXin Li     // Avoiding duplicated newline terminator, since FileLists are
216*67e74705SXin Li     // newline-separated.
217*67e74705SXin Li     if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
218*67e74705SXin Li       OS << "\n";
219*67e74705SXin Li     OS << " (end of response file)";
220*67e74705SXin Li   }
221*67e74705SXin Li 
222*67e74705SXin Li   OS << Terminator;
223*67e74705SXin Li }
224*67e74705SXin Li 
setResponseFile(const char * FileName)225*67e74705SXin Li void Command::setResponseFile(const char *FileName) {
226*67e74705SXin Li   ResponseFile = FileName;
227*67e74705SXin Li   ResponseFileFlag = Creator.getResponseFileFlag();
228*67e74705SXin Li   ResponseFileFlag += FileName;
229*67e74705SXin Li }
230*67e74705SXin Li 
Execute(const StringRef ** Redirects,std::string * ErrMsg,bool * ExecutionFailed) const231*67e74705SXin Li int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
232*67e74705SXin Li                      bool *ExecutionFailed) const {
233*67e74705SXin Li   SmallVector<const char*, 128> Argv;
234*67e74705SXin Li 
235*67e74705SXin Li   if (ResponseFile == nullptr) {
236*67e74705SXin Li     Argv.push_back(Executable);
237*67e74705SXin Li     Argv.append(Arguments.begin(), Arguments.end());
238*67e74705SXin Li     Argv.push_back(nullptr);
239*67e74705SXin Li 
240*67e74705SXin Li     return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
241*67e74705SXin Li                                      Redirects, /*secondsToWait*/ 0,
242*67e74705SXin Li                                      /*memoryLimit*/ 0, ErrMsg,
243*67e74705SXin Li                                      ExecutionFailed);
244*67e74705SXin Li   }
245*67e74705SXin Li 
246*67e74705SXin Li   // We need to put arguments in a response file (command is too large)
247*67e74705SXin Li   // Open stream to store the response file contents
248*67e74705SXin Li   std::string RespContents;
249*67e74705SXin Li   llvm::raw_string_ostream SS(RespContents);
250*67e74705SXin Li 
251*67e74705SXin Li   // Write file contents and build the Argv vector
252*67e74705SXin Li   writeResponseFile(SS);
253*67e74705SXin Li   buildArgvForResponseFile(Argv);
254*67e74705SXin Li   Argv.push_back(nullptr);
255*67e74705SXin Li   SS.flush();
256*67e74705SXin Li 
257*67e74705SXin Li   // Save the response file in the appropriate encoding
258*67e74705SXin Li   if (std::error_code EC = writeFileWithEncoding(
259*67e74705SXin Li           ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
260*67e74705SXin Li     if (ErrMsg)
261*67e74705SXin Li       *ErrMsg = EC.message();
262*67e74705SXin Li     if (ExecutionFailed)
263*67e74705SXin Li       *ExecutionFailed = true;
264*67e74705SXin Li     return -1;
265*67e74705SXin Li   }
266*67e74705SXin Li 
267*67e74705SXin Li   return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
268*67e74705SXin Li                                    Redirects, /*secondsToWait*/ 0,
269*67e74705SXin Li                                    /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
270*67e74705SXin Li }
271*67e74705SXin Li 
FallbackCommand(const Action & Source_,const Tool & Creator_,const char * Executable_,const ArgStringList & Arguments_,ArrayRef<InputInfo> Inputs,std::unique_ptr<Command> Fallback_)272*67e74705SXin Li FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
273*67e74705SXin Li                                  const char *Executable_,
274*67e74705SXin Li                                  const ArgStringList &Arguments_,
275*67e74705SXin Li                                  ArrayRef<InputInfo> Inputs,
276*67e74705SXin Li                                  std::unique_ptr<Command> Fallback_)
277*67e74705SXin Li     : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
278*67e74705SXin Li       Fallback(std::move(Fallback_)) {}
279*67e74705SXin Li 
Print(raw_ostream & OS,const char * Terminator,bool Quote,CrashReportInfo * CrashInfo) const280*67e74705SXin Li void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
281*67e74705SXin Li                             bool Quote, CrashReportInfo *CrashInfo) const {
282*67e74705SXin Li   Command::Print(OS, "", Quote, CrashInfo);
283*67e74705SXin Li   OS << " ||";
284*67e74705SXin Li   Fallback->Print(OS, Terminator, Quote, CrashInfo);
285*67e74705SXin Li }
286*67e74705SXin Li 
ShouldFallback(int ExitCode)287*67e74705SXin Li static bool ShouldFallback(int ExitCode) {
288*67e74705SXin Li   // FIXME: We really just want to fall back for internal errors, such
289*67e74705SXin Li   // as when some symbol cannot be mangled, when we should be able to
290*67e74705SXin Li   // parse something but can't, etc.
291*67e74705SXin Li   return ExitCode != 0;
292*67e74705SXin Li }
293*67e74705SXin Li 
Execute(const StringRef ** Redirects,std::string * ErrMsg,bool * ExecutionFailed) const294*67e74705SXin Li int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg,
295*67e74705SXin Li                              bool *ExecutionFailed) const {
296*67e74705SXin Li   int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
297*67e74705SXin Li   if (!ShouldFallback(PrimaryStatus))
298*67e74705SXin Li     return PrimaryStatus;
299*67e74705SXin Li 
300*67e74705SXin Li   // Clear ExecutionFailed and ErrMsg before falling back.
301*67e74705SXin Li   if (ErrMsg)
302*67e74705SXin Li     ErrMsg->clear();
303*67e74705SXin Li   if (ExecutionFailed)
304*67e74705SXin Li     *ExecutionFailed = false;
305*67e74705SXin Li 
306*67e74705SXin Li   const Driver &D = getCreator().getToolChain().getDriver();
307*67e74705SXin Li   D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();
308*67e74705SXin Li 
309*67e74705SXin Li   int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
310*67e74705SXin Li   return SecondaryStatus;
311*67e74705SXin Li }
312*67e74705SXin Li 
ForceSuccessCommand(const Action & Source_,const Tool & Creator_,const char * Executable_,const ArgStringList & Arguments_,ArrayRef<InputInfo> Inputs)313*67e74705SXin Li ForceSuccessCommand::ForceSuccessCommand(const Action &Source_,
314*67e74705SXin Li                                          const Tool &Creator_,
315*67e74705SXin Li                                          const char *Executable_,
316*67e74705SXin Li                                          const ArgStringList &Arguments_,
317*67e74705SXin Li                                          ArrayRef<InputInfo> Inputs)
318*67e74705SXin Li     : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}
319*67e74705SXin Li 
Print(raw_ostream & OS,const char * Terminator,bool Quote,CrashReportInfo * CrashInfo) const320*67e74705SXin Li void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
321*67e74705SXin Li                             bool Quote, CrashReportInfo *CrashInfo) const {
322*67e74705SXin Li   Command::Print(OS, "", Quote, CrashInfo);
323*67e74705SXin Li   OS << " || (exit 0)" << Terminator;
324*67e74705SXin Li }
325*67e74705SXin Li 
Execute(const StringRef ** Redirects,std::string * ErrMsg,bool * ExecutionFailed) const326*67e74705SXin Li int ForceSuccessCommand::Execute(const StringRef **Redirects,
327*67e74705SXin Li                                  std::string *ErrMsg,
328*67e74705SXin Li                                  bool *ExecutionFailed) const {
329*67e74705SXin Li   int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
330*67e74705SXin Li   (void)Status;
331*67e74705SXin Li   if (ExecutionFailed)
332*67e74705SXin Li     *ExecutionFailed = false;
333*67e74705SXin Li   return 0;
334*67e74705SXin Li }
335*67e74705SXin Li 
Print(raw_ostream & OS,const char * Terminator,bool Quote,CrashReportInfo * CrashInfo) const336*67e74705SXin Li void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
337*67e74705SXin Li                     CrashReportInfo *CrashInfo) const {
338*67e74705SXin Li   for (const auto &Job : *this)
339*67e74705SXin Li     Job.Print(OS, Terminator, Quote, CrashInfo);
340*67e74705SXin Li }
341*67e74705SXin Li 
clear()342*67e74705SXin Li void JobList::clear() { Jobs.clear(); }
343