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/Driver/Options.h"
19 
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Host.h"
27 #include "llvm/System/Path.h"
28 #include "llvm/System/Signals.h"
29 using namespace clang;
30 using namespace clang::driver;
31 
32 class DriverDiagnosticPrinter : public DiagnosticClient {
33   std::string ProgName;
34   llvm::raw_ostream &OS;
35 
36 public:
37   DriverDiagnosticPrinter(const std::string _ProgName,
38                           llvm::raw_ostream &_OS)
39     : ProgName(_ProgName),
40       OS(_OS) {}
41 
42   virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
43                                 const DiagnosticInfo &Info);
44 };
45 
46 void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
47                                                const DiagnosticInfo &Info) {
48   OS << ProgName << ": ";
49 
50   switch (Level) {
51   case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
52   case Diagnostic::Note:    OS << "note: "; break;
53   case Diagnostic::Warning: OS << "warning: "; break;
54   case Diagnostic::Error:   OS << "error: "; break;
55   case Diagnostic::Fatal:   OS << "fatal error: "; break;
56   }
57 
58   llvm::SmallString<100> OutStr;
59   Info.FormatDiagnostic(OutStr);
60   OS.write(OutStr.begin(), OutStr.size());
61   OS << '\n';
62 }
63 
64 llvm::sys::Path GetExecutablePath(const char *Argv0) {
65   // This just needs to be some symbol in the binary; C++ doesn't
66   // allow taking the address of ::main however.
67   void *P = (void*) (intptr_t) GetExecutablePath;
68   return llvm::sys::Path::GetMainExecutable(Argv0, P);
69 }
70 
71 static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
72                                    const std::string &S) {
73   return SavedStrings.insert(S).first->c_str();
74 }
75 
76 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
77 ///
78 /// The input string is a space separate list of edits to perform,
79 /// they are applied in order to the input argument lists. Edits
80 /// should be one of the following forms:
81 ///
82 ///  '^': Add FOO as a new argument at the beginning of the command line.
83 ///
84 ///  '+': Add FOO as a new argument at the end of the command line.
85 ///
86 ///  's/XXX/YYY/': Replace the literal argument XXX by YYY in the
87 ///  command line.
88 ///
89 ///  'xOPTION': Removes all instances of the literal argument OPTION.
90 ///
91 ///  'XOPTION': Removes all instances of the literal argument OPTION,
92 ///  and the following argument.
93 ///
94 ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
95 ///  at the end of the command line.
96 void ApplyOneQAOverride(std::vector<const char*> &Args,
97                         const std::string &Edit,
98                         std::set<std::string> &SavedStrings) {
99   // This does not need to be efficient.
100 
101    if (Edit[0] == '^') {
102      const char *Str =
103        SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
104      llvm::errs() << "### Adding argument " << Str << " at beginning\n";
105      Args.insert(Args.begin() + 1, Str);
106    } else if (Edit[0] == '+') {
107      const char *Str =
108        SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
109      llvm::errs() << "### Adding argument " << Str << " at end\n";
110      Args.push_back(Str);
111    } else if (Edit[0] == 'x' || Edit[0] == 'X') {
112      std::string Option = Edit.substr(1, std::string::npos);
113      for (unsigned i = 1; i < Args.size();) {
114        if (Option == Args[i]) {
115          llvm::errs() << "### Deleting argument " << Args[i] << '\n';
116          Args.erase(Args.begin() + i);
117          if (Edit[0] == 'X') {
118            if (i < Args.size()) {
119              llvm::errs() << "### Deleting argument " << Args[i] << '\n';
120              Args.erase(Args.begin() + i);
121            } else
122              llvm::errs() << "### Invalid X edit, end of command line!\n";
123          }
124        } else
125          ++i;
126      }
127    } else if (Edit[0] == 'O') {
128      for (unsigned i = 1; i < Args.size();) {
129        const char *A = Args[i];
130        if (A[0] == '-' && A[1] == 'O' &&
131            (A[2] == '\0' ||
132             (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
133                               ('0' <= A[2] && A[2] <= '9'))))) {
134          llvm::errs() << "### Deleting argument " << Args[i] << '\n';
135          Args.erase(Args.begin() + i);
136        } else
137          ++i;
138      }
139      llvm::errs() << "### Adding argument " << Edit << " at end\n";
140      Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));
141    } else {
142      llvm::errs() << "### Unrecognized edit: " << Edit << "\n";
143    }
144 }
145 
146 /// ApplyQAOverride - Apply a comma separate list of edits to the
147 /// input argument lists. See ApplyOneQAOverride.
148 void ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,
149                      std::set<std::string> &SavedStrings) {
150   llvm::errs() << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
151 
152   // This does not need to be efficient.
153 
154   const char *S = OverrideStr;
155   while (*S) {
156     const char *End = ::strchr(S, ' ');
157     if (!End)
158       End = S + strlen(S);
159     if (End != S)
160       ApplyOneQAOverride(Args, std::string(S, End), SavedStrings);
161     S = End;
162     if (*S != '\0')
163       ++S;
164   }
165 }
166 
167 int main(int argc, const char **argv) {
168   llvm::sys::PrintStackTraceOnErrorSignal();
169   llvm::PrettyStackTraceProgram X(argc, argv);
170 
171   llvm::sys::Path Path = GetExecutablePath(argv[0]);
172   DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());
173 
174   Diagnostic Diags(&DiagClient);
175 
176   Driver TheDriver(Path.getBasename().c_str(), Path.getDirname().c_str(),
177                    llvm::sys::getHostTriple().c_str(),
178                    "a.out", Diags);
179 
180   llvm::OwningPtr<Compilation> C;
181 
182   // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
183   // command line behind the scenes.
184   std::set<std::string> SavedStrings;
185   if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
186     // FIXME: Driver shouldn't take extra initial argument.
187     std::vector<const char*> StringPointers(argv, argv + argc);
188 
189     ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);
190 
191     C.reset(TheDriver.BuildCompilation(StringPointers.size(),
192                                        &StringPointers[0]));
193   } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
194     std::vector<const char*> StringPointers;
195 
196     // FIXME: Driver shouldn't take extra initial argument.
197     StringPointers.push_back(argv[0]);
198 
199     for (;;) {
200       const char *Next = strchr(Cur, ',');
201 
202       if (Next) {
203         StringPointers.push_back(SaveStringInSet(SavedStrings,
204                                                  std::string(Cur, Next)));
205         Cur = Next + 1;
206       } else {
207         if (*Cur != '\0')
208           StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));
209         break;
210       }
211     }
212 
213     StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);
214 
215     C.reset(TheDriver.BuildCompilation(StringPointers.size(),
216                                        &StringPointers[0]));
217   } else
218     C.reset(TheDriver.BuildCompilation(argc, argv));
219 
220   int Res = 0;
221   if (C.get())
222     Res = TheDriver.ExecuteCompilation(*C);
223 
224   llvm::llvm_shutdown();
225 
226   return Res;
227 }
228 
229