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