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