llvm-project
541 строка · 19.0 Кб
1//===--- SystemIncludeExtractor.cpp ------------------------------*- C++-*-===//
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// Some compiler drivers have implicit search mechanism for system headers.
9// This compilation database implementation tries to extract that information by
10// executing the driver in verbose mode. gcc-compatible drivers print something
11// like:
12// ....
13// ....
14// #include <...> search starts here:
15// /usr/lib/gcc/x86_64-linux-gnu/7/include
16// /usr/local/include
17// /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
18// /usr/include/x86_64-linux-gnu
19// /usr/include
20// End of search list.
21// ....
22// ....
23// This component parses that output and adds each path to command line args
24// provided by Base, after prepending them with -isystem. Therefore current
25// implementation would not work with a driver that is not gcc-compatible.
26//
27// First argument of the command line received from underlying compilation
28// database is used as compiler driver path. Due to this arbitrary binary
29// execution, this mechanism is not used by default and only executes binaries
30// in the paths that are explicitly included by the user.
31
32#include "CompileCommands.h"
33#include "GlobalCompilationDatabase.h"
34#include "support/Logger.h"
35#include "support/Threading.h"
36#include "support/Trace.h"
37#include "clang/Basic/Diagnostic.h"
38#include "clang/Basic/DiagnosticIDs.h"
39#include "clang/Basic/DiagnosticOptions.h"
40#include "clang/Basic/TargetInfo.h"
41#include "clang/Basic/TargetOptions.h"
42#include "clang/Driver/Types.h"
43#include "clang/Tooling/CompilationDatabase.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/Hashing.h"
47#include "llvm/ADT/IntrusiveRefCntPtr.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/ScopeExit.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/ADT/StringRef.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/Program.h"
59#include "llvm/Support/Regex.h"
60#include "llvm/Support/ScopedPrinter.h"
61#include "llvm/Support/raw_ostream.h"
62#include <cassert>
63#include <cstddef>
64#include <iterator>
65#include <memory>
66#include <optional>
67#include <string>
68#include <tuple>
69#include <utility>
70#include <vector>
71
72namespace clang::clangd {
73namespace {
74
75struct DriverInfo {
76std::vector<std::string> SystemIncludes;
77std::string Target;
78};
79
80struct DriverArgs {
81// Name of the driver program to execute or absolute path to it.
82std::string Driver;
83// Whether certain includes should be part of query.
84bool StandardIncludes = true;
85bool StandardCXXIncludes = true;
86// Language to use while querying.
87std::string Lang;
88std::string Sysroot;
89std::string ISysroot;
90std::string Target;
91std::string Stdlib;
92llvm::SmallVector<std::string> Specs;
93
94bool operator==(const DriverArgs &RHS) const {
95return std::tie(Driver, StandardIncludes, StandardCXXIncludes, Lang,
96Sysroot, ISysroot, Target, Stdlib, Specs) ==
97std::tie(RHS.Driver, RHS.StandardIncludes, RHS.StandardCXXIncludes,
98RHS.Lang, RHS.Sysroot, RHS.ISysroot, RHS.Target, RHS.Stdlib,
99RHS.Specs);
100}
101
102DriverArgs(const tooling::CompileCommand &Cmd, llvm::StringRef File) {
103llvm::SmallString<128> Driver(Cmd.CommandLine.front());
104// Driver is a not a single executable name but instead a path (either
105// relative or absolute).
106if (llvm::any_of(Driver,
107[](char C) { return llvm::sys::path::is_separator(C); })) {
108llvm::sys::fs::make_absolute(Cmd.Directory, Driver);
109}
110this->Driver = Driver.str().str();
111for (size_t I = 0, E = Cmd.CommandLine.size(); I < E; ++I) {
112llvm::StringRef Arg = Cmd.CommandLine[I];
113
114// Look for Language related flags.
115if (Arg.consume_front("-x")) {
116if (Arg.empty() && I + 1 < E)
117Lang = Cmd.CommandLine[I + 1];
118else
119Lang = Arg.str();
120}
121// Look for standard/builtin includes.
122else if (Arg == "-nostdinc" || Arg == "--no-standard-includes")
123StandardIncludes = false;
124else if (Arg == "-nostdinc++")
125StandardCXXIncludes = false;
126// Figure out sysroot
127else if (Arg.consume_front("--sysroot")) {
128if (Arg.consume_front("="))
129Sysroot = Arg.str();
130else if (Arg.empty() && I + 1 < E)
131Sysroot = Cmd.CommandLine[I + 1];
132} else if (Arg.consume_front("-isysroot")) {
133if (Arg.empty() && I + 1 < E)
134ISysroot = Cmd.CommandLine[I + 1];
135else
136ISysroot = Arg.str();
137} else if (Arg.consume_front("--target=")) {
138Target = Arg.str();
139} else if (Arg.consume_front("-target")) {
140if (Arg.empty() && I + 1 < E)
141Target = Cmd.CommandLine[I + 1];
142} else if (Arg.consume_front("--stdlib")) {
143if (Arg.consume_front("="))
144Stdlib = Arg.str();
145else if (Arg.empty() && I + 1 < E)
146Stdlib = Cmd.CommandLine[I + 1];
147} else if (Arg.consume_front("-stdlib=")) {
148Stdlib = Arg.str();
149} else if (Arg.starts_with("-specs=")) {
150// clang requires a single token like `-specs=file` or `--specs=file`,
151// but gcc will accept two tokens like `--specs file`. Since the
152// compilation database is presumably correct, we just forward the flags
153// as-is.
154Specs.push_back(Arg.str());
155} else if (Arg.starts_with("--specs=")) {
156Specs.push_back(Arg.str());
157} else if (Arg == "--specs" && I + 1 < E) {
158Specs.push_back(Arg.str());
159Specs.push_back(Cmd.CommandLine[I + 1]);
160}
161}
162
163// Downgrade objective-c++-header (used in clangd's fallback flags for .h
164// files) to c++-header, as some drivers may fail to run the extraction
165// command if it contains `-xobjective-c++-header` and objective-c++ support
166// is not installed.
167// In practice, we don't see different include paths for the two on
168// clang+mac, which is the most common objectve-c compiler.
169if (Lang == "objective-c++-header") {
170Lang = "c++-header";
171}
172
173// If language is not explicit in the flags, infer from the file.
174// This is important as we want to cache each language separately.
175if (Lang.empty()) {
176llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.');
177auto Type = driver::types::lookupTypeForExtension(Ext);
178if (Type == driver::types::TY_INVALID) {
179elog("System include extraction: invalid file type for {0}", Ext);
180} else {
181Lang = driver::types::getTypeName(Type);
182}
183}
184}
185llvm::SmallVector<llvm::StringRef> render() const {
186// FIXME: Don't treat lang specially?
187assert(!Lang.empty());
188llvm::SmallVector<llvm::StringRef> Args = {"-x", Lang};
189if (!StandardIncludes)
190Args.push_back("-nostdinc");
191if (!StandardCXXIncludes)
192Args.push_back("-nostdinc++");
193if (!Sysroot.empty())
194Args.append({"--sysroot", Sysroot});
195if (!ISysroot.empty())
196Args.append({"-isysroot", ISysroot});
197if (!Target.empty())
198Args.append({"-target", Target});
199if (!Stdlib.empty())
200Args.append({"--stdlib", Stdlib});
201
202for (llvm::StringRef Spec : Specs) {
203Args.push_back(Spec);
204}
205
206return Args;
207}
208
209static DriverArgs getEmpty() { return {}; }
210
211private:
212DriverArgs() = default;
213};
214} // namespace
215} // namespace clang::clangd
216namespace llvm {
217using DriverArgs = clang::clangd::DriverArgs;
218template <> struct DenseMapInfo<DriverArgs> {
219static DriverArgs getEmptyKey() {
220auto Driver = DriverArgs::getEmpty();
221Driver.Driver = "EMPTY_KEY";
222return Driver;
223}
224static DriverArgs getTombstoneKey() {
225auto Driver = DriverArgs::getEmpty();
226Driver.Driver = "TOMBSTONE_KEY";
227return Driver;
228}
229static unsigned getHashValue(const DriverArgs &Val) {
230unsigned FixedFieldsHash = llvm::hash_value(std::tuple{
231Val.Driver,
232Val.StandardIncludes,
233Val.StandardCXXIncludes,
234Val.Lang,
235Val.Sysroot,
236Val.ISysroot,
237Val.Target,
238Val.Stdlib,
239});
240
241unsigned SpecsHash =
242llvm::hash_combine_range(Val.Specs.begin(), Val.Specs.end());
243
244return llvm::hash_combine(FixedFieldsHash, SpecsHash);
245}
246static bool isEqual(const DriverArgs &LHS, const DriverArgs &RHS) {
247return LHS == RHS;
248}
249};
250} // namespace llvm
251namespace clang::clangd {
252namespace {
253bool isValidTarget(llvm::StringRef Triple) {
254std::shared_ptr<TargetOptions> TargetOpts(new TargetOptions);
255TargetOpts->Triple = Triple.str();
256DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions,
257new IgnoringDiagConsumer);
258llvm::IntrusiveRefCntPtr<TargetInfo> Target =
259TargetInfo::CreateTargetInfo(Diags, TargetOpts);
260return bool(Target);
261}
262
263std::optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
264DriverInfo Info;
265const char SIS[] = "#include <...> search starts here:";
266const char SIE[] = "End of search list.";
267const char TS[] = "Target: ";
268llvm::SmallVector<llvm::StringRef> Lines;
269Output.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
270
271enum {
272Initial, // Initial state: searching for target or includes list.
273IncludesExtracting, // Includes extracting.
274Done // Includes and target extraction done.
275} State = Initial;
276bool SeenIncludes = false;
277bool SeenTarget = false;
278for (auto *It = Lines.begin(); State != Done && It != Lines.end(); ++It) {
279auto Line = *It;
280switch (State) {
281case Initial:
282if (!SeenIncludes && Line.trim() == SIS) {
283SeenIncludes = true;
284State = IncludesExtracting;
285} else if (!SeenTarget && Line.trim().starts_with(TS)) {
286SeenTarget = true;
287llvm::StringRef TargetLine = Line.trim();
288TargetLine.consume_front(TS);
289// Only detect targets that clang understands
290if (!isValidTarget(TargetLine)) {
291elog("System include extraction: invalid target \"{0}\", ignoring",
292TargetLine);
293} else {
294Info.Target = TargetLine.str();
295vlog("System include extraction: target extracted: \"{0}\"",
296TargetLine);
297}
298}
299break;
300case IncludesExtracting:
301if (Line.trim() == SIE) {
302State = SeenTarget ? Done : Initial;
303} else {
304Info.SystemIncludes.push_back(Line.trim().str());
305vlog("System include extraction: adding {0}", Line);
306}
307break;
308default:
309llvm_unreachable("Impossible state of the driver output parser");
310break;
311}
312}
313if (!SeenIncludes) {
314elog("System include extraction: start marker not found: {0}", Output);
315return std::nullopt;
316}
317if (State == IncludesExtracting) {
318elog("System include extraction: end marker missing: {0}", Output);
319return std::nullopt;
320}
321return std::move(Info);
322}
323
324std::optional<std::string> run(llvm::ArrayRef<llvm::StringRef> Argv,
325bool OutputIsStderr) {
326llvm::SmallString<128> OutputPath;
327if (auto EC = llvm::sys::fs::createTemporaryFile("system-includes", "clangd",
328OutputPath)) {
329elog("System include extraction: failed to create temporary file with "
330"error {0}",
331EC.message());
332return std::nullopt;
333}
334auto CleanUp = llvm::make_scope_exit(
335[&OutputPath]() { llvm::sys::fs::remove(OutputPath); });
336
337std::optional<llvm::StringRef> Redirects[] = {{""}, {""}, {""}};
338Redirects[OutputIsStderr ? 2 : 1] = OutputPath.str();
339
340std::string ErrMsg;
341if (int RC =
342llvm::sys::ExecuteAndWait(Argv.front(), Argv, /*Env=*/std::nullopt,
343Redirects, /*SecondsToWait=*/0,
344/*MemoryLimit=*/0, &ErrMsg)) {
345elog("System include extraction: driver execution failed with return code: "
346"{0} - '{1}'. Args: [{2}]",
347llvm::to_string(RC), ErrMsg, printArgv(Argv));
348return std::nullopt;
349}
350
351auto BufOrError = llvm::MemoryBuffer::getFile(OutputPath);
352if (!BufOrError) {
353elog("System include extraction: failed to read {0} with error {1}",
354OutputPath, BufOrError.getError().message());
355return std::nullopt;
356}
357return BufOrError.get().get()->getBuffer().str();
358}
359
360std::optional<DriverInfo>
361extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
362const llvm::Regex &QueryDriverRegex) {
363trace::Span Tracer("Extract system includes and target");
364
365std::string Driver = InputArgs.Driver;
366if (!llvm::sys::path::is_absolute(Driver)) {
367auto DriverProgram = llvm::sys::findProgramByName(Driver);
368if (DriverProgram) {
369vlog("System include extraction: driver {0} expanded to {1}", Driver,
370*DriverProgram);
371Driver = *DriverProgram;
372} else {
373elog("System include extraction: driver {0} not found in PATH", Driver);
374return std::nullopt;
375}
376}
377
378SPAN_ATTACH(Tracer, "driver", Driver);
379SPAN_ATTACH(Tracer, "lang", InputArgs.Lang);
380
381// If driver was "../foo" then having to allowlist "/path/a/../foo" rather
382// than "/path/foo" is absurd.
383// Allow either to match the allowlist, then proceed with "/path/a/../foo".
384// This was our historical behavior, and it *could* resolve to something else.
385llvm::SmallString<256> NoDots(Driver);
386llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);
387if (!QueryDriverRegex.match(Driver) && !QueryDriverRegex.match(NoDots)) {
388vlog("System include extraction: not allowed driver {0}", Driver);
389return std::nullopt;
390}
391
392llvm::SmallVector<llvm::StringRef> Args = {Driver, "-E", "-v"};
393Args.append(InputArgs.render());
394// Input needs to go after Lang flags.
395Args.push_back("-");
396auto Output = run(Args, /*OutputIsStderr=*/true);
397if (!Output)
398return std::nullopt;
399
400std::optional<DriverInfo> Info = parseDriverOutput(*Output);
401if (!Info)
402return std::nullopt;
403
404// The built-in headers are tightly coupled to parser builtins.
405// (These are clang's "resource dir", GCC's GCC_INCLUDE_DIR.)
406// We should keep using clangd's versions, so exclude the queried builtins.
407// They're not specially marked in the -v output, but we can get the path
408// with `$DRIVER -print-file-name=include`.
409if (auto BuiltinHeaders =
410run({Driver, "-print-file-name=include"}, /*OutputIsStderr=*/false)) {
411auto Path = llvm::StringRef(*BuiltinHeaders).trim();
412if (!Path.empty() && llvm::sys::path::is_absolute(Path)) {
413auto Size = Info->SystemIncludes.size();
414llvm::erase(Info->SystemIncludes, Path);
415vlog("System includes extractor: builtin headers {0} {1}", Path,
416(Info->SystemIncludes.size() != Size)
417? "excluded"
418: "not found in driver's response");
419}
420}
421
422log("System includes extractor: successfully executed {0}\n\tgot includes: "
423"\"{1}\"\n\tgot target: \"{2}\"",
424Driver, llvm::join(Info->SystemIncludes, ", "), Info->Target);
425return Info;
426}
427
428tooling::CompileCommand &
429addSystemIncludes(tooling::CompileCommand &Cmd,
430llvm::ArrayRef<std::string> SystemIncludes) {
431std::vector<std::string> ToAppend;
432for (llvm::StringRef Include : SystemIncludes) {
433// FIXME(kadircet): This doesn't work when we have "--driver-mode=cl"
434ToAppend.push_back("-isystem");
435ToAppend.push_back(Include.str());
436}
437if (!ToAppend.empty()) {
438// Just append when `--` isn't present.
439auto InsertAt = llvm::find(Cmd.CommandLine, "--");
440Cmd.CommandLine.insert(InsertAt, std::make_move_iterator(ToAppend.begin()),
441std::make_move_iterator(ToAppend.end()));
442}
443return Cmd;
444}
445
446tooling::CompileCommand &setTarget(tooling::CompileCommand &Cmd,
447const std::string &Target) {
448if (!Target.empty()) {
449// We do not want to override existing target with extracted one.
450for (llvm::StringRef Arg : Cmd.CommandLine) {
451if (Arg == "-target" || Arg.starts_with("--target="))
452return Cmd;
453}
454// Just append when `--` isn't present.
455auto InsertAt = llvm::find(Cmd.CommandLine, "--");
456Cmd.CommandLine.insert(InsertAt, "--target=" + Target);
457}
458return Cmd;
459}
460
461/// Converts a glob containing only ** or * into a regex.
462std::string convertGlobToRegex(llvm::StringRef Glob) {
463std::string RegText;
464llvm::raw_string_ostream RegStream(RegText);
465RegStream << '^';
466for (size_t I = 0, E = Glob.size(); I < E; ++I) {
467if (Glob[I] == '*') {
468if (I + 1 < E && Glob[I + 1] == '*') {
469// Double star, accept any sequence.
470RegStream << ".*";
471// Also skip the second star.
472++I;
473} else {
474// Single star, accept any sequence without a slash.
475RegStream << "[^/]*";
476}
477} else if (llvm::sys::path::is_separator(Glob[I]) &&
478llvm::sys::path::is_separator('/') &&
479llvm::sys::path::is_separator('\\')) {
480RegStream << R"([/\\])"; // Accept either slash on windows.
481} else {
482RegStream << llvm::Regex::escape(Glob.substr(I, 1));
483}
484}
485RegStream << '$';
486RegStream.flush();
487return RegText;
488}
489
490/// Converts a glob containing only ** or * into a regex.
491llvm::Regex convertGlobsToRegex(llvm::ArrayRef<std::string> Globs) {
492assert(!Globs.empty() && "Globs cannot be empty!");
493std::vector<std::string> RegTexts;
494RegTexts.reserve(Globs.size());
495for (llvm::StringRef Glob : Globs)
496RegTexts.push_back(convertGlobToRegex(Glob));
497
498// Tempting to pass IgnoreCase, but we don't know the FS sensitivity.
499llvm::Regex Reg(llvm::join(RegTexts, "|"));
500assert(Reg.isValid(RegTexts.front()) &&
501"Created an invalid regex from globs");
502return Reg;
503}
504
505/// Extracts system includes from a trusted driver by parsing the output of
506/// include search path and appends them to the commands coming from underlying
507/// compilation database.
508class SystemIncludeExtractor {
509public:
510SystemIncludeExtractor(llvm::ArrayRef<std::string> QueryDriverGlobs)
511: QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)) {}
512
513void operator()(tooling::CompileCommand &Cmd, llvm::StringRef File) const {
514if (Cmd.CommandLine.empty())
515return;
516
517DriverArgs Args(Cmd, File);
518if (Args.Lang.empty())
519return;
520if (auto Info = QueriedDrivers.get(Args, [&] {
521return extractSystemIncludesAndTarget(Args, QueryDriverRegex);
522})) {
523setTarget(addSystemIncludes(Cmd, Info->SystemIncludes), Info->Target);
524}
525}
526
527private:
528// Caches includes extracted from a driver. Key is driver:lang.
529Memoize<llvm::DenseMap<DriverArgs, std::optional<DriverInfo>>> QueriedDrivers;
530llvm::Regex QueryDriverRegex;
531};
532} // namespace
533
534SystemIncludeExtractorFn
535getSystemIncludeExtractor(llvm::ArrayRef<std::string> QueryDriverGlobs) {
536if (QueryDriverGlobs.empty())
537return nullptr;
538return SystemIncludeExtractor(QueryDriverGlobs);
539}
540
541} // namespace clang::clangd
542