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