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/Option/ArgList.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <errno.h>
21 #include <sys/stat.h>
22 
23 using namespace clang::driver;
24 using namespace clang;
25 using namespace llvm::opt;
26 
27 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
28                          InputArgList *_Args, DerivedArgList *_TranslatedArgs)
29   : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
30     TranslatedArgs(_TranslatedArgs), Redirects(nullptr) {
31 }
32 
33 Compilation::~Compilation() {
34   delete TranslatedArgs;
35   delete Args;
36 
37   // Free any derived arg lists.
38   for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
39                       DerivedArgList*>::iterator it = TCArgs.begin(),
40          ie = TCArgs.end(); it != ie; ++it)
41     if (it->second != TranslatedArgs)
42       delete it->second;
43 
44   // Free the actions, if built.
45   for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
46        it != ie; ++it)
47     delete *it;
48 
49   // Free redirections of stdout/stderr.
50   if (Redirects) {
51     delete Redirects[1];
52     delete Redirects[2];
53     delete [] Redirects;
54   }
55 }
56 
57 const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
58                                                        const char *BoundArch) {
59   if (!TC)
60     TC = &DefaultToolChain;
61 
62   DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
63   if (!Entry) {
64     Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
65     if (!Entry)
66       Entry = TranslatedArgs;
67   }
68 
69   return *Entry;
70 }
71 
72 bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
73   // FIXME: Why are we trying to remove files that we have not created? For
74   // example we should only try to remove a temporary assembly file if
75   // "clang -cc1" succeed in writing it. Was this a workaround for when
76   // clang was writing directly to a .s file and sometimes leaving it behind
77   // during a failure?
78 
79   // FIXME: If this is necessary, we can still try to split
80   // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
81   // duplicated stat from is_regular_file.
82 
83   // Don't try to remove files which we don't have write access to (but may be
84   // able to remove), or non-regular files. Underlying tools may have
85   // intentionally not overwritten them.
86   if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
87     return true;
88 
89   if (llvm::error_code EC = llvm::sys::fs::remove(File)) {
90     // Failure is only failure if the file exists and is "regular". We checked
91     // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
92     // so we don't need to check again.
93 
94     if (IssueErrors)
95       getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
96         << EC.message();
97     return false;
98   }
99   return true;
100 }
101 
102 bool Compilation::CleanupFileList(const ArgStringList &Files,
103                                   bool IssueErrors) const {
104   bool Success = true;
105   for (ArgStringList::const_iterator
106          it = Files.begin(), ie = Files.end(); it != ie; ++it)
107     Success &= CleanupFile(*it, IssueErrors);
108   return Success;
109 }
110 
111 bool Compilation::CleanupFileMap(const ArgStringMap &Files,
112                                  const JobAction *JA,
113                                  bool IssueErrors) const {
114   bool Success = true;
115   for (ArgStringMap::const_iterator
116          it = Files.begin(), ie = Files.end(); it != ie; ++it) {
117 
118     // If specified, only delete the files associated with the JobAction.
119     // Otherwise, delete all files in the map.
120     if (JA && it->first != JA)
121       continue;
122     Success &= CleanupFile(it->second, IssueErrors);
123   }
124   return Success;
125 }
126 
127 int Compilation::ExecuteCommand(const Command &C,
128                                 const Command *&FailingCommand) const {
129   if ((getDriver().CCPrintOptions ||
130        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
131     raw_ostream *OS = &llvm::errs();
132 
133     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
134     // output stream.
135     if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
136       std::string Error;
137       OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, Error,
138                                     llvm::sys::fs::F_Append |
139                                         llvm::sys::fs::F_Text);
140       if (!Error.empty()) {
141         getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
142           << Error;
143         FailingCommand = &C;
144         delete OS;
145         return 1;
146       }
147     }
148 
149     if (getDriver().CCPrintOptions)
150       *OS << "[Logging clang options]";
151 
152     C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
153 
154     if (OS != &llvm::errs())
155       delete OS;
156   }
157 
158   std::string Error;
159   bool ExecutionFailed;
160   int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
161   if (!Error.empty()) {
162     assert(Res && "Error string set with 0 result code!");
163     getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
164   }
165 
166   if (Res)
167     FailingCommand = &C;
168 
169   return ExecutionFailed ? 1 : Res;
170 }
171 
172 typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
173 
174 static bool ActionFailed(const Action *A,
175                          const FailingCommandList &FailingCommands) {
176 
177   if (FailingCommands.empty())
178     return false;
179 
180   for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
181          CE = FailingCommands.end(); CI != CE; ++CI)
182     if (A == &(CI->second->getSource()))
183       return true;
184 
185   for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
186     if (ActionFailed(*AI, FailingCommands))
187       return true;
188 
189   return false;
190 }
191 
192 static bool InputsOk(const Command &C,
193                      const FailingCommandList &FailingCommands) {
194   return !ActionFailed(&C.getSource(), FailingCommands);
195 }
196 
197 void Compilation::ExecuteJob(const Job &J,
198                              FailingCommandList &FailingCommands) const {
199   if (const Command *C = dyn_cast<Command>(&J)) {
200     if (!InputsOk(*C, FailingCommands))
201       return;
202     const Command *FailingCommand = nullptr;
203     if (int Res = ExecuteCommand(*C, FailingCommand))
204       FailingCommands.push_back(std::make_pair(Res, FailingCommand));
205   } else {
206     const JobList *Jobs = cast<JobList>(&J);
207     for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end();
208          it != ie; ++it)
209       ExecuteJob(**it, FailingCommands);
210   }
211 }
212 
213 void Compilation::initCompilationForDiagnostics() {
214   // Free actions and jobs.
215   DeleteContainerPointers(Actions);
216   Jobs.clear();
217 
218   // Clear temporary/results file lists.
219   TempFiles.clear();
220   ResultFiles.clear();
221   FailureResultFiles.clear();
222 
223   // Remove any user specified output.  Claim any unclaimed arguments, so as
224   // to avoid emitting warnings about unused args.
225   OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
226                                 options::OPT_MMD };
227   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
228     if (TranslatedArgs->hasArg(OutputOpts[i]))
229       TranslatedArgs->eraseArg(OutputOpts[i]);
230   }
231   TranslatedArgs->ClaimAllArgs();
232 
233   // Redirect stdout/stderr to /dev/null.
234   Redirects = new const StringRef*[3]();
235   Redirects[0] = nullptr;
236   Redirects[1] = new const StringRef();
237   Redirects[2] = new const StringRef();
238 }
239 
240 StringRef Compilation::getSysRoot() const {
241   return getDriver().SysRoot;
242 }
243