Compilation.cpp revision 2da13b15959365df7edf1ed12a049b599b39c276
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
12#include "clang/Driver/Action.h"
13#include "clang/Driver/ArgList.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/DriverDiagnostic.h"
16#include "clang/Driver/Options.h"
17#include "clang/Driver/ToolChain.h"
18
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/Support/Program.h"
21#include <sys/stat.h>
22#include <errno.h>
23using namespace clang::driver;
24
25Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
26                         InputArgList *_Args, DerivedArgList *_TranslatedArgs)
27  : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
28    TranslatedArgs(_TranslatedArgs), Redirects(0) {
29}
30
31Compilation::~Compilation() {
32  delete TranslatedArgs;
33  delete Args;
34
35  // Free any derived arg lists.
36  for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
37                      DerivedArgList*>::iterator it = TCArgs.begin(),
38         ie = TCArgs.end(); it != ie; ++it)
39    if (it->second != TranslatedArgs)
40      delete it->second;
41
42  // Free the actions, if built.
43  for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
44       it != ie; ++it)
45    delete *it;
46
47  // Free redirections of stdout/stderr.
48  if (Redirects) {
49    delete Redirects[1];
50    delete Redirects[2];
51    delete Redirects;
52  }
53}
54
55const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
56                                                       const char *BoundArch) {
57  if (!TC)
58    TC = &DefaultToolChain;
59
60  DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
61  if (!Entry) {
62    Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
63    if (!Entry)
64      Entry = TranslatedArgs;
65  }
66
67  return *Entry;
68}
69
70void Compilation::PrintJob(llvm::raw_ostream &OS, const Job &J,
71                           const char *Terminator, bool Quote) const {
72  if (const Command *C = dyn_cast<Command>(&J)) {
73    OS << " \"" << C->getExecutable() << '"';
74    for (ArgStringList::const_iterator it = C->getArguments().begin(),
75           ie = C->getArguments().end(); it != ie; ++it) {
76      OS << ' ';
77      if (!Quote) {
78        OS << *it;
79        continue;
80      }
81
82      // Quote the argument and escape shell special characters; this isn't
83      // really complete but is good enough.
84      OS << '"';
85      for (const char *s = *it; *s; ++s) {
86        if (*s == '"' || *s == '\\' || *s == '$')
87          OS << '\\';
88        OS << *s;
89      }
90      OS << '"';
91    }
92    OS << Terminator;
93  } else {
94    const JobList *Jobs = cast<JobList>(&J);
95    for (JobList::const_iterator
96           it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
97      PrintJob(OS, **it, Terminator, Quote);
98  }
99}
100
101bool Compilation::CleanupFileList(const ArgStringList &Files,
102                                  bool IssueErrors) const {
103  bool Success = true;
104
105  for (ArgStringList::const_iterator
106         it = Files.begin(), ie = Files.end(); it != ie; ++it) {
107
108    llvm::sys::Path P(*it);
109    std::string Error;
110
111    // Don't try to remove files which we don't have write access to (but may be
112    // able to remove). Underlying tools may have intentionally not overwritten
113    // them.
114    if (!P.canWrite())
115      continue;
116
117    if (P.eraseFromDisk(false, &Error)) {
118      // Failure is only failure if the file exists and is "regular". There is
119      // a race condition here due to the limited interface of
120      // llvm::sys::Path, we want to know if the removal gave ENOENT.
121
122      // FIXME: Grumble, P.exists() is broken. PR3837.
123      struct stat buf;
124      if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG :
125                                         (errno != ENOENT)) {
126        if (IssueErrors)
127          getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
128            << Error;
129        Success = false;
130      }
131    }
132  }
133
134  return Success;
135}
136
137int Compilation::ExecuteCommand(const Command &C,
138                                const Command *&FailingCommand) const {
139  llvm::sys::Path Prog(C.getExecutable());
140  const char **Argv = new const char*[C.getArguments().size() + 2];
141  Argv[0] = C.getExecutable();
142  std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);
143  Argv[C.getArguments().size() + 1] = 0;
144
145  if ((getDriver().CCCEcho || getDriver().CCPrintOptions ||
146       getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
147    llvm::raw_ostream *OS = &llvm::errs();
148
149    // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
150    // output stream.
151    if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
152      std::string Error;
153      OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename,
154                                    Error,
155                                    llvm::raw_fd_ostream::F_Append);
156      if (!Error.empty()) {
157        getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
158          << Error;
159        FailingCommand = &C;
160        delete OS;
161        return 1;
162      }
163    }
164
165    if (getDriver().CCPrintOptions)
166      *OS << "[Logging clang options]";
167
168    PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions);
169
170    if (OS != &llvm::errs())
171      delete OS;
172  }
173
174  std::string Error;
175  int Res =
176    llvm::sys::Program::ExecuteAndWait(Prog, Argv,
177                                       /*env*/0, Redirects,
178                                       /*secondsToWait*/0, /*memoryLimit*/0,
179                                       &Error);
180  if (!Error.empty()) {
181    assert(Res && "Error string set with 0 result code!");
182    getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
183  }
184
185  if (Res)
186    FailingCommand = &C;
187
188  delete[] Argv;
189  return Res;
190}
191
192int Compilation::ExecuteJob(const Job &J,
193                            const Command *&FailingCommand) const {
194  if (const Command *C = dyn_cast<Command>(&J)) {
195    return ExecuteCommand(*C, FailingCommand);
196  } else {
197    const JobList *Jobs = cast<JobList>(&J);
198    for (JobList::const_iterator
199           it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it)
200      if (int Res = ExecuteJob(**it, FailingCommand))
201        return Res;
202    return 0;
203  }
204}
205
206void Compilation::initCompilationForDiagnostics(void) {
207  // Free actions and jobs, if built.
208  for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
209       it != ie; ++it)
210    delete *it;
211  Actions.clear();
212  Jobs.clear();
213
214  // Clear temporary and results file lists.
215  TempFiles.clear();
216  ResultFiles.clear();
217
218  // Remove any user specified output.  Claim any unclaimed arguments, so as
219  // to avoid emitting warnings about unused args.
220  if (TranslatedArgs->hasArg(options::OPT_o))
221    TranslatedArgs->eraseArg(options::OPT_o);
222  TranslatedArgs->ClaimAllArgs();
223
224  // Redirect stdout/stderr to /dev/null.
225  Redirects = new const llvm::sys::Path*[3]();
226  Redirects[1] = new const llvm::sys::Path();
227  Redirects[2] = new const llvm::sys::Path();
228}
229