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