1 //===--- CompileCommands.cpp ----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "CompileCommands.h" 10 #include "Config.h" 11 #include "support/Logger.h" 12 #include "clang/Driver/Options.h" 13 #include "clang/Frontend/CompilerInvocation.h" 14 #include "clang/Tooling/ArgumentsAdjusters.h" 15 #include "llvm/Option/Option.h" 16 #include "llvm/Support/Allocator.h" 17 #include "llvm/Support/Debug.h" 18 #include "llvm/Support/FileSystem.h" 19 #include "llvm/Support/FileUtilities.h" 20 #include "llvm/Support/MemoryBuffer.h" 21 #include "llvm/Support/Path.h" 22 #include "llvm/Support/Program.h" 23 24 namespace clang { 25 namespace clangd { 26 namespace { 27 28 // Query apple's `xcrun` launcher, which is the source of truth for "how should" 29 // clang be invoked on this system. 30 llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) { 31 auto Xcrun = llvm::sys::findProgramByName("xcrun"); 32 if (!Xcrun) { 33 log("Couldn't find xcrun. Hopefully you have a non-apple toolchain..."); 34 return llvm::None; 35 } 36 llvm::SmallString<64> OutFile; 37 llvm::sys::fs::createTemporaryFile("clangd-xcrun", "", OutFile); 38 llvm::FileRemover OutRemover(OutFile); 39 llvm::Optional<llvm::StringRef> Redirects[3] = { 40 /*stdin=*/{""}, /*stdout=*/{OutFile}, /*stderr=*/{""}}; 41 vlog("Invoking {0} to find clang installation", *Xcrun); 42 int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv, 43 /*Env=*/llvm::None, Redirects, 44 /*SecondsToWait=*/10); 45 if (Ret != 0) { 46 log("xcrun exists but failed with code {0}. " 47 "If you have a non-apple toolchain, this is OK. " 48 "Otherwise, try xcode-select --install.", 49 Ret); 50 return llvm::None; 51 } 52 53 auto Buf = llvm::MemoryBuffer::getFile(OutFile); 54 if (!Buf) { 55 log("Can't read xcrun output: {0}", Buf.getError().message()); 56 return llvm::None; 57 } 58 StringRef Path = Buf->get()->getBuffer().trim(); 59 if (Path.empty()) { 60 log("xcrun produced no output"); 61 return llvm::None; 62 } 63 return Path.str(); 64 } 65 66 // Resolve symlinks if possible. 67 std::string resolve(std::string Path) { 68 llvm::SmallString<128> Resolved; 69 if (llvm::sys::fs::real_path(Path, Resolved)) { 70 log("Failed to resolve possible symlink {0}", Path); 71 return Path; 72 } 73 return std::string(Resolved.str()); 74 } 75 76 // Get a plausible full `clang` path. 77 // This is used in the fallback compile command, or when the CDB returns a 78 // generic driver with no path. 79 std::string detectClangPath() { 80 // The driver and/or cc1 sometimes depend on the binary name to compute 81 // useful things like the standard library location. 82 // We need to emulate what clang on this system is likely to see. 83 // cc1 in particular looks at the "real path" of the running process, and 84 // so if /usr/bin/clang is a symlink, it sees the resolved path. 85 // clangd doesn't have that luxury, so we resolve symlinks ourselves. 86 87 // On Mac, `which clang` is /usr/bin/clang. It runs `xcrun clang`, which knows 88 // where the real clang is kept. We need to do the same thing, 89 // because cc1 (not the driver!) will find libc++ relative to argv[0]. 90 #ifdef __APPLE__ 91 if (auto MacClang = queryXcrun({"xcrun", "--find", "clang"})) 92 return resolve(std::move(*MacClang)); 93 #endif 94 // On other platforms, just look for compilers on the PATH. 95 for (const char *Name : {"clang", "gcc", "cc"}) 96 if (auto PathCC = llvm::sys::findProgramByName(Name)) 97 return resolve(std::move(*PathCC)); 98 // Fallback: a nonexistent 'clang' binary next to clangd. 99 static int StaticForMainAddr; 100 std::string ClangdExecutable = 101 llvm::sys::fs::getMainExecutable("clangd", (void *)&StaticForMainAddr); 102 SmallString<128> ClangPath; 103 ClangPath = llvm::sys::path::parent_path(ClangdExecutable); 104 llvm::sys::path::append(ClangPath, "clang"); 105 return std::string(ClangPath.str()); 106 } 107 108 // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang. 109 // The effect of this is to set -isysroot correctly. We do the same. 110 const llvm::Optional<std::string> detectSysroot() { 111 #ifndef __APPLE__ 112 return llvm::None; 113 #endif 114 115 // SDKROOT overridden in environment, respect it. Driver will set isysroot. 116 if (::getenv("SDKROOT")) 117 return llvm::None; 118 return queryXcrun({"xcrun", "--show-sdk-path"}); 119 return llvm::None; 120 } 121 122 std::string detectStandardResourceDir() { 123 static int StaticForMainAddr; // Just an address in this process. 124 return CompilerInvocation::GetResourcesPath("clangd", 125 (void *)&StaticForMainAddr); 126 } 127 128 // The path passed to argv[0] is important: 129 // - its parent directory is Driver::Dir, used for library discovery 130 // - its basename affects CLI parsing (clang-cl) and other settings 131 // Where possible it should be an absolute path with sensible directory, but 132 // with the original basename. 133 static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink, 134 llvm::Optional<std::string> ClangPath) { 135 auto SiblingOf = [&](llvm::StringRef AbsPath) { 136 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath); 137 llvm::sys::path::append(Result, llvm::sys::path::filename(Driver)); 138 return Result.str().str(); 139 }; 140 141 // First, eliminate relative paths. 142 std::string Storage; 143 if (!llvm::sys::path::is_absolute(Driver)) { 144 // If it's working-dir relative like bin/clang, we can't resolve it. 145 // FIXME: we could if we had the working directory here. 146 // Let's hope it's not a symlink. 147 if (llvm::any_of(Driver, 148 [](char C) { return llvm::sys::path::is_separator(C); })) 149 return Driver.str(); 150 // If the driver is a generic like "g++" with no path, add clang dir. 151 if (ClangPath && 152 (Driver == "clang" || Driver == "clang++" || Driver == "gcc" || 153 Driver == "g++" || Driver == "cc" || Driver == "c++")) { 154 return SiblingOf(*ClangPath); 155 } 156 // Otherwise try to look it up on PATH. This won't change basename. 157 auto Absolute = llvm::sys::findProgramByName(Driver); 158 if (Absolute && llvm::sys::path::is_absolute(*Absolute)) 159 Driver = Storage = std::move(*Absolute); 160 else if (ClangPath) // If we don't find it, use clang dir again. 161 return SiblingOf(*ClangPath); 162 else // Nothing to do: can't find the command and no detected dir. 163 return Driver.str(); 164 } 165 166 // Now we have an absolute path, but it may be a symlink. 167 assert(llvm::sys::path::is_absolute(Driver)); 168 if (FollowSymlink) { 169 llvm::SmallString<256> Resolved; 170 if (!llvm::sys::fs::real_path(Driver, Resolved)) 171 return SiblingOf(Resolved); 172 } 173 return Driver.str(); 174 } 175 176 } // namespace 177 178 CommandMangler CommandMangler::detect() { 179 CommandMangler Result; 180 Result.ClangPath = detectClangPath(); 181 Result.ResourceDir = detectStandardResourceDir(); 182 Result.Sysroot = detectSysroot(); 183 return Result; 184 } 185 186 CommandMangler CommandMangler::forTests() { 187 return CommandMangler(); 188 } 189 190 void CommandMangler::adjust(std::vector<std::string> &Cmd) const { 191 for (auto &Edit : Config::current().CompileFlags.Edits) 192 Edit(Cmd); 193 194 // Check whether the flag exists, either as -flag or -flag=* 195 auto Has = [&](llvm::StringRef Flag) { 196 for (llvm::StringRef Arg : Cmd) { 197 if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] == '=')) 198 return true; 199 } 200 return false; 201 }; 202 203 // clangd should not write files to disk, including dependency files 204 // requested on the command line. 205 Cmd = tooling::getClangStripDependencyFileAdjuster()(Cmd, ""); 206 // Strip plugin related command line arguments. Clangd does 207 // not support plugins currently. Therefore it breaks if 208 // compiler tries to load plugins. 209 Cmd = tooling::getStripPluginsAdjuster()(Cmd, ""); 210 Cmd = tooling::getClangSyntaxOnlyAdjuster()(Cmd, ""); 211 212 if (ResourceDir && !Has("-resource-dir")) 213 Cmd.push_back(("-resource-dir=" + *ResourceDir)); 214 215 // Don't set `-isysroot` if it is already set or if `--sysroot` is set. 216 // `--sysroot` is a superset of the `-isysroot` argument. 217 if (Sysroot && !Has("-isysroot") && !Has("--sysroot")) { 218 Cmd.push_back("-isysroot"); 219 Cmd.push_back(*Sysroot); 220 } 221 222 if (!Cmd.empty()) { 223 bool FollowSymlink = !Has("-no-canonical-prefixes"); 224 Cmd.front() = 225 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow) 226 .get(Cmd.front(), [&, this] { 227 return resolveDriver(Cmd.front(), FollowSymlink, ClangPath); 228 }); 229 } 230 } 231 232 CommandMangler::operator clang::tooling::ArgumentsAdjuster() && { 233 // ArgumentsAdjuster is a std::function and so must be copyable. 234 return [Mangler = std::make_shared<CommandMangler>(std::move(*this))]( 235 const std::vector<std::string> &Args, llvm::StringRef File) { 236 auto Result = Args; 237 Mangler->adjust(Result); 238 return Result; 239 }; 240 } 241 242 // ArgStripper implementation 243 namespace { 244 245 // Determine total number of args consumed by this option. 246 // Return answers for {Exact, Prefix} match. 0 means not allowed. 247 std::pair<unsigned, unsigned> getArgCount(const llvm::opt::Option &Opt) { 248 constexpr static unsigned Rest = 10000; // Should be all the rest! 249 // Reference is llvm::opt::Option::acceptInternal() 250 using llvm::opt::Option; 251 switch (Opt.getKind()) { 252 case Option::FlagClass: 253 return {1, 0}; 254 case Option::JoinedClass: 255 case Option::CommaJoinedClass: 256 return {1, 1}; 257 case Option::GroupClass: 258 case Option::InputClass: 259 case Option::UnknownClass: 260 case Option::ValuesClass: 261 return {1, 0}; 262 case Option::JoinedAndSeparateClass: 263 return {2, 2}; 264 case Option::SeparateClass: 265 return {2, 0}; 266 case Option::MultiArgClass: 267 return {1 + Opt.getNumArgs(), 0}; 268 case Option::JoinedOrSeparateClass: 269 return {2, 1}; 270 case Option::RemainingArgsClass: 271 return {Rest, 0}; 272 case Option::RemainingArgsJoinedClass: 273 return {Rest, Rest}; 274 } 275 llvm_unreachable("Unhandled option kind"); 276 } 277 278 // Flag-parsing mode, which affects which flags are available. 279 enum DriverMode : unsigned char { 280 DM_None = 0, 281 DM_GCC = 1, // Default mode e.g. when invoked as 'clang' 282 DM_CL = 2, // MS CL.exe compatible mode e.g. when invoked as 'clang-cl' 283 DM_CC1 = 4, // When invoked as 'clang -cc1' or after '-Xclang' 284 DM_All = 7 285 }; 286 287 // Examine args list to determine if we're in GCC, CL-compatible, or cc1 mode. 288 DriverMode getDriverMode(const std::vector<std::string> &Args) { 289 DriverMode Mode = DM_GCC; 290 llvm::StringRef Argv0 = Args.front(); 291 if (Argv0.endswith_lower(".exe")) 292 Argv0 = Argv0.drop_back(strlen(".exe")); 293 if (Argv0.endswith_lower("cl")) 294 Mode = DM_CL; 295 for (const llvm::StringRef Arg : Args) { 296 if (Arg == "--driver-mode=cl") { 297 Mode = DM_CL; 298 break; 299 } 300 if (Arg == "-cc1") { 301 Mode = DM_CC1; 302 break; 303 } 304 } 305 return Mode; 306 } 307 308 // Returns the set of DriverModes where an option may be used. 309 unsigned char getModes(const llvm::opt::Option &Opt) { 310 // Why is this so complicated?! 311 // Reference is clang::driver::Driver::getIncludeExcludeOptionFlagMasks() 312 unsigned char Result = DM_None; 313 if (Opt.hasFlag(driver::options::CC1Option)) 314 Result |= DM_CC1; 315 if (!Opt.hasFlag(driver::options::NoDriverOption)) { 316 if (Opt.hasFlag(driver::options::CLOption)) { 317 Result |= DM_CL; 318 } else { 319 Result |= DM_GCC; 320 if (Opt.hasFlag(driver::options::CoreOption)) { 321 Result |= DM_CL; 322 } 323 } 324 } 325 return Result; 326 } 327 328 } // namespace 329 330 llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) { 331 // All the hard work is done once in a static initializer. 332 // We compute a table containing strings to look for and #args to skip. 333 // e.g. "-x" => {-x 2 args, -x* 1 arg, --language 2 args, --language=* 1 arg} 334 using TableTy = 335 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>; 336 static TableTy *Table = [] { 337 auto &DriverTable = driver::getDriverOptTable(); 338 using DriverID = clang::driver::options::ID; 339 340 // Collect sets of aliases, so we can treat -foo and -foo= as synonyms. 341 // Conceptually a double-linked list: PrevAlias[I] -> I -> NextAlias[I]. 342 // If PrevAlias[I] is INVALID, then I is canonical. 343 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID}; 344 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID}; 345 auto AddAlias = [&](DriverID Self, DriverID T) { 346 if (NextAlias[T]) { 347 PrevAlias[NextAlias[T]] = Self; 348 NextAlias[Self] = NextAlias[T]; 349 } 350 PrevAlias[Self] = T; 351 NextAlias[T] = Self; 352 }; 353 // Also grab prefixes for each option, these are not fully exposed. 354 const char *const *Prefixes[DriverID::LastOption] = {nullptr}; 355 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE; 356 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 357 HELP, METAVAR, VALUES) \ 358 if (DriverID::OPT_##ALIAS != DriverID::OPT_INVALID && ALIASARGS == nullptr) \ 359 AddAlias(DriverID::OPT_##ID, DriverID::OPT_##ALIAS); \ 360 Prefixes[DriverID::OPT_##ID] = PREFIX; 361 #include "clang/Driver/Options.inc" 362 #undef OPTION 363 #undef PREFIX 364 365 auto Result = std::make_unique<TableTy>(); 366 // Iterate over distinct options (represented by the canonical alias). 367 // Every spelling of this option will get the same set of rules. 368 for (unsigned ID = 1 /*Skip INVALID */; ID < DriverID::LastOption; ++ID) { 369 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang) 370 continue; // Not canonical, or specially handled. 371 llvm::SmallVector<Rule> Rules; 372 // Iterate over each alias, to add rules for parsing it. 373 for (unsigned A = ID; A != DriverID::OPT_INVALID; A = NextAlias[A]) { 374 if (Prefixes[A] == nullptr) // option groups. 375 continue; 376 auto Opt = DriverTable.getOption(A); 377 // Exclude - and -foo pseudo-options. 378 if (Opt.getName().empty()) 379 continue; 380 auto Modes = getModes(Opt); 381 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt); 382 // Iterate over each spelling of the alias, e.g. -foo vs --foo. 383 for (auto *Prefix = Prefixes[A]; *Prefix != nullptr; ++Prefix) { 384 llvm::SmallString<64> Buf(*Prefix); 385 Buf.append(Opt.getName()); 386 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey(); 387 Rules.emplace_back(); 388 Rule &R = Rules.back(); 389 R.Text = Spelling; 390 R.Modes = Modes; 391 R.ExactArgs = ArgCount.first; 392 R.PrefixArgs = ArgCount.second; 393 // Concrete priority is the index into the option table. 394 // Effectively, earlier entries take priority over later ones. 395 assert(ID < std::numeric_limits<decltype(R.Priority)>::max() && 396 "Rules::Priority overflowed by options table"); 397 R.Priority = ID; 398 } 399 } 400 // Register the set of rules under each possible name. 401 for (const auto &R : Rules) 402 Result->find(R.Text)->second.append(Rules.begin(), Rules.end()); 403 } 404 #ifndef NDEBUG 405 // Dump the table and various measures of its size. 406 unsigned RuleCount = 0; 407 dlog("ArgStripper Option spelling table"); 408 for (const auto &Entry : *Result) { 409 dlog("{0}", Entry.first()); 410 RuleCount += Entry.second.size(); 411 for (const auto &R : Entry.second) 412 dlog(" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs, 413 int(R.Modes)); 414 } 415 dlog("Table spellings={0} rules={1} string-bytes={2}", Result->size(), 416 RuleCount, Result->getAllocator().getBytesAllocated()); 417 #endif 418 // The static table will never be destroyed. 419 return Result.release(); 420 }(); 421 422 auto It = Table->find(Arg); 423 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second; 424 } 425 426 void ArgStripper::strip(llvm::StringRef Arg) { 427 auto OptionRules = rulesFor(Arg); 428 if (OptionRules.empty()) { 429 // Not a recognized flag. Strip it literally. 430 Storage.emplace_back(Arg); 431 Rules.emplace_back(); 432 Rules.back().Text = Storage.back(); 433 Rules.back().ExactArgs = 1; 434 if (Rules.back().Text.consume_back("*")) 435 Rules.back().PrefixArgs = 1; 436 Rules.back().Modes = DM_All; 437 Rules.back().Priority = -1; // Max unsigned = lowest priority. 438 } else { 439 Rules.append(OptionRules.begin(), OptionRules.end()); 440 } 441 } 442 443 const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg, 444 unsigned Mode, 445 unsigned &ArgCount) const { 446 const ArgStripper::Rule *BestRule = nullptr; 447 for (const Rule &R : Rules) { 448 // Rule can fail to match if... 449 if (!(R.Modes & Mode)) 450 continue; // not applicable to current driver mode 451 if (BestRule && BestRule->Priority < R.Priority) 452 continue; // lower-priority than best candidate. 453 if (!Arg.startswith(R.Text)) 454 continue; // current arg doesn't match the prefix string 455 bool PrefixMatch = Arg.size() > R.Text.size(); 456 // Can rule apply as an exact/prefix match? 457 if (unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) { 458 BestRule = &R; 459 ArgCount = Count; 460 } 461 // Continue in case we find a higher-priority rule. 462 } 463 return BestRule; 464 } 465 466 void ArgStripper::process(std::vector<std::string> &Args) const { 467 if (Args.empty()) 468 return; 469 470 // We're parsing the args list in some mode (e.g. gcc-compatible) but may 471 // temporarily switch to another mode with the -Xclang flag. 472 DriverMode MainMode = getDriverMode(Args); 473 DriverMode CurrentMode = MainMode; 474 475 // Read and write heads for in-place deletion. 476 unsigned Read = 0, Write = 0; 477 bool WasXclang = false; 478 while (Read < Args.size()) { 479 unsigned ArgCount = 0; 480 if (matchingRule(Args[Read], CurrentMode, ArgCount)) { 481 // Delete it and its args. 482 if (WasXclang) { 483 assert(Write > 0); 484 --Write; // Drop previous -Xclang arg 485 CurrentMode = MainMode; 486 WasXclang = false; 487 } 488 // Advance to last arg. An arg may be foo or -Xclang foo. 489 for (unsigned I = 1; Read < Args.size() && I < ArgCount; ++I) { 490 ++Read; 491 if (Read < Args.size() && Args[Read] == "-Xclang") 492 ++Read; 493 } 494 } else { 495 // No match, just copy the arg through. 496 WasXclang = Args[Read] == "-Xclang"; 497 CurrentMode = WasXclang ? DM_CC1 : MainMode; 498 if (Write != Read) 499 Args[Write] = std::move(Args[Read]); 500 ++Write; 501 } 502 ++Read; 503 } 504 Args.resize(Write); 505 } 506 507 508 std::string printArgv(llvm::ArrayRef<llvm::StringRef> Args) { 509 std::string Buf; 510 llvm::raw_string_ostream OS(Buf); 511 bool Sep = false; 512 for (llvm::StringRef Arg : Args) { 513 if (Sep) 514 OS << ' '; 515 Sep = true; 516 if (llvm::all_of(Arg, llvm::isPrint) && 517 Arg.find_first_of(" \t\n\"\\") == llvm::StringRef::npos) { 518 OS << Arg; 519 continue; 520 } 521 OS << '"'; 522 OS.write_escaped(Arg, /*UseHexEscapes=*/true); 523 OS << '"'; 524 } 525 return std::move(OS.str()); 526 } 527 528 std::string printArgv(llvm::ArrayRef<std::string> Args) { 529 std::vector<llvm::StringRef> Refs(Args.size()); 530 llvm::copy(Args, Refs.begin()); 531 return printArgv(Refs); 532 } 533 534 } // namespace clangd 535 } // namespace clang 536