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