driver.cpp revision 322c29fefe7fa33f03273136eb5f8b7f5b4df7c0
1//===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
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// This is the entry point to the clang driver; it is a thin wrapper
11// for functionality in the Driver clang library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/Option.h"
18#include "clang/Frontend/DiagnosticOptions.h"
19#include "clang/Frontend/TextDiagnosticPrinter.h"
20
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/Config/config.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/ManagedStatic.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/PrettyStackTrace.h"
30#include "llvm/Support/Regex.h"
31#include "llvm/Support/Timer.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/Host.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/Program.h"
36#include "llvm/Support/Signals.h"
37#include "llvm/Support/system_error.h"
38#include <cctype>
39using namespace clang;
40using namespace clang::driver;
41
42llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
43  if (!CanonicalPrefixes)
44    return llvm::sys::Path(Argv0);
45
46  // This just needs to be some symbol in the binary; C++ doesn't
47  // allow taking the address of ::main however.
48  void *P = (void*) (intptr_t) GetExecutablePath;
49  return llvm::sys::Path::GetMainExecutable(Argv0, P);
50}
51
52static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
53                                   llvm::StringRef S) {
54  return SavedStrings.insert(S).first->c_str();
55}
56
57/// ApplyQAOverride - Apply a list of edits to the input argument lists.
58///
59/// The input string is a space separate list of edits to perform,
60/// they are applied in order to the input argument lists. Edits
61/// should be one of the following forms:
62///
63///  '#': Silence information about the changes to the command line arguments.
64///
65///  '^': Add FOO as a new argument at the beginning of the command line.
66///
67///  '+': Add FOO as a new argument at the end of the command line.
68///
69///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
70///  line.
71///
72///  'xOPTION': Removes all instances of the literal argument OPTION.
73///
74///  'XOPTION': Removes all instances of the literal argument OPTION,
75///  and the following argument.
76///
77///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
78///  at the end of the command line.
79///
80/// \param OS - The stream to write edit information to.
81/// \param Args - The vector of command line arguments.
82/// \param Edit - The override command to perform.
83/// \param SavedStrings - Set to use for storing string representations.
84static void ApplyOneQAOverride(llvm::raw_ostream &OS,
85                               llvm::SmallVectorImpl<const char*> &Args,
86                               llvm::StringRef Edit,
87                               std::set<std::string> &SavedStrings) {
88  // This does not need to be efficient.
89
90  if (Edit[0] == '^') {
91    const char *Str =
92      SaveStringInSet(SavedStrings, Edit.substr(1));
93    OS << "### Adding argument " << Str << " at beginning\n";
94    Args.insert(Args.begin() + 1, Str);
95  } else if (Edit[0] == '+') {
96    const char *Str =
97      SaveStringInSet(SavedStrings, Edit.substr(1));
98    OS << "### Adding argument " << Str << " at end\n";
99    Args.push_back(Str);
100  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
101             Edit.slice(2, Edit.size()-1).find('/') != llvm::StringRef::npos) {
102    llvm::StringRef MatchPattern = Edit.substr(2).split('/').first;
103    llvm::StringRef ReplPattern = Edit.substr(2).split('/').second;
104    ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
105
106    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
107      std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
108
109      if (Repl != Args[i]) {
110        OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
111        Args[i] = SaveStringInSet(SavedStrings, Repl);
112      }
113    }
114  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
115    std::string Option = Edit.substr(1, std::string::npos);
116    for (unsigned i = 1; i < Args.size();) {
117      if (Option == Args[i]) {
118        OS << "### Deleting argument " << Args[i] << '\n';
119        Args.erase(Args.begin() + i);
120        if (Edit[0] == 'X') {
121          if (i < Args.size()) {
122            OS << "### Deleting argument " << Args[i] << '\n';
123            Args.erase(Args.begin() + i);
124          } else
125            OS << "### Invalid X edit, end of command line!\n";
126        }
127      } else
128        ++i;
129    }
130  } else if (Edit[0] == 'O') {
131    for (unsigned i = 1; i < Args.size();) {
132      const char *A = Args[i];
133      if (A[0] == '-' && A[1] == 'O' &&
134          (A[2] == '\0' ||
135           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
136                             ('0' <= A[2] && A[2] <= '9'))))) {
137        OS << "### Deleting argument " << Args[i] << '\n';
138        Args.erase(Args.begin() + i);
139      } else
140        ++i;
141    }
142    OS << "### Adding argument " << Edit << " at end\n";
143    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
144  } else {
145    OS << "### Unrecognized edit: " << Edit << "\n";
146  }
147}
148
149/// ApplyQAOverride - Apply a comma separate list of edits to the
150/// input argument lists. See ApplyOneQAOverride.
151static void ApplyQAOverride(llvm::SmallVectorImpl<const char*> &Args,
152                            const char *OverrideStr,
153                            std::set<std::string> &SavedStrings) {
154  llvm::raw_ostream *OS = &llvm::errs();
155
156  if (OverrideStr[0] == '#') {
157    ++OverrideStr;
158    OS = &llvm::nulls();
159  }
160
161  *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
162
163  // This does not need to be efficient.
164
165  const char *S = OverrideStr;
166  while (*S) {
167    const char *End = ::strchr(S, ' ');
168    if (!End)
169      End = S + strlen(S);
170    if (End != S)
171      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
172    S = End;
173    if (*S != '\0')
174      ++S;
175  }
176}
177
178extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
179                    const char *Argv0, void *MainAddr);
180extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
181                      const char *Argv0, void *MainAddr);
182
183static void ExpandArgsFromBuf(const char *Arg,
184                              llvm::SmallVectorImpl<const char*> &ArgVector,
185                              std::set<std::string> &SavedStrings) {
186  const char *FName = Arg + 1;
187  llvm::OwningPtr<llvm::MemoryBuffer> MemBuf;
188  if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
189    ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
190    return;
191  }
192
193  const char *Buf = MemBuf->getBufferStart();
194  char InQuote = ' ';
195  std::string CurArg;
196
197  for (const char *P = Buf; ; ++P) {
198    if (*P == '\0' || (isspace(*P) && InQuote == ' ')) {
199      if (!CurArg.empty()) {
200
201        if (CurArg[0] != '@') {
202          ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
203        } else {
204          ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
205        }
206
207        CurArg = "";
208      }
209      if (*P == '\0')
210        break;
211      else
212        continue;
213    }
214
215    if (isspace(*P)) {
216      if (InQuote != ' ')
217        CurArg.push_back(*P);
218      continue;
219    }
220
221    if (*P == '"' || *P == '\'') {
222      if (InQuote == *P)
223        InQuote = ' ';
224      else if (InQuote == ' ')
225        InQuote = *P;
226      else
227        CurArg.push_back(*P);
228      continue;
229    }
230
231    if (*P == '\\') {
232      ++P;
233      if (*P != '\0')
234        CurArg.push_back(*P);
235      continue;
236    }
237    CurArg.push_back(*P);
238  }
239}
240
241static void ExpandArgv(int argc, const char **argv,
242                       llvm::SmallVectorImpl<const char*> &ArgVector,
243                       std::set<std::string> &SavedStrings) {
244  for (int i = 0; i < argc; ++i) {
245    const char *Arg = argv[i];
246    if (Arg[0] != '@') {
247      ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
248      continue;
249    }
250
251    ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
252  }
253}
254
255int main(int argc_, const char **argv_) {
256  llvm::sys::PrintStackTraceOnErrorSignal();
257  llvm::PrettyStackTraceProgram X(argc_, argv_);
258
259  std::set<std::string> SavedStrings;
260  llvm::SmallVector<const char*, 256> argv;
261
262  ExpandArgv(argc_, argv_, argv, SavedStrings);
263
264  // Handle -cc1 integrated tools.
265  if (argv.size() > 1 && llvm::StringRef(argv[1]).startswith("-cc1")) {
266    llvm::StringRef Tool = argv[1] + 4;
267
268    if (Tool == "")
269      return cc1_main(argv.data()+2, argv.data()+argv.size(), argv[0],
270                      (void*) (intptr_t) GetExecutablePath);
271    if (Tool == "as")
272      return cc1as_main(argv.data()+2, argv.data()+argv.size(), argv[0],
273                      (void*) (intptr_t) GetExecutablePath);
274
275    // Reject unknown tools.
276    llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
277    return 1;
278  }
279
280  bool CanonicalPrefixes = true;
281  for (int i = 1, size = argv.size(); i < size; ++i) {
282    if (llvm::StringRef(argv[i]) == "-no-canonical-prefixes") {
283      CanonicalPrefixes = false;
284      break;
285    }
286  }
287
288  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);
289
290  TextDiagnosticPrinter *DiagClient
291    = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
292  DiagClient->setPrefix(llvm::sys::path::stem(Path.str()));
293  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
294  Diagnostic Diags(DiagID, DiagClient);
295
296#ifdef CLANG_IS_PRODUCTION
297  const bool IsProduction = true;
298#  ifdef CLANGXX_IS_PRODUCTION
299  const bool CXXIsProduction = true;
300#  else
301  const bool CXXIsProduction = false;
302#  endif
303#else
304  const bool IsProduction = false;
305  const bool CXXIsProduction = false;
306#endif
307  Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
308                   "a.out", IsProduction, CXXIsProduction,
309                   Diags);
310
311  // Attempt to find the original path used to invoke the driver, to determine
312  // the installed path. We do this manually, because we want to support that
313  // path being a symlink.
314  {
315    llvm::SmallString<128> InstalledPath(argv[0]);
316
317    // Do a PATH lookup, if there are no directory components.
318    if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
319      llvm::sys::Path Tmp = llvm::sys::Program::FindProgramByName(
320        llvm::sys::path::filename(InstalledPath.str()));
321      if (!Tmp.empty())
322        InstalledPath = Tmp.str();
323    }
324    llvm::sys::fs::make_absolute(InstalledPath);
325    InstalledPath = llvm::sys::path::parent_path(InstalledPath);
326    bool exists;
327    if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
328      TheDriver.setInstalledDir(InstalledPath);
329  }
330
331  // Check for ".*++" or ".*++-[^-]*" to determine if we are a C++
332  // compiler. This matches things like "c++", "clang++", and "clang++-1.1".
333  //
334  // Note that we intentionally want to use argv[0] here, to support "clang++"
335  // being a symlink.
336  //
337  // We use *argv instead of argv[0] to work around a bogus g++ warning.
338  const char *progname = argv_[0];
339  std::string ProgName(llvm::sys::path::stem(progname));
340  if (llvm::StringRef(ProgName).endswith("++") ||
341      llvm::StringRef(ProgName).rsplit('-').first.endswith("++")) {
342    TheDriver.CCCIsCXX = true;
343  }
344
345  // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
346  TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
347  if (TheDriver.CCPrintOptions)
348    TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
349
350  // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
351  TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
352  if (TheDriver.CCPrintHeaders)
353    TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
354
355  // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
356  // command line behind the scenes.
357  if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
358    // FIXME: Driver shouldn't take extra initial argument.
359    ApplyQAOverride(argv, OverrideStr, SavedStrings);
360  } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
361    // FIXME: Driver shouldn't take extra initial argument.
362    std::vector<const char*> ExtraArgs;
363
364    for (;;) {
365      const char *Next = strchr(Cur, ',');
366
367      if (Next) {
368        ExtraArgs.push_back(SaveStringInSet(SavedStrings,
369                                            std::string(Cur, Next)));
370        Cur = Next + 1;
371      } else {
372        if (*Cur != '\0')
373          ExtraArgs.push_back(SaveStringInSet(SavedStrings, Cur));
374        break;
375      }
376    }
377
378    argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
379  }
380
381  llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv.size(),
382                                                            &argv[0]));
383  int Res = 0;
384  if (C.get())
385    Res = TheDriver.ExecuteCompilation(*C);
386
387  // If any timers were active but haven't been destroyed yet, print their
388  // results now.  This happens in -disable-free mode.
389  llvm::TimerGroup::printAll(llvm::errs());
390
391  llvm::llvm_shutdown();
392
393  return Res;
394}
395