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