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 "Logger.h" 11 #include "clang/Frontend/CompilerInvocation.h" 12 #include "clang/Tooling/ArgumentsAdjusters.h" 13 #include "llvm/Support/FileSystem.h" 14 #include "llvm/Support/FileUtilities.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "llvm/Support/Path.h" 17 #include "llvm/Support/Program.h" 18 19 namespace clang { 20 namespace clangd { 21 namespace { 22 23 // Query apple's `xcrun` launcher, which is the source of truth for "how should" 24 // clang be invoked on this system. 25 llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) { 26 auto Xcrun = llvm::sys::findProgramByName("xcrun"); 27 if (!Xcrun) { 28 log("Couldn't find xcrun. Hopefully you have a non-apple toolchain..."); 29 return llvm::None; 30 } 31 llvm::SmallString<64> OutFile; 32 llvm::sys::fs::createTemporaryFile("clangd-xcrun", "", OutFile); 33 llvm::FileRemover OutRemover(OutFile); 34 llvm::Optional<llvm::StringRef> Redirects[3] = { 35 /*stdin=*/{""}, /*stdout=*/{OutFile}, /*stderr=*/{""}}; 36 vlog("Invoking {0} to find clang installation", *Xcrun); 37 int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv, 38 /*Env=*/llvm::None, Redirects, 39 /*SecondsToWait=*/10); 40 if (Ret != 0) { 41 log("xcrun exists but failed with code {0}. " 42 "If you have a non-apple toolchain, this is OK. " 43 "Otherwise, try xcode-select --install.", 44 Ret); 45 return llvm::None; 46 } 47 48 auto Buf = llvm::MemoryBuffer::getFile(OutFile); 49 if (!Buf) { 50 log("Can't read xcrun output: {0}", Buf.getError().message()); 51 return llvm::None; 52 } 53 StringRef Path = Buf->get()->getBuffer().trim(); 54 if (Path.empty()) { 55 log("xcrun produced no output"); 56 return llvm::None; 57 } 58 return Path.str(); 59 } 60 61 // Resolve symlinks if possible. 62 std::string resolve(std::string Path) { 63 llvm::SmallString<128> Resolved; 64 if (llvm::sys::fs::real_path(Path, Resolved)) { 65 log("Failed to resolve possible symlink {0}", Path); 66 return Path; 67 } 68 return std::string(Resolved.str()); 69 } 70 71 // Get a plausible full `clang` path. 72 // This is used in the fallback compile command, or when the CDB returns a 73 // generic driver with no path. 74 std::string detectClangPath() { 75 // The driver and/or cc1 sometimes depend on the binary name to compute 76 // useful things like the standard library location. 77 // We need to emulate what clang on this system is likely to see. 78 // cc1 in particular looks at the "real path" of the running process, and 79 // so if /usr/bin/clang is a symlink, it sees the resolved path. 80 // clangd doesn't have that luxury, so we resolve symlinks ourselves. 81 82 // On Mac, `which clang` is /usr/bin/clang. It runs `xcrun clang`, which knows 83 // where the real clang is kept. We need to do the same thing, 84 // because cc1 (not the driver!) will find libc++ relative to argv[0]. 85 #ifdef __APPLE__ 86 if (auto MacClang = queryXcrun({"xcrun", "--find", "clang"})) 87 return resolve(std::move(*MacClang)); 88 #endif 89 // On other platforms, just look for compilers on the PATH. 90 for (const char *Name : {"clang", "gcc", "cc"}) 91 if (auto PathCC = llvm::sys::findProgramByName(Name)) 92 return resolve(std::move(*PathCC)); 93 // Fallback: a nonexistent 'clang' binary next to clangd. 94 static int Dummy; 95 std::string ClangdExecutable = 96 llvm::sys::fs::getMainExecutable("clangd", (void *)&Dummy); 97 SmallString<128> ClangPath; 98 ClangPath = llvm::sys::path::parent_path(ClangdExecutable); 99 llvm::sys::path::append(ClangPath, "clang"); 100 return std::string(ClangPath.str()); 101 } 102 103 // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang. 104 // The effect of this is to set -isysroot correctly. We do the same. 105 const llvm::Optional<std::string> detectSysroot() { 106 #ifndef __APPLE__ 107 return llvm::None; 108 #endif 109 110 // SDKROOT overridden in environment, respect it. Driver will set isysroot. 111 if (::getenv("SDKROOT")) 112 return llvm::None; 113 return queryXcrun({"xcrun", "--show-sdk-path"}); 114 return llvm::None; 115 } 116 117 std::string detectStandardResourceDir() { 118 static int Dummy; // Just an address in this process. 119 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy); 120 } 121 122 } // namespace 123 124 CommandMangler CommandMangler::detect() { 125 CommandMangler Result; 126 Result.ClangPath = detectClangPath(); 127 Result.ResourceDir = detectStandardResourceDir(); 128 Result.Sysroot = detectSysroot(); 129 return Result; 130 } 131 132 CommandMangler CommandMangler::forTests() { 133 return CommandMangler(); 134 } 135 136 void CommandMangler::adjust(std::vector<std::string> &Cmd) const { 137 // Check whether the flag exists, either as -flag or -flag=* 138 auto Has = [&](llvm::StringRef Flag) { 139 for (llvm::StringRef Arg : Cmd) { 140 if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] == '=')) 141 return true; 142 } 143 return false; 144 }; 145 146 // clangd should not write files to disk, including dependency files 147 // requested on the command line. 148 Cmd = tooling::getClangStripDependencyFileAdjuster()(Cmd, ""); 149 // Strip plugin related command line arguments. Clangd does 150 // not support plugins currently. Therefore it breaks if 151 // compiler tries to load plugins. 152 Cmd = tooling::getStripPluginsAdjuster()(Cmd, ""); 153 Cmd = tooling::getClangSyntaxOnlyAdjuster()(Cmd, ""); 154 155 if (ResourceDir && !Has("-resource-dir")) 156 Cmd.push_back(("-resource-dir=" + *ResourceDir)); 157 158 // Don't set `-isysroot` if it is already set or if `--sysroot` is set. 159 // `--sysroot` is a superset of the `-isysroot` argument. 160 if (Sysroot && !Has("-isysroot") && !Has("--sysroot")) { 161 Cmd.push_back("-isysroot"); 162 Cmd.push_back(*Sysroot); 163 } 164 165 // If the driver is a generic name like "g++" with no path, add a clang path. 166 // This makes it easier for us to find the standard libraries on mac. 167 if (ClangPath && llvm::sys::path::is_absolute(*ClangPath) && !Cmd.empty()) { 168 std::string &Driver = Cmd.front(); 169 if (Driver == "clang" || Driver == "clang++" || Driver == "gcc" || 170 Driver == "g++" || Driver == "cc" || Driver == "c++") { 171 llvm::SmallString<128> QualifiedDriver = 172 llvm::sys::path::parent_path(*ClangPath); 173 llvm::sys::path::append(QualifiedDriver, Driver); 174 Driver = std::string(QualifiedDriver.str()); 175 } 176 } 177 } 178 179 CommandMangler::operator clang::tooling::ArgumentsAdjuster() { 180 return [Mangler{*this}](const std::vector<std::string> &Args, 181 llvm::StringRef File) { 182 auto Result = Args; 183 Mangler.adjust(Result); 184 return Result; 185 }; 186 } 187 188 } // namespace clangd 189 } // namespace clang 190