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