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 ///  '#': Silence information about the changes to the command line arguments.
83 ///
84 ///  '^': Add FOO as a new argument at the beginning of the command line.
85 ///
86 ///  '+': Add FOO as a new argument at the end of the command line.
87 ///
88 ///  's/XXX/YYY/': Replace the literal argument XXX by YYY in the
89 ///  command line.
90 ///
91 ///  'xOPTION': Removes all instances of the literal argument OPTION.
92 ///
93 ///  'XOPTION': Removes all instances of the literal argument OPTION,
94 ///  and the following argument.
95 ///
96 ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
97 ///  at the end of the command line.
98 ///
99 /// \param OS - The stream to write edit information to.
100 /// \param Args - The vector of command line arguments.
101 /// \param Edit - The override command to perform.
102 /// \param SavedStrings - Set to use for storing string representations.
103 void ApplyOneQAOverride(llvm::raw_ostream &OS,
104                         std::vector<const char*> &Args,
105                         const std::string &Edit,
106                         std::set<std::string> &SavedStrings) {
107   // This does not need to be efficient.
108 
109   if (Edit[0] == '^') {
110     const char *Str =
111       SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
112     OS << "### Adding argument " << Str << " at beginning\n";
113     Args.insert(Args.begin() + 1, Str);
114   } else if (Edit[0] == '+') {
115     const char *Str =
116       SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));
117     OS << "### Adding argument " << Str << " at end\n";
118     Args.push_back(Str);
119   } else if (Edit[0] == 'x' || Edit[0] == 'X') {
120     std::string Option = Edit.substr(1, std::string::npos);
121     for (unsigned i = 1; i < Args.size();) {
122       if (Option == Args[i]) {
123         OS << "### Deleting argument " << Args[i] << '\n';
124         Args.erase(Args.begin() + i);
125         if (Edit[0] == 'X') {
126           if (i < Args.size()) {
127             OS << "### Deleting argument " << Args[i] << '\n';
128             Args.erase(Args.begin() + i);
129           } else
130             OS << "### Invalid X edit, end of command line!\n";
131         }
132       } else
133         ++i;
134     }
135   } else if (Edit[0] == 'O') {
136     for (unsigned i = 1; i < Args.size();) {
137       const char *A = Args[i];
138       if (A[0] == '-' && A[1] == 'O' &&
139           (A[2] == '\0' ||
140            (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
141                              ('0' <= A[2] && A[2] <= '9'))))) {
142         OS << "### Deleting argument " << Args[i] << '\n';
143         Args.erase(Args.begin() + i);
144       } else
145         ++i;
146     }
147     OS << "### Adding argument " << Edit << " at end\n";
148     Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));
149   } else {
150     OS << "### Unrecognized edit: " << Edit << "\n";
151   }
152 }
153 
154 /// ApplyQAOverride - Apply a comma separate list of edits to the
155 /// input argument lists. See ApplyOneQAOverride.
156 void ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,
157                      std::set<std::string> &SavedStrings) {
158   llvm::raw_ostream *OS = &llvm::errs();
159 
160   if (OverrideStr[0] == '#') {
161     ++OverrideStr;
162     OS = &llvm::nulls();
163   }
164 
165   *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
166 
167   // This does not need to be efficient.
168 
169   const char *S = OverrideStr;
170   while (*S) {
171     const char *End = ::strchr(S, ' ');
172     if (!End)
173       End = S + strlen(S);
174     if (End != S)
175       ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
176     S = End;
177     if (*S != '\0')
178       ++S;
179   }
180 }
181 
182 int main(int argc, const char **argv) {
183   llvm::sys::PrintStackTraceOnErrorSignal();
184   llvm::PrettyStackTraceProgram X(argc, argv);
185 
186   llvm::sys::Path Path = GetExecutablePath(argv[0]);
187   DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());
188 
189   Diagnostic Diags(&DiagClient);
190 
191   Driver TheDriver(Path.getBasename().c_str(), Path.getDirname().c_str(),
192                    llvm::sys::getHostTriple().c_str(),
193                    "a.out", Diags);
194 
195   llvm::OwningPtr<Compilation> C;
196 
197   // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
198   // command line behind the scenes.
199   std::set<std::string> SavedStrings;
200   if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
201     // FIXME: Driver shouldn't take extra initial argument.
202     std::vector<const char*> StringPointers(argv, argv + argc);
203 
204     ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);
205 
206     C.reset(TheDriver.BuildCompilation(StringPointers.size(),
207                                        &StringPointers[0]));
208   } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
209     std::vector<const char*> StringPointers;
210 
211     // FIXME: Driver shouldn't take extra initial argument.
212     StringPointers.push_back(argv[0]);
213 
214     for (;;) {
215       const char *Next = strchr(Cur, ',');
216 
217       if (Next) {
218         StringPointers.push_back(SaveStringInSet(SavedStrings,
219                                                  std::string(Cur, Next)));
220         Cur = Next + 1;
221       } else {
222         if (*Cur != '\0')
223           StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));
224         break;
225       }
226     }
227 
228     StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);
229 
230     C.reset(TheDriver.BuildCompilation(StringPointers.size(),
231                                        &StringPointers[0]));
232   } else
233     C.reset(TheDriver.BuildCompilation(argc, argv));
234 
235   int Res = 0;
236   if (C.get())
237     Res = TheDriver.ExecuteCompilation(*C);
238 
239   llvm::llvm_shutdown();
240 
241   return Res;
242 }
243 
244