1 //===--- QueryDriverDatabase.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 "GlobalCompilationDatabase.h"
33 #include "support/Logger.h"
34 #include "support/Path.h"
35 #include "support/Trace.h"
36 #include "clang/Basic/Diagnostic.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TargetOptions.h"
39 #include "clang/Driver/Types.h"
40 #include "clang/Tooling/CompilationDatabase.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/StringRef.h"
46 #include "llvm/ADT/iterator_range.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/Regex.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include <algorithm>
54 #include <map>
55 #include <string>
56 #include <vector>
57 
58 namespace clang {
59 namespace clangd {
60 namespace {
61 
62 struct DriverInfo {
63   std::vector<std::string> SystemIncludes;
64   std::string Target;
65 };
66 
67 bool isValidTarget(llvm::StringRef Triple) {
68   std::shared_ptr<TargetOptions> TargetOpts(new TargetOptions);
69   TargetOpts->Triple = Triple.str();
70   DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions,
71                           new IgnoringDiagConsumer);
72   IntrusiveRefCntPtr<TargetInfo> Target =
73       TargetInfo::CreateTargetInfo(Diags, TargetOpts);
74   return bool(Target);
75 }
76 
77 llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
78   DriverInfo Info;
79   const char SIS[] = "#include <...> search starts here:";
80   const char SIE[] = "End of search list.";
81   const char TS[] = "Target: ";
82   llvm::SmallVector<llvm::StringRef> Lines;
83   Output.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
84 
85   enum {
86     Initial,            // Initial state: searching for target or includes list.
87     IncludesExtracting, // Includes extracting.
88     Done                // Includes and target extraction done.
89   } State = Initial;
90   bool SeenIncludes = false;
91   bool SeenTarget = false;
92   for (auto *It = Lines.begin(); State != Done && It != Lines.end(); ++It) {
93     auto Line = *It;
94     switch (State) {
95     case Initial:
96       if (!SeenIncludes && Line.trim() == SIS) {
97         SeenIncludes = true;
98         State = IncludesExtracting;
99       } else if (!SeenTarget && Line.trim().startswith(TS)) {
100         SeenTarget = true;
101         llvm::StringRef TargetLine = Line.trim();
102         TargetLine.consume_front(TS);
103         // Only detect targets that clang understands
104         if (!isValidTarget(TargetLine)) {
105           elog("System include extraction: invalid target \"{0}\", ignoring",
106                TargetLine);
107         } else {
108           Info.Target = TargetLine.str();
109           vlog("System include extraction: target extracted: \"{0}\"",
110                TargetLine);
111         }
112       }
113       break;
114     case IncludesExtracting:
115       if (Line.trim() == SIE) {
116         State = SeenTarget ? Done : Initial;
117       } else {
118         Info.SystemIncludes.push_back(Line.trim().str());
119         vlog("System include extraction: adding {0}", Line);
120       }
121       break;
122     default:
123       llvm_unreachable("Impossible state of the driver output parser");
124       break;
125     }
126   }
127   if (!SeenIncludes) {
128     elog("System include extraction: start marker not found: {0}", Output);
129     return llvm::None;
130   }
131   if (State == IncludesExtracting) {
132     elog("System include extraction: end marker missing: {0}", Output);
133     return llvm::None;
134   }
135   return std::move(Info);
136 }
137 
138 llvm::Optional<DriverInfo>
139 extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
140                                llvm::StringRef Lang,
141                                llvm::ArrayRef<std::string> CommandLine,
142                                const llvm::Regex &QueryDriverRegex) {
143   trace::Span Tracer("Extract system includes and target");
144 
145   if (!llvm::sys::path::is_absolute(Driver)) {
146     assert(llvm::none_of(
147         Driver, [](char C) { return llvm::sys::path::is_separator(C); }));
148     auto DriverProgram = llvm::sys::findProgramByName(Driver);
149     if (DriverProgram) {
150       vlog("System include extraction: driver {0} expanded to {1}", Driver,
151            *DriverProgram);
152       Driver = *DriverProgram;
153     } else {
154       elog("System include extraction: driver {0} not found in PATH", Driver);
155       return llvm::None;
156     }
157   }
158 
159   SPAN_ATTACH(Tracer, "driver", Driver);
160   SPAN_ATTACH(Tracer, "lang", Lang);
161 
162   if (!QueryDriverRegex.match(Driver)) {
163     vlog("System include extraction: not allowed driver {0}", Driver);
164     return llvm::None;
165   }
166 
167   llvm::SmallString<128> StdErrPath;
168   if (auto EC = llvm::sys::fs::createTemporaryFile("system-includes", "clangd",
169                                                    StdErrPath)) {
170     elog("System include extraction: failed to create temporary file with "
171          "error {0}",
172          EC.message());
173     return llvm::None;
174   }
175   auto CleanUp = llvm::make_scope_exit(
176       [&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); });
177 
178   llvm::Optional<llvm::StringRef> Redirects[] = {
179       {""}, {""}, llvm::StringRef(StdErrPath)};
180 
181   llvm::SmallVector<llvm::StringRef> Args = {Driver, "-E", "-x",
182                                              Lang,   "-",  "-v"};
183 
184   // These flags will be preserved
185   const llvm::StringRef FlagsToPreserve[] = {
186       "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"};
187   // Preserves these flags and their values, either as separate args or with an
188   // equalsbetween them
189   const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"};
190 
191   for (size_t I = 0, E = CommandLine.size(); I < E; ++I) {
192     llvm::StringRef Arg = CommandLine[I];
193     if (llvm::any_of(FlagsToPreserve,
194                      [&Arg](llvm::StringRef S) { return S == Arg; })) {
195       Args.push_back(Arg);
196     } else {
197       const auto *Found =
198           llvm::find_if(ArgsToPreserve, [&Arg](llvm::StringRef S) {
199             return Arg.startswith(S);
200           });
201       if (Found == std::end(ArgsToPreserve))
202         continue;
203       Arg = Arg.drop_front(Found->size());
204       if (Arg.empty() && I + 1 < E) {
205         Args.push_back(CommandLine[I]);
206         Args.push_back(CommandLine[++I]);
207       } else if (Arg.startswith("=")) {
208         Args.push_back(CommandLine[I]);
209       }
210     }
211   }
212 
213   std::string ErrMsg;
214   if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, /*Env=*/llvm::None,
215                                          Redirects, /*SecondsToWait=*/0,
216                                          /*MemoryLimit=*/0, &ErrMsg)) {
217     elog("System include extraction: driver execution failed with return code: "
218          "{0} - '{1}'. Args: [{2}]",
219          llvm::to_string(RC), ErrMsg, printArgv(Args));
220     return llvm::None;
221   }
222 
223   auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath);
224   if (!BufOrError) {
225     elog("System include extraction: failed to read {0} with error {1}",
226          StdErrPath, BufOrError.getError().message());
227     return llvm::None;
228   }
229 
230   llvm::Optional<DriverInfo> Info =
231       parseDriverOutput(BufOrError->get()->getBuffer());
232   if (!Info)
233     return llvm::None;
234   log("System includes extractor: successfully executed {0}\n\tgot includes: "
235       "\"{1}\"\n\tgot target: \"{2}\"",
236       Driver, llvm::join(Info->SystemIncludes, ", "), Info->Target);
237   return Info;
238 }
239 
240 tooling::CompileCommand &
241 addSystemIncludes(tooling::CompileCommand &Cmd,
242                   llvm::ArrayRef<std::string> SystemIncludes) {
243   for (llvm::StringRef Include : SystemIncludes) {
244     // FIXME(kadircet): This doesn't work when we have "--driver-mode=cl"
245     Cmd.CommandLine.push_back("-isystem");
246     Cmd.CommandLine.push_back(Include.str());
247   }
248   return Cmd;
249 }
250 
251 tooling::CompileCommand &setTarget(tooling::CompileCommand &Cmd,
252                                    const std::string &Target) {
253   if (!Target.empty()) {
254     // We do not want to override existing target with extracted one.
255     for (llvm::StringRef Arg : Cmd.CommandLine) {
256       if (Arg == "-target" || Arg.startswith("--target="))
257         return Cmd;
258     }
259     Cmd.CommandLine.push_back("--target=" + Target);
260   }
261   return Cmd;
262 }
263 
264 /// Converts a glob containing only ** or * into a regex.
265 std::string convertGlobToRegex(llvm::StringRef Glob) {
266   std::string RegText;
267   llvm::raw_string_ostream RegStream(RegText);
268   RegStream << '^';
269   for (size_t I = 0, E = Glob.size(); I < E; ++I) {
270     if (Glob[I] == '*') {
271       if (I + 1 < E && Glob[I + 1] == '*') {
272         // Double star, accept any sequence.
273         RegStream << ".*";
274         // Also skip the second star.
275         ++I;
276       } else {
277         // Single star, accept any sequence without a slash.
278         RegStream << "[^/]*";
279       }
280     } else {
281       RegStream << llvm::Regex::escape(Glob.substr(I, 1));
282     }
283   }
284   RegStream << '$';
285   RegStream.flush();
286   return RegText;
287 }
288 
289 /// Converts a glob containing only ** or * into a regex.
290 llvm::Regex convertGlobsToRegex(llvm::ArrayRef<std::string> Globs) {
291   assert(!Globs.empty() && "Globs cannot be empty!");
292   std::vector<std::string> RegTexts;
293   RegTexts.reserve(Globs.size());
294   for (llvm::StringRef Glob : Globs)
295     RegTexts.push_back(convertGlobToRegex(Glob));
296 
297   llvm::Regex Reg(llvm::join(RegTexts, "|"));
298   assert(Reg.isValid(RegTexts.front()) &&
299          "Created an invalid regex from globs");
300   return Reg;
301 }
302 
303 /// Extracts system includes from a trusted driver by parsing the output of
304 /// include search path and appends them to the commands coming from underlying
305 /// compilation database.
306 class QueryDriverDatabase : public DelegatingCDB {
307 public:
308   QueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs,
309                       std::unique_ptr<GlobalCompilationDatabase> Base)
310       : DelegatingCDB(std::move(Base)),
311         QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)) {}
312 
313   llvm::Optional<tooling::CompileCommand>
314   getCompileCommand(PathRef File) const override {
315     auto Cmd = DelegatingCDB::getCompileCommand(File);
316     if (!Cmd || Cmd->CommandLine.empty())
317       return Cmd;
318 
319     llvm::StringRef Lang;
320     for (size_t I = 0, E = Cmd->CommandLine.size(); I < E; ++I) {
321       llvm::StringRef Arg = Cmd->CommandLine[I];
322       if (Arg == "-x" && I + 1 < E)
323         Lang = Cmd->CommandLine[I + 1];
324       else if (Arg.startswith("-x"))
325         Lang = Arg.drop_front(2).trim();
326     }
327     if (Lang.empty()) {
328       llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.');
329       auto Type = driver::types::lookupTypeForExtension(Ext);
330       if (Type == driver::types::TY_INVALID) {
331         elog("System include extraction: invalid file type for {0}", Ext);
332         return {};
333       }
334       Lang = driver::types::getTypeName(Type);
335     }
336 
337     llvm::SmallString<128> Driver(Cmd->CommandLine.front());
338     if (llvm::any_of(Driver,
339                        [](char C) { return llvm::sys::path::is_separator(C); }))
340       // Driver is a not a single executable name but instead a path (either
341       // relative or absolute).
342       llvm::sys::fs::make_absolute(Cmd->Directory, Driver);
343 
344     if (auto Info =
345             QueriedDrivers.get(/*Key=*/(Driver + ":" + Lang).str(), [&] {
346               return extractSystemIncludesAndTarget(
347                   Driver, Lang, Cmd->CommandLine, QueryDriverRegex);
348             })) {
349       setTarget(addSystemIncludes(*Cmd, Info->SystemIncludes), Info->Target);
350     }
351     return Cmd;
352   }
353 
354 private:
355   // Caches includes extracted from a driver. Key is driver:lang.
356   Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers;
357   llvm::Regex QueryDriverRegex;
358 };
359 } // namespace
360 
361 std::unique_ptr<GlobalCompilationDatabase>
362 getQueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs,
363                        std::unique_ptr<GlobalCompilationDatabase> Base) {
364   assert(Base && "Null base to SystemIncludeExtractor");
365   if (QueryDriverGlobs.empty())
366     return Base;
367   return std::make_unique<QueryDriverDatabase>(QueryDriverGlobs,
368                                                std::move(Base));
369 }
370 
371 } // namespace clangd
372 } // namespace clang
373