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 "support/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 // The path passed to argv[0] is important:
123 //  - its parent directory is Driver::Dir, used for library discovery
124 //  - its basename affects CLI parsing (clang-cl) and other settings
125 // Where possible it should be an absolute path with sensible directory, but
126 // with the original basename.
127 static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink,
128                                  llvm::Optional<std::string> ClangPath) {
129   auto SiblingOf = [&](llvm::StringRef AbsPath) {
130     llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
131     llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
132     return Result.str().str();
133   };
134 
135   // First, eliminate relative paths.
136   std::string Storage;
137   if (!llvm::sys::path::is_absolute(Driver)) {
138     // If it's working-dir relative like bin/clang, we can't resolve it.
139     // FIXME: we could if we had the working directory here.
140     // Let's hope it's not a symlink.
141     if (llvm::any_of(Driver,
142                      [](char C) { return llvm::sys::path::is_separator(C); }))
143       return Driver.str();
144     // If the driver is a generic like "g++" with no path, add clang dir.
145     if (ClangPath &&
146         (Driver == "clang" || Driver == "clang++" || Driver == "gcc" ||
147          Driver == "g++" || Driver == "cc" || Driver == "c++")) {
148       return SiblingOf(*ClangPath);
149     }
150     // Otherwise try to look it up on PATH. This won't change basename.
151     auto Absolute = llvm::sys::findProgramByName(Driver);
152     if (Absolute && llvm::sys::path::is_absolute(*Absolute))
153       Driver = Storage = std::move(*Absolute);
154     else if (ClangPath) // If we don't find it, use clang dir again.
155       return SiblingOf(*ClangPath);
156     else // Nothing to do: can't find the command and no detected dir.
157       return Driver.str();
158   }
159 
160   // Now we have an absolute path, but it may be a symlink.
161   assert(llvm::sys::path::is_absolute(Driver));
162   if (FollowSymlink) {
163     llvm::SmallString<256> Resolved;
164     if (!llvm::sys::fs::real_path(Driver, Resolved))
165       return SiblingOf(Resolved);
166   }
167   return Driver.str();
168 }
169 
170 } // namespace
171 
172 CommandMangler CommandMangler::detect() {
173   CommandMangler Result;
174   Result.ClangPath = detectClangPath();
175   Result.ResourceDir = detectStandardResourceDir();
176   Result.Sysroot = detectSysroot();
177   return Result;
178 }
179 
180 CommandMangler CommandMangler::forTests() {
181   return CommandMangler();
182 }
183 
184 void CommandMangler::adjust(std::vector<std::string> &Cmd) const {
185   // Check whether the flag exists, either as -flag or -flag=*
186   auto Has = [&](llvm::StringRef Flag) {
187     for (llvm::StringRef Arg : Cmd) {
188       if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] == '='))
189         return true;
190     }
191     return false;
192   };
193 
194   // clangd should not write files to disk, including dependency files
195   // requested on the command line.
196   Cmd = tooling::getClangStripDependencyFileAdjuster()(Cmd, "");
197   // Strip plugin related command line arguments. Clangd does
198   // not support plugins currently. Therefore it breaks if
199   // compiler tries to load plugins.
200   Cmd = tooling::getStripPluginsAdjuster()(Cmd, "");
201   Cmd = tooling::getClangSyntaxOnlyAdjuster()(Cmd, "");
202 
203   if (ResourceDir && !Has("-resource-dir"))
204     Cmd.push_back(("-resource-dir=" + *ResourceDir));
205 
206   // Don't set `-isysroot` if it is already set or if `--sysroot` is set.
207   // `--sysroot` is a superset of the `-isysroot` argument.
208   if (Sysroot && !Has("-isysroot") && !Has("--sysroot")) {
209     Cmd.push_back("-isysroot");
210     Cmd.push_back(*Sysroot);
211   }
212 
213   if (!Cmd.empty()) {
214     bool FollowSymlink = !Has("-no-canonical-prefixes");
215     Cmd.front() =
216         (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
217             .get(Cmd.front(), [&, this] {
218               return resolveDriver(Cmd.front(), FollowSymlink, ClangPath);
219             });
220   }
221 }
222 
223 CommandMangler::operator clang::tooling::ArgumentsAdjuster() && {
224   // ArgumentsAdjuster is a std::function and so must be copyable.
225   return [Mangler = std::make_shared<CommandMangler>(std::move(*this))](
226              const std::vector<std::string> &Args, llvm::StringRef File) {
227     auto Result = Args;
228     Mangler->adjust(Result);
229     return Result;
230   };
231 }
232 
233 } // namespace clangd
234 } // namespace clang
235