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 "CompileCommands.h" 33 #include "GlobalCompilationDatabase.h" 34 #include "support/Logger.h" 35 #include "support/Path.h" 36 #include "support/Trace.h" 37 #include "clang/Basic/Diagnostic.h" 38 #include "clang/Basic/TargetInfo.h" 39 #include "clang/Basic/TargetOptions.h" 40 #include "clang/Driver/Types.h" 41 #include "clang/Tooling/CompilationDatabase.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/Support/FileSystem.h" 47 #include "llvm/Support/MemoryBuffer.h" 48 #include "llvm/Support/Path.h" 49 #include "llvm/Support/Program.h" 50 #include "llvm/Support/Regex.h" 51 #include "llvm/Support/ScopedPrinter.h" 52 #include <algorithm> 53 #include <iterator> 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[] = {{""}, {""}, StdErrPath.str()}; 179 180 llvm::SmallVector<llvm::StringRef> Args = {Driver, "-E", "-x", 181 Lang, "-", "-v"}; 182 183 // These flags will be preserved 184 const llvm::StringRef FlagsToPreserve[] = { 185 "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"}; 186 // Preserves these flags and their values, either as separate args or with an 187 // equalsbetween them 188 const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"}; 189 190 for (size_t I = 0, E = CommandLine.size(); I < E; ++I) { 191 llvm::StringRef Arg = CommandLine[I]; 192 if (llvm::any_of(FlagsToPreserve, 193 [&Arg](llvm::StringRef S) { return S == Arg; })) { 194 Args.push_back(Arg); 195 } else { 196 const auto *Found = 197 llvm::find_if(ArgsToPreserve, [&Arg](llvm::StringRef S) { 198 return Arg.startswith(S); 199 }); 200 if (Found == std::end(ArgsToPreserve)) 201 continue; 202 Arg = Arg.drop_front(Found->size()); 203 if (Arg.empty() && I + 1 < E) { 204 Args.push_back(CommandLine[I]); 205 Args.push_back(CommandLine[++I]); 206 } else if (Arg.startswith("=")) { 207 Args.push_back(CommandLine[I]); 208 } 209 } 210 } 211 212 std::string ErrMsg; 213 if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, /*Env=*/llvm::None, 214 Redirects, /*SecondsToWait=*/0, 215 /*MemoryLimit=*/0, &ErrMsg)) { 216 elog("System include extraction: driver execution failed with return code: " 217 "{0} - '{1}'. Args: [{2}]", 218 llvm::to_string(RC), ErrMsg, printArgv(Args)); 219 return llvm::None; 220 } 221 222 auto BufOrError = llvm::MemoryBuffer::getFile(StdErrPath); 223 if (!BufOrError) { 224 elog("System include extraction: failed to read {0} with error {1}", 225 StdErrPath, BufOrError.getError().message()); 226 return llvm::None; 227 } 228 229 llvm::Optional<DriverInfo> Info = 230 parseDriverOutput(BufOrError->get()->getBuffer()); 231 if (!Info) 232 return llvm::None; 233 log("System includes extractor: successfully executed {0}\n\tgot includes: " 234 "\"{1}\"\n\tgot target: \"{2}\"", 235 Driver, llvm::join(Info->SystemIncludes, ", "), Info->Target); 236 return Info; 237 } 238 239 tooling::CompileCommand & 240 addSystemIncludes(tooling::CompileCommand &Cmd, 241 llvm::ArrayRef<std::string> SystemIncludes) { 242 std::vector<std::string> ToAppend; 243 for (llvm::StringRef Include : SystemIncludes) { 244 // FIXME(kadircet): This doesn't work when we have "--driver-mode=cl" 245 ToAppend.push_back("-isystem"); 246 ToAppend.push_back(Include.str()); 247 } 248 if (!ToAppend.empty()) { 249 // Just append when `--` isn't present. 250 auto InsertAt = llvm::find(Cmd.CommandLine, "--"); 251 Cmd.CommandLine.insert(InsertAt, std::make_move_iterator(ToAppend.begin()), 252 std::make_move_iterator(ToAppend.end())); 253 } 254 return Cmd; 255 } 256 257 tooling::CompileCommand &setTarget(tooling::CompileCommand &Cmd, 258 const std::string &Target) { 259 if (!Target.empty()) { 260 // We do not want to override existing target with extracted one. 261 for (llvm::StringRef Arg : Cmd.CommandLine) { 262 if (Arg == "-target" || Arg.startswith("--target=")) 263 return Cmd; 264 } 265 // Just append when `--` isn't present. 266 auto InsertAt = llvm::find(Cmd.CommandLine, "--"); 267 Cmd.CommandLine.insert(InsertAt, "--target=" + Target); 268 } 269 return Cmd; 270 } 271 272 /// Converts a glob containing only ** or * into a regex. 273 std::string convertGlobToRegex(llvm::StringRef Glob) { 274 std::string RegText; 275 llvm::raw_string_ostream RegStream(RegText); 276 RegStream << '^'; 277 for (size_t I = 0, E = Glob.size(); I < E; ++I) { 278 if (Glob[I] == '*') { 279 if (I + 1 < E && Glob[I + 1] == '*') { 280 // Double star, accept any sequence. 281 RegStream << ".*"; 282 // Also skip the second star. 283 ++I; 284 } else { 285 // Single star, accept any sequence without a slash. 286 RegStream << "[^/]*"; 287 } 288 } else if (llvm::sys::path::is_separator(Glob[I]) && 289 llvm::sys::path::is_separator('/') && 290 llvm::sys::path::is_separator('\\')) { 291 RegStream << R"([/\\])"; // Accept either slash on windows. 292 } else { 293 RegStream << llvm::Regex::escape(Glob.substr(I, 1)); 294 } 295 } 296 RegStream << '$'; 297 RegStream.flush(); 298 return RegText; 299 } 300 301 /// Converts a glob containing only ** or * into a regex. 302 llvm::Regex convertGlobsToRegex(llvm::ArrayRef<std::string> Globs) { 303 assert(!Globs.empty() && "Globs cannot be empty!"); 304 std::vector<std::string> RegTexts; 305 RegTexts.reserve(Globs.size()); 306 for (llvm::StringRef Glob : Globs) 307 RegTexts.push_back(convertGlobToRegex(Glob)); 308 309 // Tempting to pass IgnoreCase, but we don't know the FS sensitivity. 310 llvm::Regex Reg(llvm::join(RegTexts, "|")); 311 assert(Reg.isValid(RegTexts.front()) && 312 "Created an invalid regex from globs"); 313 return Reg; 314 } 315 316 /// Extracts system includes from a trusted driver by parsing the output of 317 /// include search path and appends them to the commands coming from underlying 318 /// compilation database. 319 class QueryDriverDatabase : public DelegatingCDB { 320 public: 321 QueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs, 322 std::unique_ptr<GlobalCompilationDatabase> Base) 323 : DelegatingCDB(std::move(Base)), 324 QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)) {} 325 326 llvm::Optional<tooling::CompileCommand> 327 getCompileCommand(PathRef File) const override { 328 auto Cmd = DelegatingCDB::getCompileCommand(File); 329 if (!Cmd || Cmd->CommandLine.empty()) 330 return Cmd; 331 332 llvm::StringRef Lang; 333 for (size_t I = 0, E = Cmd->CommandLine.size(); I < E; ++I) { 334 llvm::StringRef Arg = Cmd->CommandLine[I]; 335 if (Arg == "-x" && I + 1 < E) 336 Lang = Cmd->CommandLine[I + 1]; 337 else if (Arg.startswith("-x")) 338 Lang = Arg.drop_front(2).trim(); 339 } 340 if (Lang.empty()) { 341 llvm::StringRef Ext = llvm::sys::path::extension(File).trim('.'); 342 auto Type = driver::types::lookupTypeForExtension(Ext); 343 if (Type == driver::types::TY_INVALID) { 344 elog("System include extraction: invalid file type for {0}", Ext); 345 return {}; 346 } 347 Lang = driver::types::getTypeName(Type); 348 } 349 350 llvm::SmallString<128> Driver(Cmd->CommandLine.front()); 351 if (llvm::any_of(Driver, 352 [](char C) { return llvm::sys::path::is_separator(C); })) 353 // Driver is a not a single executable name but instead a path (either 354 // relative or absolute). 355 llvm::sys::fs::make_absolute(Cmd->Directory, Driver); 356 357 if (auto Info = 358 QueriedDrivers.get(/*Key=*/(Driver + ":" + Lang).str(), [&] { 359 return extractSystemIncludesAndTarget( 360 Driver, Lang, Cmd->CommandLine, QueryDriverRegex); 361 })) { 362 setTarget(addSystemIncludes(*Cmd, Info->SystemIncludes), Info->Target); 363 } 364 return Cmd; 365 } 366 367 private: 368 // Caches includes extracted from a driver. Key is driver:lang. 369 Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers; 370 llvm::Regex QueryDriverRegex; 371 }; 372 } // namespace 373 374 std::unique_ptr<GlobalCompilationDatabase> 375 getQueryDriverDatabase(llvm::ArrayRef<std::string> QueryDriverGlobs, 376 std::unique_ptr<GlobalCompilationDatabase> Base) { 377 assert(Base && "Null base to SystemIncludeExtractor"); 378 if (QueryDriverGlobs.empty()) 379 return Base; 380 return std::make_unique<QueryDriverDatabase>(QueryDriverGlobs, 381 std::move(Base)); 382 } 383 384 } // namespace clangd 385 } // namespace clang 386