1 //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the entry point to the clang driver; it is a thin wrapper
11 // for functionality in the Driver clang library.
13 //===----------------------------------------------------------------------===//
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"
52 #include <system_error>
53 using namespace clang;
54 using namespace clang::driver;
55 using namespace llvm::opt;
57 std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
58 if (!CanonicalPrefixes)
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);
67 static const char *GetStableCStr(std::set<std::string> &SavedStrings,
69 return SavedStrings.insert(S).first->c_str();
72 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
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:
78 /// '#': Silence information about the changes to the command line arguments.
80 /// '^': Add FOO as a new argument at the beginning of the command line.
82 /// '+': Add FOO as a new argument at the end of the command line.
84 /// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
87 /// 'xOPTION': Removes all instances of the literal argument OPTION.
89 /// 'XOPTION': Removes all instances of the literal argument OPTION,
90 /// and the following argument.
92 /// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
93 /// at the end of the command line.
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,
102 std::set<std::string> &SavedStrings) {
103 // This does not need to be efficient.
105 if (Edit[0] == '^') {
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] == '+') {
112 GetStableCStr(SavedStrings, Edit.substr(1));
113 OS << "### Adding argument " << Str << " at end\n";
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);
121 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
122 // Ignore end-of-line response file markers
123 if (Args[i] == nullptr)
125 std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
127 if (Repl != Args[i]) {
128 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
129 Args[i] = GetStableCStr(SavedStrings, Repl);
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);
143 OS << "### Invalid X edit, end of command line!\n";
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
154 if (A[0] == '-' && A[1] == 'O' &&
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);
163 OS << "### Adding argument " << Edit << " at end\n";
164 Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
166 OS << "### Unrecognized edit: " << Edit << "\n";
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();
177 if (OverrideStr[0] == '#') {
182 *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
184 // This does not need to be efficient.
186 const char *S = OverrideStr;
188 const char *End = ::strchr(S, ' ');
192 ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
199 extern int cc1_main(ArrayRef<const char *> Argv, const char *Argv0,
201 extern int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0,
204 struct DriverSuffix {
206 const char *ModeFlag;
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[] = {
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"},
223 {"cpp", "--driver-mode=cpp"},
224 {"cl", "--driver-mode=cl"},
225 {"++", "--driver-mode=g++"},
228 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
229 if (ProgName.endswith(DriverSuffixes[i].Suffix))
230 return &DriverSuffixes[i];
234 static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
235 std::set<std::string> &SavedStrings) {
236 // Try to infer frontend type and default target from the program name by
237 // comparing it against DriverSuffixes in order.
239 // If there is a match, the function tries to identify a target as prefix.
240 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
241 // prefix "x86_64-linux". If such a target prefix is found, is gets added via
242 // -target as implicit first argument.
244 std::string ProgName =llvm::sys::path::stem(ArgVector[0]);
246 // Transform to lowercase for case insensitive file systems.
247 ProgName = StringRef(ProgName).lower();
250 StringRef ProgNameRef = ProgName;
251 const DriverSuffix *DS = FindDriverSuffix(ProgNameRef);
254 // Try again after stripping any trailing version number:
255 // clang++3.5 -> clang++
256 ProgNameRef = ProgNameRef.rtrim("0123456789.");
257 DS = FindDriverSuffix(ProgNameRef);
261 // Try again after stripping trailing -component.
262 // clang++-tot -> clang++
263 ProgNameRef = ProgNameRef.slice(0, ProgNameRef.rfind('-'));
264 DS = FindDriverSuffix(ProgNameRef);
268 if (const char *Flag = DS->ModeFlag) {
269 // Add Flag to the arguments.
270 auto it = ArgVector.begin();
271 if (it != ArgVector.end())
273 ArgVector.insert(it, Flag);
276 StringRef::size_type LastComponent = ProgNameRef.rfind(
277 '-', ProgNameRef.size() - strlen(DS->Suffix));
278 if (LastComponent == StringRef::npos)
281 // Infer target from the prefix.
282 StringRef Prefix = ProgNameRef.slice(0, LastComponent);
283 std::string IgnoredError;
284 if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
285 auto it = ArgVector.begin();
286 if (it != ArgVector.end())
288 const char *arr[] = { "-target", GetStableCStr(SavedStrings, Prefix) };
289 ArgVector.insert(it, std::begin(arr), std::end(arr));
294 static void SetBackdoorDriverOutputsFromEnvVars(Driver &TheDriver) {
295 // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
296 TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
297 if (TheDriver.CCPrintOptions)
298 TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
300 // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
301 TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
302 if (TheDriver.CCPrintHeaders)
303 TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
305 // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
306 TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
307 if (TheDriver.CCLogDiagnostics)
308 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
311 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
312 const std::string &Path) {
313 // If the clang binary happens to be named cl.exe for compatibility reasons,
314 // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
315 StringRef ExeBasename(llvm::sys::path::filename(Path));
316 if (ExeBasename.equals_lower("cl.exe"))
317 ExeBasename = "clang-cl.exe";
318 DiagClient->setPrefix(ExeBasename);
321 // This lets us create the DiagnosticsEngine with a properly-filled-out
322 // DiagnosticOptions instance.
323 static DiagnosticOptions *
324 CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
325 auto *DiagOpts = new DiagnosticOptions;
326 std::unique_ptr<OptTable> Opts(createDriverOptTable());
327 unsigned MissingArgIndex, MissingArgCount;
329 Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
330 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
331 // Any errors that would be diagnosed here will also be diagnosed later,
332 // when the DiagnosticsEngine actually exists.
333 (void)ParseDiagnosticArgs(*DiagOpts, Args);
337 static void SetInstallDir(SmallVectorImpl<const char *> &argv,
339 // Attempt to find the original path used to invoke the driver, to determine
340 // the installed path. We do this manually, because we want to support that
341 // path being a symlink.
342 SmallString<128> InstalledPath(argv[0]);
344 // Do a PATH lookup, if there are no directory components.
345 if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
346 if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
347 llvm::sys::path::filename(InstalledPath.str())))
348 InstalledPath = *Tmp;
349 llvm::sys::fs::make_absolute(InstalledPath);
350 InstalledPath = llvm::sys::path::parent_path(InstalledPath);
351 if (llvm::sys::fs::exists(InstalledPath.c_str()))
352 TheDriver.setInstalledDir(InstalledPath);
355 static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) {
356 void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
358 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
360 return cc1as_main(argv.slice(2), argv[0], GetExecutablePathVP);
362 // Reject unknown tools.
363 llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
367 int main(int argc_, const char **argv_) {
368 llvm::sys::PrintStackTraceOnErrorSignal();
369 llvm::PrettyStackTraceProgram X(argc_, argv_);
371 if (llvm::sys::Process::FixupStandardFileDescriptors())
374 SmallVector<const char *, 256> argv;
375 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
376 std::error_code EC = llvm::sys::Process::GetArgumentVector(
377 argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
379 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
383 llvm::BumpPtrAllocator A;
384 llvm::BumpPtrStringSaver Saver(A);
386 // Determines whether we want nullptr markers in argv to indicate response
387 // files end-of-lines. We only use this for the /LINK driver argument.
388 bool MarkEOLs = true;
389 if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1"))
391 llvm::cl::ExpandResponseFiles(Saver, llvm::cl::TokenizeGNUCommandLine, argv,
394 // Handle -cc1 integrated tools, even if -cc1 was expanded from a response
396 auto FirstArg = std::find_if(argv.begin() + 1, argv.end(),
397 [](const char *A) { return A != nullptr; });
398 if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) {
399 // If -cc1 came from a response file, remove the EOL sentinels.
401 auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
402 argv.resize(newEnd - argv.begin());
404 return ExecuteCC1Tool(argv, argv[1] + 4);
407 bool CanonicalPrefixes = true;
408 for (int i = 1, size = argv.size(); i < size; ++i) {
409 // Skip end-of-line response file markers
410 if (argv[i] == nullptr)
412 if (StringRef(argv[i]) == "-no-canonical-prefixes") {
413 CanonicalPrefixes = false;
418 std::set<std::string> SavedStrings;
419 // Handle CCC_OVERRIDE_OPTIONS, used for editing a command line behind the
421 if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) {
422 // FIXME: Driver shouldn't take extra initial argument.
423 ApplyQAOverride(argv, OverrideStr, SavedStrings);
426 std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes);
428 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
429 CreateAndPopulateDiagOpts(argv);
431 TextDiagnosticPrinter *DiagClient
432 = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
433 FixupDiagPrefixExeName(DiagClient, Path);
435 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
437 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
439 if (!DiagOpts->DiagnosticSerializationFile.empty()) {
440 auto SerializedConsumer =
441 clang::serialized_diags::create(DiagOpts->DiagnosticSerializationFile,
442 &*DiagOpts, /*MergeChildRecords=*/true);
443 Diags.setClient(new ChainedDiagnosticConsumer(
444 Diags.takeClient(), std::move(SerializedConsumer)));
447 ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
449 Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
450 SetInstallDir(argv, TheDriver);
452 llvm::InitializeAllTargets();
453 ParseProgName(argv, SavedStrings);
455 SetBackdoorDriverOutputsFromEnvVars(TheDriver);
457 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
459 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
461 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
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";
467 // Pretend that every command failed.
468 FailingCommands.clear();
469 for (const auto &J : C->getJobs())
470 if (const Command *C = dyn_cast<Command>(&J))
471 FailingCommands.push_back(std::make_pair(-1, C));
474 for (const auto &P : FailingCommands) {
475 int CommandRes = P.first;
476 const Command *FailingCommand = P.second;
480 // If result status is < 0, then the driver command signalled an error.
481 // If result status is 70, then the driver command reported a fatal error.
482 // On Windows, abort will return an exit code of 3. In these cases,
483 // generate additional diagnostic information if possible.
484 bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70;
486 DiagnoseCrash |= CommandRes == 3;
489 TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
494 Diags.getClient()->finish();
496 // If any timers were active but haven't been destroyed yet, print their
497 // results now. This happens in -disable-free mode.
498 llvm::TimerGroup::printAll(llvm::errs());
500 llvm::llvm_shutdown();
503 // Exit status should not be negative on Win32, unless abnormal termination.
504 // Once abnormal termiation was caught, negative status should not be
510 // If we have multiple failing commands, we return the result of the first