driver.cpp revision c93dc7889644293e318e19d82830ea2acc45b678
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/ArrayRef.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/OwningPtr.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/TargetRegistry.h"
38#include "llvm/Support/TargetSelect.h"
39#include "llvm/Support/system_error.h"
40#include <cctype>
41using namespace clang;
42using namespace clang::driver;
43
44llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
45  if (!CanonicalPrefixes)
46    return llvm::sys::Path(Argv0);
47
48  // This just needs to be some symbol in the binary; C++ doesn't
49  // allow taking the address of ::main however.
50  void *P = (void*) (intptr_t) GetExecutablePath;
51  return llvm::sys::Path::GetMainExecutable(Argv0, P);
52}
53
54static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
55                                   StringRef S) {
56  return SavedStrings.insert(S).first->c_str();
57}
58
59/// ApplyQAOverride - Apply a list of edits to the input argument lists.
60///
61/// The input string is a space separate list of edits to perform,
62/// they are applied in order to the input argument lists. Edits
63/// should be one of the following forms:
64///
65///  '#': Silence information about the changes to the command line arguments.
66///
67///  '^': Add FOO as a new argument at the beginning of the command line.
68///
69///  '+': Add FOO as a new argument at the end of the command line.
70///
71///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
72///  line.
73///
74///  'xOPTION': Removes all instances of the literal argument OPTION.
75///
76///  'XOPTION': Removes all instances of the literal argument OPTION,
77///  and the following argument.
78///
79///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
80///  at the end of the command line.
81///
82/// \param OS - The stream to write edit information to.
83/// \param Args - The vector of command line arguments.
84/// \param Edit - The override command to perform.
85/// \param SavedStrings - Set to use for storing string representations.
86static void ApplyOneQAOverride(raw_ostream &OS,
87                               SmallVectorImpl<const char*> &Args,
88                               StringRef Edit,
89                               std::set<std::string> &SavedStrings) {
90  // This does not need to be efficient.
91
92  if (Edit[0] == '^') {
93    const char *Str =
94      SaveStringInSet(SavedStrings, Edit.substr(1));
95    OS << "### Adding argument " << Str << " at beginning\n";
96    Args.insert(Args.begin() + 1, Str);
97  } else if (Edit[0] == '+') {
98    const char *Str =
99      SaveStringInSet(SavedStrings, Edit.substr(1));
100    OS << "### Adding argument " << Str << " at end\n";
101    Args.push_back(Str);
102  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
103             Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
104    StringRef MatchPattern = Edit.substr(2).split('/').first;
105    StringRef ReplPattern = Edit.substr(2).split('/').second;
106    ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
107
108    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
109      std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
110
111      if (Repl != Args[i]) {
112        OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
113        Args[i] = SaveStringInSet(SavedStrings, Repl);
114      }
115    }
116  } else if (Edit[0] == 'x' || Edit[0] == 'X') {
117    std::string Option = Edit.substr(1, std::string::npos);
118    for (unsigned i = 1; i < Args.size();) {
119      if (Option == Args[i]) {
120        OS << "### Deleting argument " << Args[i] << '\n';
121        Args.erase(Args.begin() + i);
122        if (Edit[0] == 'X') {
123          if (i < Args.size()) {
124            OS << "### Deleting argument " << Args[i] << '\n';
125            Args.erase(Args.begin() + i);
126          } else
127            OS << "### Invalid X edit, end of command line!\n";
128        }
129      } else
130        ++i;
131    }
132  } else if (Edit[0] == 'O') {
133    for (unsigned i = 1; i < Args.size();) {
134      const char *A = Args[i];
135      if (A[0] == '-' && A[1] == 'O' &&
136          (A[2] == '\0' ||
137           (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
138                             ('0' <= A[2] && A[2] <= '9'))))) {
139        OS << "### Deleting argument " << Args[i] << '\n';
140        Args.erase(Args.begin() + i);
141      } else
142        ++i;
143    }
144    OS << "### Adding argument " << Edit << " at end\n";
145    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
146  } else {
147    OS << "### Unrecognized edit: " << Edit << "\n";
148  }
149}
150
151/// ApplyQAOverride - Apply a comma separate list of edits to the
152/// input argument lists. See ApplyOneQAOverride.
153static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
154                            const char *OverrideStr,
155                            std::set<std::string> &SavedStrings) {
156  raw_ostream *OS = &llvm::errs();
157
158  if (OverrideStr[0] == '#') {
159    ++OverrideStr;
160    OS = &llvm::nulls();
161  }
162
163  *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
164
165  // This does not need to be efficient.
166
167  const char *S = OverrideStr;
168  while (*S) {
169    const char *End = ::strchr(S, ' ');
170    if (!End)
171      End = S + strlen(S);
172    if (End != S)
173      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
174    S = End;
175    if (*S != '\0')
176      ++S;
177  }
178}
179
180extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
181                    const char *Argv0, void *MainAddr);
182extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
183                      const char *Argv0, void *MainAddr);
184
185static void ExpandArgsFromBuf(const char *Arg,
186                              SmallVectorImpl<const char*> &ArgVector,
187                              std::set<std::string> &SavedStrings) {
188  const char *FName = Arg + 1;
189  OwningPtr<llvm::MemoryBuffer> MemBuf;
190  if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
191    ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
192    return;
193  }
194
195  const char *Buf = MemBuf->getBufferStart();
196  char InQuote = ' ';
197  std::string CurArg;
198
199  for (const char *P = Buf; ; ++P) {
200    if (*P == '\0' || (isspace(*P) && InQuote == ' ')) {
201      if (!CurArg.empty()) {
202
203        if (CurArg[0] != '@') {
204          ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
205        } else {
206          ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
207        }
208
209        CurArg = "";
210      }
211      if (*P == '\0')
212        break;
213      else
214        continue;
215    }
216
217    if (isspace(*P)) {
218      if (InQuote != ' ')
219        CurArg.push_back(*P);
220      continue;
221    }
222
223    if (*P == '"' || *P == '\'') {
224      if (InQuote == *P)
225        InQuote = ' ';
226      else if (InQuote == ' ')
227        InQuote = *P;
228      else
229        CurArg.push_back(*P);
230      continue;
231    }
232
233    if (*P == '\\') {
234      ++P;
235      if (*P != '\0')
236        CurArg.push_back(*P);
237      continue;
238    }
239    CurArg.push_back(*P);
240  }
241}
242
243static void ExpandArgv(int argc, const char **argv,
244                       SmallVectorImpl<const char*> &ArgVector,
245                       std::set<std::string> &SavedStrings) {
246  for (int i = 0; i < argc; ++i) {
247    const char *Arg = argv[i];
248    if (Arg[0] != '@') {
249      ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
250      continue;
251    }
252
253    ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
254  }
255}
256
257static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
258                          std::set<std::string> &SavedStrings,
259                          Driver &TheDriver)
260{
261  // Try to infer frontend type and default target from the program name.
262
263  // suffixes[] contains the list of known driver suffixes.
264  // Suffixes are compared against the program name in order.
265  // If there is a match, the frontend type is updated as necessary (CPP/C++).
266  // If there is no match, a second round is done after stripping the last
267  // hyphen and everything following it. This allows using something like
268  // "clang++-2.9".
269
270  // If there is a match in either the first or second round,
271  // the function tries to identify a target as prefix. E.g.
272  // "x86_64-linux-clang" as interpreted as suffix "clang" with
273  // target prefix "x86_64-linux". If such a target prefix is found,
274  // is gets added via -target as implicit first argument.
275  static const struct {
276    const char *Suffix;
277    bool IsCXX;
278    bool IsCPP;
279  } suffixes [] = {
280    { "clang", false, false },
281    { "clang++", true, false },
282    { "clang-c++", true, false },
283    { "clang-cc", false, false },
284    { "clang-cpp", false, true },
285    { "clang-g++", true, false },
286    { "clang-gcc", false, false },
287    { "cc", false, false },
288    { "cpp", false, true },
289    { "++", true, false },
290  };
291  std::string ProgName(llvm::sys::path::stem(ArgVector[0]));
292  StringRef ProgNameRef(ProgName);
293  StringRef Prefix;
294
295  for (int Components = 2; Components; --Components) {
296    bool FoundMatch = false;
297    size_t i;
298
299    for (i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
300      if (ProgNameRef.endswith(suffixes[i].Suffix)) {
301        FoundMatch = true;
302        if (suffixes[i].IsCXX)
303          TheDriver.CCCIsCXX = true;
304        if (suffixes[i].IsCPP)
305          TheDriver.CCCIsCPP = true;
306        break;
307      }
308    }
309
310    if (FoundMatch) {
311      StringRef::size_type LastComponent = ProgNameRef.rfind('-',
312        ProgNameRef.size() - strlen(suffixes[i].Suffix));
313      if (LastComponent != StringRef::npos)
314        Prefix = ProgNameRef.slice(0, LastComponent);
315      break;
316    }
317
318    StringRef::size_type LastComponent = ProgNameRef.rfind('-');
319    if (LastComponent == StringRef::npos)
320      break;
321    ProgNameRef = ProgNameRef.slice(0, LastComponent);
322  }
323
324  if (Prefix.empty())
325    return;
326
327  std::string IgnoredError;
328  if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
329    SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
330    if (it != ArgVector.end())
331      ++it;
332    ArgVector.insert(it, SaveStringInSet(SavedStrings, Prefix));
333    ArgVector.insert(it,
334      SaveStringInSet(SavedStrings, std::string("-target")));
335  }
336}
337
338int main(int argc_, const char **argv_) {
339  llvm::sys::PrintStackTraceOnErrorSignal();
340  llvm::PrettyStackTraceProgram X(argc_, argv_);
341
342  std::set<std::string> SavedStrings;
343  SmallVector<const char*, 256> argv;
344
345  ExpandArgv(argc_, argv_, argv, SavedStrings);
346
347  // Handle -cc1 integrated tools.
348  if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1")) {
349    StringRef Tool = argv[1] + 4;
350
351    if (Tool == "")
352      return cc1_main(argv.data()+2, argv.data()+argv.size(), argv[0],
353                      (void*) (intptr_t) GetExecutablePath);
354    if (Tool == "as")
355      return cc1as_main(argv.data()+2, argv.data()+argv.size(), argv[0],
356                      (void*) (intptr_t) GetExecutablePath);
357
358    // Reject unknown tools.
359    llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
360    return 1;
361  }
362
363  bool CanonicalPrefixes = true;
364  for (int i = 1, size = argv.size(); i < size; ++i) {
365    if (StringRef(argv[i]) == "-no-canonical-prefixes") {
366      CanonicalPrefixes = false;
367      break;
368    }
369  }
370
371  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);
372
373  TextDiagnosticPrinter *DiagClient
374    = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
375  DiagClient->setPrefix(llvm::sys::path::stem(Path.str()));
376  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
377  DiagnosticsEngine Diags(DiagID, DiagClient);
378
379#ifdef CLANG_IS_PRODUCTION
380  const bool IsProduction = true;
381#else
382  const bool IsProduction = false;
383#endif
384  Driver TheDriver(Path.str(), llvm::sys::getDefaultTargetTriple(),
385                   "a.out", IsProduction, Diags);
386
387  // Attempt to find the original path used to invoke the driver, to determine
388  // the installed path. We do this manually, because we want to support that
389  // path being a symlink.
390  {
391    SmallString<128> InstalledPath(argv[0]);
392
393    // Do a PATH lookup, if there are no directory components.
394    if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
395      llvm::sys::Path Tmp = llvm::sys::Program::FindProgramByName(
396        llvm::sys::path::filename(InstalledPath.str()));
397      if (!Tmp.empty())
398        InstalledPath = Tmp.str();
399    }
400    llvm::sys::fs::make_absolute(InstalledPath);
401    InstalledPath = llvm::sys::path::parent_path(InstalledPath);
402    bool exists;
403    if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
404      TheDriver.setInstalledDir(InstalledPath);
405  }
406
407  llvm::InitializeAllTargets();
408  ParseProgName(argv, SavedStrings, TheDriver);
409
410  // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
411  TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
412  if (TheDriver.CCPrintOptions)
413    TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
414
415  // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
416  TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
417  if (TheDriver.CCPrintHeaders)
418    TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
419
420  // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
421  TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
422  if (TheDriver.CCLogDiagnostics)
423    TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
424
425  // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
426  // command line behind the scenes.
427  if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
428    // FIXME: Driver shouldn't take extra initial argument.
429    ApplyQAOverride(argv, OverrideStr, SavedStrings);
430  } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
431    // FIXME: Driver shouldn't take extra initial argument.
432    std::vector<const char*> ExtraArgs;
433
434    for (;;) {
435      const char *Next = strchr(Cur, ',');
436
437      if (Next) {
438        ExtraArgs.push_back(SaveStringInSet(SavedStrings,
439                                            std::string(Cur, Next)));
440        Cur = Next + 1;
441      } else {
442        if (*Cur != '\0')
443          ExtraArgs.push_back(SaveStringInSet(SavedStrings, Cur));
444        break;
445      }
446    }
447
448    argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
449  }
450
451  OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
452  int Res = 0;
453  const Command *FailingCommand = 0;
454  if (C.get())
455    Res = TheDriver.ExecuteCompilation(*C, FailingCommand);
456
457  // If result status is < 0, then the driver command signalled an error.
458  // In this case, generate additional diagnostic information if possible.
459  if (Res < 0)
460    TheDriver.generateCompilationDiagnostics(*C, FailingCommand);
461
462  // If any timers were active but haven't been destroyed yet, print their
463  // results now.  This happens in -disable-free mode.
464  llvm::TimerGroup::printAll(llvm::errs());
465
466  llvm::llvm_shutdown();
467
468  return Res;
469}
470