1 //===--- Compilation.cpp - Compilation Task Implementation ----------------===//
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/Compilation.h"
11 #include "clang/Driver/Action.h"
12 #include "clang/Driver/Driver.h"
13 #include "clang/Driver/DriverDiagnostic.h"
14 #include "clang/Driver/Options.h"
15 #include "clang/Driver/ToolChain.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/Program.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <errno.h>
22 #include <sys/stat.h>
23 
24 using namespace clang::driver;
25 using namespace clang;
26 using namespace llvm::opt;
27 
28 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
29                          InputArgList *_Args, DerivedArgList *_TranslatedArgs)
30   : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
31     TranslatedArgs(_TranslatedArgs), Redirects(0) {
32 }
33 
34 Compilation::~Compilation() {
35   delete TranslatedArgs;
36   delete Args;
37 
38   // Free any derived arg lists.
39   for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
40                       DerivedArgList*>::iterator it = TCArgs.begin(),
41          ie = TCArgs.end(); it != ie; ++it)
42     if (it->second != TranslatedArgs)
43       delete it->second;
44 
45   // Free the actions, if built.
46   for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
47        it != ie; ++it)
48     delete *it;
49 
50   // Free redirections of stdout/stderr.
51   if (Redirects) {
52     delete Redirects[1];
53     delete Redirects[2];
54     delete [] Redirects;
55   }
56 }
57 
58 const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
59                                                        const char *BoundArch) {
60   if (!TC)
61     TC = &DefaultToolChain;
62 
63   DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
64   if (!Entry) {
65     Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
66     if (!Entry)
67       Entry = TranslatedArgs;
68   }
69 
70   return *Entry;
71 }
72 
73 void Compilation::PrintJob(raw_ostream &OS, const Job &J,
74                            const char *Terminator, bool Quote) const {
75   if (const Command *C = dyn_cast<Command>(&J)) {
76     OS << " \"" << C->getExecutable() << '"';
77     for (ArgStringList::const_iterator it = C->getArguments().begin(),
78            ie = C->getArguments().end(); it != ie; ++it) {
79       OS << ' ';
80       if (!Quote && !std::strpbrk(*it, " \"\\$")) {
81         OS << *it;
82         continue;
83       }
84 
85       // Quote the argument and escape shell special characters; this isn't
86       // really complete but is good enough.
87       OS << '"';
88       for (const char *s = *it; *s; ++s) {
89         if (*s == '"' || *s == '\\' || *s == '$')
90           OS << '\\';
91         OS << *s;
92       }
93       OS << '"';
94     }
95     OS << Terminator;
96   } else {
97     const JobList *Jobs = cast<JobList>(&J);
98     for (JobList::const_iterator
99            it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
100       PrintJob(OS, **it, Terminator, Quote);
101   }
102 }
103 
104 static bool skipArg(const char *Flag, bool &SkipNextArg) {
105   StringRef FlagRef(Flag);
106 
107   // Assume we're going to see -Flag <Arg>.
108   SkipNextArg = true;
109 
110   // These flags are all of the form -Flag <Arg> and are treated as two
111   // arguments.  Therefore, we need to skip the flag and the next argument.
112   bool Res = llvm::StringSwitch<bool>(Flag)
113     .Cases("-I", "-MF", "-MT", "-MQ", true)
114     .Cases("-o", "-coverage-file", "-dependency-file", true)
115     .Cases("-fdebug-compilation-dir", "-idirafter", true)
116     .Cases("-include", "-include-pch", "-internal-isystem", true)
117     .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true)
118     .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true)
119     .Cases("-resource-dir", "-serialize-diagnostic-file", true)
120     .Case("-dwarf-debug-flags", true)
121     .Default(false);
122 
123   // Match found.
124   if (Res)
125     return Res;
126 
127   // The remaining flags are treated as a single argument.
128   SkipNextArg = false;
129 
130   // These flags are all of the form -Flag and have no second argument.
131   Res = llvm::StringSwitch<bool>(Flag)
132     .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
133     .Case("-MMD", true)
134     .Default(false);
135 
136   // Match found.
137   if (Res)
138     return Res;
139 
140   // These flags are treated as a single argument (e.g., -F<Dir>).
141   if (FlagRef.startswith("-F") || FlagRef.startswith("-I"))
142     return true;
143 
144   return false;
145 }
146 
147 static bool quoteNextArg(const char *flag) {
148   return llvm::StringSwitch<bool>(flag)
149     .Case("-D", true)
150     .Default(false);
151 }
152 
153 void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const {
154   if (const Command *C = dyn_cast<Command>(&J)) {
155     OS << C->getExecutable();
156     unsigned QuoteNextArg = 0;
157     for (ArgStringList::const_iterator it = C->getArguments().begin(),
158            ie = C->getArguments().end(); it != ie; ++it) {
159 
160       bool SkipNext;
161       if (skipArg(*it, SkipNext)) {
162         if (SkipNext) ++it;
163         continue;
164       }
165 
166       if (!QuoteNextArg)
167         QuoteNextArg = quoteNextArg(*it) ? 2 : 0;
168 
169       OS << ' ';
170 
171       if (QuoteNextArg == 1)
172         OS << '"';
173 
174       if (!std::strpbrk(*it, " \"\\$")) {
175         OS << *it;
176       } else {
177         // Quote the argument and escape shell special characters; this isn't
178         // really complete but is good enough.
179         OS << '"';
180         for (const char *s = *it; *s; ++s) {
181           if (*s == '"' || *s == '\\' || *s == '$')
182             OS << '\\';
183           OS << *s;
184         }
185         OS << '"';
186       }
187 
188       if (QuoteNextArg) {
189         if (QuoteNextArg == 1)
190           OS << '"';
191         --QuoteNextArg;
192       }
193     }
194     OS << '\n';
195   } else {
196     const JobList *Jobs = cast<JobList>(&J);
197     for (JobList::const_iterator
198            it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
199       PrintDiagnosticJob(OS, **it);
200   }
201 }
202 
203 bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
204   llvm::sys::Path P(File);
205   std::string Error;
206 
207   // Don't try to remove files which we don't have write access to (but may be
208   // able to remove), or non-regular files. Underlying tools may have
209   // intentionally not overwritten them.
210   if (!P.canWrite() || !P.isRegularFile())
211     return true;
212 
213   if (P.eraseFromDisk(false, &Error)) {
214     // Failure is only failure if the file exists and is "regular". There is
215     // a race condition here due to the limited interface of
216     // llvm::sys::Path, we want to know if the removal gave ENOENT.
217 
218     // FIXME: Grumble, P.exists() is broken. PR3837.
219     struct stat buf;
220     if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
221         (errno != ENOENT)) {
222       if (IssueErrors)
223         getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
224           << Error;
225       return false;
226     }
227   }
228   return true;
229 }
230 
231 bool Compilation::CleanupFileList(const ArgStringList &Files,
232                                   bool IssueErrors) const {
233   bool Success = true;
234   for (ArgStringList::const_iterator
235          it = Files.begin(), ie = Files.end(); it != ie; ++it)
236     Success &= CleanupFile(*it, IssueErrors);
237   return Success;
238 }
239 
240 bool Compilation::CleanupFileMap(const ArgStringMap &Files,
241                                  const JobAction *JA,
242                                  bool IssueErrors) const {
243   bool Success = true;
244   for (ArgStringMap::const_iterator
245          it = Files.begin(), ie = Files.end(); it != ie; ++it) {
246 
247     // If specified, only delete the files associated with the JobAction.
248     // Otherwise, delete all files in the map.
249     if (JA && it->first != JA)
250       continue;
251     Success &= CleanupFile(it->second, IssueErrors);
252   }
253   return Success;
254 }
255 
256 int Compilation::ExecuteCommand(const Command &C,
257                                 const Command *&FailingCommand) const {
258   llvm::sys::Path Prog(C.getExecutable());
259   const char **Argv = new const char*[C.getArguments().size() + 2];
260   Argv[0] = C.getExecutable();
261   std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
262   Argv[C.getArguments().size() + 1] = 0;
263 
264   if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
265        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
266     raw_ostream *OS = &llvm::errs();
267 
268     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
269     // output stream.
270     if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
271       std::string Error;
272       OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
273                                     Error,
274                                     llvm::raw_fd_ostream::F_Append);
275       if (!Error.empty()) {
276         getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
277           << Error;
278         FailingCommand = &C;
279         delete OS;
280         return 1;
281       }
282     }
283 
284     if (getDriver().CCPrintOptions)
285       *OS << "[Logging clang options]";
286 
287     PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
288 
289     if (OS != &llvm::errs())
290       delete OS;
291   }
292 
293   std::string Error;
294   bool ExecutionFailed;
295   int Res = llvm::sys::ExecuteAndWait(Prog.str(), Argv, /*env*/ 0, Redirects,
296                                       /*secondsToWait*/ 0, /*memoryLimit*/ 0,
297                                       &Error, &ExecutionFailed);
298   if (!Error.empty()) {
299     assert(Res && "Error string set with 0 result code!");
300     getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
301   }
302 
303   if (Res)
304     FailingCommand = &C;
305 
306   delete[] Argv;
307   return ExecutionFailed ? 1 : Res;
308 }
309 
310 typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
311 
312 static bool ActionFailed(const Action *A,
313                          const FailingCommandList &FailingCommands) {
314 
315   if (FailingCommands.empty())
316     return false;
317 
318   for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
319          CE = FailingCommands.end(); CI != CE; ++CI)
320     if (A == &(CI->second->getSource()))
321       return true;
322 
323   for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
324     if (ActionFailed(*AI, FailingCommands))
325       return true;
326 
327   return false;
328 }
329 
330 static bool InputsOk(const Command &C,
331                      const FailingCommandList &FailingCommands) {
332   return !ActionFailed(&C.getSource(), FailingCommands);
333 }
334 
335 void Compilation::ExecuteJob(const Job &J,
336                              FailingCommandList &FailingCommands) const {
337   if (const Command *C = dyn_cast<Command>(&J)) {
338     if (!InputsOk(*C, FailingCommands))
339       return;
340     const Command *FailingCommand = 0;
341     if (int Res = ExecuteCommand(*C, FailingCommand))
342       FailingCommands.push_back(std::make_pair(Res, FailingCommand));
343   } else {
344     const JobList *Jobs = cast<JobList>(&J);
345     for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
346          it != ie; ++it)
347       ExecuteJob(**it, FailingCommands);
348   }
349 }
350 
351 void Compilation::initCompilationForDiagnostics() {
352   // Free actions and jobs.
353   DeleteContainerPointers(Actions);
354   Jobs.clear();
355 
356   // Clear temporary/results file lists.
357   TempFiles.clear();
358   ResultFiles.clear();
359   FailureResultFiles.clear();
360 
361   // Remove any user specified output.  Claim any unclaimed arguments, so as
362   // to avoid emitting warnings about unused args.
363   OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
364                                 options::OPT_MMD };
365   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
366     if (TranslatedArgs->hasArg(OutputOpts[i]))
367       TranslatedArgs->eraseArg(OutputOpts[i]);
368   }
369   TranslatedArgs->ClaimAllArgs();
370 
371   // Redirect stdout/stderr to /dev/null.
372   Redirects = new const StringRef*[3]();
373   Redirects[0] = 0;
374   Redirects[1] = new const StringRef();
375   Redirects[2] = new const StringRef();
376 }
377 
378 StringRef Compilation::getSysRoot() const {
379   return getDriver().SysRoot;
380 }
381