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 whitelisted by the user. 31 32 #include "GlobalCompilationDatabase.h" 33 #include "Logger.h" 34 #include "Path.h" 35 #include "Trace.h" 36 #include "clang/Driver/Types.h" 37 #include "clang/Tooling/CompilationDatabase.h" 38 #include "llvm/ADT/DenseMap.h" 39 #include "llvm/ADT/ScopeExit.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/StringExtras.h" 42 #include "llvm/ADT/StringRef.h" 43 #include "llvm/ADT/iterator_range.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/Program.h" 48 #include "llvm/Support/Regex.h" 49 #include "llvm/Support/ScopedPrinter.h" 50 #include <algorithm> 51 #include <map> 52 #include <string> 53 #include <vector> 54 55 namespace clang { 56 namespace clangd { 57 namespace { 58 59 std::vector<std::string> parseDriverOutput(llvm::StringRef Output) { 60 std::vector<std::string> SystemIncludes; 61 constexpr char const *SIS = "#include <...> search starts here:"; 62 constexpr char const *SIE = "End of search list."; 63 llvm::SmallVector<llvm::StringRef, 8> Lines; 64 Output.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 65 66 auto StartIt = std::find(Lines.begin(), Lines.end(), SIS); 67 if (StartIt == Lines.end()) { 68 elog("System include extraction: start marker not found: {0}", Output); 69 return {}; 70 } 71 ++StartIt; 72 const auto EndIt = std::find(StartIt, Lines.end(), SIE); 73 if (EndIt == Lines.end()) { 74 elog("System include extraction: end marker missing: {0}", Output); 75 return {}; 76 } 77 78 for (llvm::StringRef Line : llvm::make_range(StartIt, EndIt)) { 79 SystemIncludes.push_back(Line.str()); 80 vlog("System include extraction: adding {0}", Line); 81 } 82 return SystemIncludes; 83 } 84 85 std::vector<std::string> extractSystemIncludes(PathRef Driver, 86 llvm::StringRef Ext, 87 llvm::Regex &QueryDriverRegex) { 88 trace::Span Tracer("Extract system includes"); 89 SPAN_ATTACH(Tracer, "driver", Driver); 90 SPAN_ATTACH(Tracer, "ext", Ext); 91 92 if (!QueryDriverRegex.match(Driver)) { 93 vlog("System include extraction: not whitelisted driver {0}", Driver); 94 return {}; 95 } 96 97 if (!llvm::sys::fs::exists(Driver)) { 98 elog("System include extraction: {0} does not exist.", Driver); 99 return {}; 100 } 101 if (!llvm::sys::fs::can_execute(Driver)) { 102 elog("System include extraction: {0} is not executable.", Driver); 103 return {}; 104 } 105 106 llvm::SmallString<128> StdErrPath; 107 if (auto EC = llvm::sys::fs::createTemporaryFile("system-includes", "clangd", 108 StdErrPath)) { 109 elog("System include extraction: failed to create temporary file with " 110 "error {0}", 111 EC.message()); 112 return {}; 113 } 114 auto CleanUp = llvm::make_scope_exit( 115 [&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); }); 116 117 llvm::Optional<llvm::StringRef> Redirects[] = { 118 {""}, {""}, llvm::StringRef(StdErrPath)}; 119 120 auto Type = driver::types::lookupTypeForExtension(Ext); 121 if (Type == driver::types::TY_INVALID) { 122 elog("System include extraction: invalid file type for {0}", Ext); 123 return {}; 124 } 125 // Should we also preserve flags like "-sysroot", "-nostdinc" ? 126 const llvm::StringRef Args[] = { 127 Driver, "-E", "-x", driver::types::getTypeName(Type), "-", "-v"}; 128 129 if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, /*Env=*/llvm::None, 130 Redirects)) { 131 elog("System include extraction: driver execution failed with return code: " 132 "{0}", 133 llvm::to_string(RC)); 134 return {}; 135 } 136 137 auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath); 138 if (!BufOrError) { 139 elog("System include extraction: failed to read {0} with error {1}", 140 StdErrPath, BufOrError.getError().message()); 141 return {}; 142 } 143 144 auto Includes = parseDriverOutput(BufOrError->get()->getBuffer()); 145 log("System include extractor: succesfully executed {0}, got includes: " 146 "\"{1}\"", 147 Driver, llvm::join(Includes, ", ")); 148 return Includes; 149 } 150 151 tooling::CompileCommand & 152 addSystemIncludes(tooling::CompileCommand &Cmd, 153 llvm::ArrayRef<std::string> SystemIncludes) { 154 for (llvm::StringRef Include : SystemIncludes) { 155 // FIXME(kadircet): This doesn't work when we have "--driver-mode=cl" 156 Cmd.CommandLine.push_back("-isystem"); 157 Cmd.CommandLine.push_back(Include.str()); 158 } 159 return Cmd; 160 } 161 162 /// Converts a glob containing only ** or * into a regex. 163 std::string convertGlobToRegex(llvm::StringRef Glob) { 164 std::string RegText; 165 llvm::raw_string_ostream RegStream(RegText); 166 RegStream << '^'; 167 for (size_t I = 0, E = Glob.size(); I < E; ++I) { 168 if (Glob[I] == '*') { 169 if (I + 1 < E && Glob[I + 1] == '*') { 170 // Double star, accept any sequence. 171 RegStream << ".*"; 172 // Also skip the second star. 173 ++I; 174 } else { 175 // Single star, accept any sequence without a slash. 176 RegStream << "[^/]*"; 177 } 178 } else { 179 RegStream << llvm::Regex::escape(Glob.substr(I, 1)); 180 } 181 } 182 RegStream << '$'; 183 RegStream.flush(); 184 return RegText; 185 } 186 187 /// Converts a glob containing only ** or * into a regex. 188 llvm::Regex convertGlobsToRegex(llvm::ArrayRef<std::string> Globs) { 189 assert(!Globs.empty() && "Globs cannot be empty!"); 190 std::vector<std::string> RegTexts; 191 RegTexts.reserve(Globs.size()); 192 for (llvm::StringRef Glob : Globs) 193 RegTexts.push_back(convertGlobToRegex(Glob)); 194 195 llvm::Regex Reg(llvm::join(RegTexts, "|")); 196 assert(Reg.isValid(RegTexts.front()) && 197 "Created an invalid regex from globs"); 198 return Reg; 199 } 200 201 /// Extracts system includes from a trusted driver by parsing the output of 202 /// include search path and appends them to the commands coming from underlying 203 /// compilation database. 204 class QueryDriverDatabase : public GlobalCompilationDatabase { 205 public: 206 QueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs, 207 std::unique_ptr<GlobalCompilationDatabase> Base) 208 : QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)), 209 Base(std::move(Base)) { 210 assert(this->Base); 211 BaseChanged = 212 this->Base->watch([this](const std::vector<std::string> &Changes) { 213 OnCommandChanged.broadcast(Changes); 214 }); 215 } 216 217 llvm::Optional<tooling::CompileCommand> 218 getCompileCommand(PathRef File, ProjectInfo *PI = nullptr) const override { 219 auto Cmd = Base->getCompileCommand(File, PI); 220 if (!Cmd || Cmd->CommandLine.empty()) 221 return Cmd; 222 223 llvm::SmallString<128> Driver(Cmd->CommandLine.front()); 224 llvm::sys::fs::make_absolute(Cmd->Directory, Driver); 225 llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.'); 226 auto Key = std::make_pair(Driver.str(), Ext); 227 228 std::vector<std::string> SystemIncludes; 229 { 230 std::lock_guard<std::mutex> Lock(Mu); 231 232 auto It = DriverToIncludesCache.find(Key); 233 if (It != DriverToIncludesCache.end()) 234 SystemIncludes = It->second; 235 else 236 DriverToIncludesCache[Key] = SystemIncludes = 237 extractSystemIncludes(Key.first, Key.second, QueryDriverRegex); 238 } 239 240 return addSystemIncludes(*Cmd, SystemIncludes); 241 } 242 243 private: 244 mutable std::mutex Mu; 245 // Caches includes extracted from a driver. 246 mutable std::map<std::pair<std::string, std::string>, 247 std::vector<std::string>> 248 DriverToIncludesCache; 249 mutable llvm::Regex QueryDriverRegex; 250 251 std::unique_ptr<GlobalCompilationDatabase> Base; 252 CommandChanged::Subscription BaseChanged; 253 }; 254 } // namespace 255 256 std::unique_ptr<GlobalCompilationDatabase> 257 getQueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs, 258 std::unique_ptr<GlobalCompilationDatabase> Base) { 259 assert(Base && "Null base to SystemIncludeExtractor"); 260 if (QueryDriverGlobs.empty()) 261 return Base; 262 return llvm::make_unique<QueryDriverDatabase>(QueryDriverGlobs, 263 std::move(Base)); 264 } 265 266 } // namespace clangd 267 } // namespace clang 268