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