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