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