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, 8> 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(PathRef Driver, llvm::StringRef Lang, 140 llvm::ArrayRef<std::string> CommandLine, 141 const llvm::Regex &QueryDriverRegex) { 142 trace::Span Tracer("Extract system includes and target"); 143 SPAN_ATTACH(Tracer, "driver", Driver); 144 SPAN_ATTACH(Tracer, "lang", Lang); 145 146 if (!QueryDriverRegex.match(Driver)) { 147 vlog("System include extraction: not allowed driver {0}", Driver); 148 return llvm::None; 149 } 150 151 if (!llvm::sys::fs::exists(Driver)) { 152 elog("System include extraction: {0} does not exist.", Driver); 153 return llvm::None; 154 } 155 if (!llvm::sys::fs::can_execute(Driver)) { 156 elog("System include extraction: {0} is not executable.", Driver); 157 return llvm::None; 158 } 159 160 llvm::SmallString<128> StdErrPath; 161 if (auto EC = llvm::sys::fs::createTemporaryFile("system-includes", "clangd", 162 StdErrPath)) { 163 elog("System include extraction: failed to create temporary file with " 164 "error {0}", 165 EC.message()); 166 return llvm::None; 167 } 168 auto CleanUp = llvm::make_scope_exit( 169 [&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); }); 170 171 llvm::Optional<llvm::StringRef> Redirects[] = { 172 {""}, {""}, llvm::StringRef(StdErrPath)}; 173 174 llvm::SmallVector<llvm::StringRef, 12> Args = {Driver, "-E", "-x", 175 Lang, "-", "-v"}; 176 177 // These flags will be preserved 178 const llvm::StringRef FlagsToPreserve[] = { 179 "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"}; 180 // Preserves these flags and their values, either as separate args or with an 181 // equalsbetween them 182 const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"}; 183 184 for (size_t I = 0, E = CommandLine.size(); I < E; ++I) { 185 llvm::StringRef Arg = CommandLine[I]; 186 if (llvm::any_of(FlagsToPreserve, 187 [&Arg](llvm::StringRef S) { return S == Arg; })) { 188 Args.push_back(Arg); 189 } else { 190 const auto *Found = 191 llvm::find_if(ArgsToPreserve, [&Arg](llvm::StringRef S) { 192 return Arg.startswith(S); 193 }); 194 if (Found == std::end(ArgsToPreserve)) 195 continue; 196 Arg = Arg.drop_front(Found->size()); 197 if (Arg.empty() && I + 1 < E) { 198 Args.push_back(CommandLine[I]); 199 Args.push_back(CommandLine[++I]); 200 } else if (Arg.startswith("=")) { 201 Args.push_back(CommandLine[I]); 202 } 203 } 204 } 205 206 if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, /*Env=*/llvm::None, 207 Redirects)) { 208 elog("System include extraction: driver execution failed with return code: " 209 "{0}. Args: ['{1}']", 210 llvm::to_string(RC), llvm::join(Args, "', '")); 211 return llvm::None; 212 } 213 214 auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath); 215 if (!BufOrError) { 216 elog("System include extraction: failed to read {0} with error {1}", 217 StdErrPath, BufOrError.getError().message()); 218 return llvm::None; 219 } 220 221 llvm::Optional<DriverInfo> Info = 222 parseDriverOutput(BufOrError->get()->getBuffer()); 223 if (!Info) 224 return llvm::None; 225 log("System includes extractor: successfully executed {0}\n\tgot includes: " 226 "\"{1}\"\n\tgot target: \"{2}\"", 227 Driver, llvm::join(Info->SystemIncludes, ", "), Info->Target); 228 return Info; 229 } 230 231 tooling::CompileCommand & 232 addSystemIncludes(tooling::CompileCommand &Cmd, 233 llvm::ArrayRef<std::string> SystemIncludes) { 234 for (llvm::StringRef Include : SystemIncludes) { 235 // FIXME(kadircet): This doesn't work when we have "--driver-mode=cl" 236 Cmd.CommandLine.push_back("-isystem"); 237 Cmd.CommandLine.push_back(Include.str()); 238 } 239 return Cmd; 240 } 241 242 tooling::CompileCommand &setTarget(tooling::CompileCommand &Cmd, 243 const std::string &Target) { 244 if (!Target.empty()) { 245 // We do not want to override existing target with extracted one. 246 for (llvm::StringRef Arg : Cmd.CommandLine) { 247 if (Arg == "-target" || Arg.startswith("--target=")) 248 return Cmd; 249 } 250 Cmd.CommandLine.push_back("--target=" + Target); 251 } 252 return Cmd; 253 } 254 255 /// Converts a glob containing only ** or * into a regex. 256 std::string convertGlobToRegex(llvm::StringRef Glob) { 257 std::string RegText; 258 llvm::raw_string_ostream RegStream(RegText); 259 RegStream << '^'; 260 for (size_t I = 0, E = Glob.size(); I < E; ++I) { 261 if (Glob[I] == '*') { 262 if (I + 1 < E && Glob[I + 1] == '*') { 263 // Double star, accept any sequence. 264 RegStream << ".*"; 265 // Also skip the second star. 266 ++I; 267 } else { 268 // Single star, accept any sequence without a slash. 269 RegStream << "[^/]*"; 270 } 271 } else { 272 RegStream << llvm::Regex::escape(Glob.substr(I, 1)); 273 } 274 } 275 RegStream << '$'; 276 RegStream.flush(); 277 return RegText; 278 } 279 280 /// Converts a glob containing only ** or * into a regex. 281 llvm::Regex convertGlobsToRegex(llvm::ArrayRef<std::string> Globs) { 282 assert(!Globs.empty() && "Globs cannot be empty!"); 283 std::vector<std::string> RegTexts; 284 RegTexts.reserve(Globs.size()); 285 for (llvm::StringRef Glob : Globs) 286 RegTexts.push_back(convertGlobToRegex(Glob)); 287 288 llvm::Regex Reg(llvm::join(RegTexts, "|")); 289 assert(Reg.isValid(RegTexts.front()) && 290 "Created an invalid regex from globs"); 291 return Reg; 292 } 293 294 /// Extracts system includes from a trusted driver by parsing the output of 295 /// include search path and appends them to the commands coming from underlying 296 /// compilation database. 297 class QueryDriverDatabase : public GlobalCompilationDatabase { 298 public: 299 QueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs, 300 std::unique_ptr<GlobalCompilationDatabase> Base) 301 : QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)), 302 Base(std::move(Base)) { 303 assert(this->Base); 304 BaseChanged = 305 this->Base->watch([this](const std::vector<std::string> &Changes) { 306 OnCommandChanged.broadcast(Changes); 307 }); 308 } 309 310 llvm::Optional<tooling::CompileCommand> 311 getCompileCommand(PathRef File) const override { 312 auto Cmd = Base->getCompileCommand(File); 313 if (!Cmd || Cmd->CommandLine.empty()) 314 return Cmd; 315 316 llvm::StringRef Lang; 317 for (size_t I = 0, E = Cmd->CommandLine.size(); I < E; ++I) { 318 llvm::StringRef Arg = Cmd->CommandLine[I]; 319 if (Arg == "-x" && I + 1 < E) 320 Lang = Cmd->CommandLine[I + 1]; 321 else if (Arg.startswith("-x")) 322 Lang = Arg.drop_front(2).trim(); 323 } 324 if (Lang.empty()) { 325 llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.'); 326 auto Type = driver::types::lookupTypeForExtension(Ext); 327 if (Type == driver::types::TY_INVALID) { 328 elog("System include extraction: invalid file type for {0}", Ext); 329 return {}; 330 } 331 Lang = driver::types::getTypeName(Type); 332 } 333 334 llvm::SmallString<128> Driver(Cmd->CommandLine.front()); 335 llvm::sys::fs::make_absolute(Cmd->Directory, Driver); 336 337 if (auto Info = 338 QueriedDrivers.get(/*Key=*/(Driver + ":" + Lang).str(), [&] { 339 return extractSystemIncludesAndTarget( 340 Driver, Lang, Cmd->CommandLine, QueryDriverRegex); 341 })) { 342 setTarget(addSystemIncludes(*Cmd, Info->SystemIncludes), Info->Target); 343 } 344 return Cmd; 345 } 346 347 llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override { 348 return Base->getProjectInfo(File); 349 } 350 351 private: 352 // Caches includes extracted from a driver. Key is driver:lang. 353 Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers; 354 llvm::Regex QueryDriverRegex; 355 356 std::unique_ptr<GlobalCompilationDatabase> Base; 357 CommandChanged::Subscription BaseChanged; 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