1 //===--- GlobalCompilationDatabase.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 9 #include "GlobalCompilationDatabase.h" 10 #include "FS.h" 11 #include "SourceCode.h" 12 #include "support/Logger.h" 13 #include "support/Path.h" 14 #include "support/ThreadsafeFS.h" 15 #include "clang/Frontend/CompilerInvocation.h" 16 #include "clang/Tooling/ArgumentsAdjusters.h" 17 #include "clang/Tooling/CompilationDatabase.h" 18 #include "clang/Tooling/CompilationDatabasePluginRegistry.h" 19 #include "clang/Tooling/JSONCompilationDatabase.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/ScopeExit.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/FileUtilities.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/Program.h" 29 #include "llvm/Support/VirtualFileSystem.h" 30 #include <chrono> 31 #include <string> 32 #include <tuple> 33 #include <vector> 34 35 namespace clang { 36 namespace clangd { 37 namespace { 38 39 // Variant of parent_path that operates only on absolute paths. 40 PathRef absoluteParent(PathRef Path) { 41 assert(llvm::sys::path::is_absolute(Path)); 42 #if defined(_WIN32) 43 // llvm::sys says "C:\" is absolute, and its parent is "C:" which is relative. 44 // This unhelpful behavior seems to have been inherited from boost. 45 if (llvm::sys::path::relative_path(Path).empty()) { 46 return PathRef(); 47 } 48 #endif 49 PathRef Result = llvm::sys::path::parent_path(Path); 50 assert(Result.empty() || llvm::sys::path::is_absolute(Result)); 51 return Result; 52 } 53 54 // Runs the given action on all parent directories of filename, starting from 55 // deepest directory and going up to root. Stops whenever action succeeds. 56 void actOnAllParentDirectories(PathRef FileName, 57 llvm::function_ref<bool(PathRef)> Action) { 58 for (auto Path = absoluteParent(FileName); !Path.empty() && !Action(Path); 59 Path = absoluteParent(Path)) 60 ; 61 } 62 63 } // namespace 64 65 tooling::CompileCommand 66 GlobalCompilationDatabase::getFallbackCommand(PathRef File) const { 67 std::vector<std::string> Argv = {"clang"}; 68 // Clang treats .h files as C by default and files without extension as linker 69 // input, resulting in unhelpful diagnostics. 70 // Parsing as Objective C++ is friendly to more cases. 71 auto FileExtension = llvm::sys::path::extension(File); 72 if (FileExtension.empty() || FileExtension == ".h") 73 Argv.push_back("-xobjective-c++-header"); 74 Argv.push_back(std::string(File)); 75 tooling::CompileCommand Cmd(llvm::sys::path::parent_path(File), 76 llvm::sys::path::filename(File), std::move(Argv), 77 /*Output=*/""); 78 Cmd.Heuristic = "clangd fallback"; 79 return Cmd; 80 } 81 82 // Loads and caches the CDB from a single directory. 83 // 84 // This class is threadsafe, which is to say we have independent locks for each 85 // directory we're searching for a CDB. 86 // Loading is deferred until first access. 87 // 88 // The DirectoryBasedCDB keeps a map from path => DirectoryCache. 89 // Typical usage is to: 90 // - 1) determine all the paths that might be searched 91 // - 2) acquire the map lock and get-or-create all the DirectoryCache entries 92 // - 3) release the map lock and query the caches as desired 93 class DirectoryBasedGlobalCompilationDatabase::DirectoryCache { 94 using stopwatch = std::chrono::steady_clock; 95 96 // CachedFile is used to read a CDB file on disk (e.g. compile_commands.json). 97 // It specializes in being able to quickly bail out if the file is unchanged, 98 // which is the common case. 99 // Internally, it stores file metadata so a stat() can verify it's unchanged. 100 // We don't actually cache the content as it's not needed - if the file is 101 // unchanged then the previous CDB is valid. 102 struct CachedFile { 103 CachedFile(llvm::StringRef Parent, llvm::StringRef Rel) { 104 llvm::SmallString<256> Path = Parent; 105 llvm::sys::path::append(Path, Rel); 106 this->Path = Path.str().str(); 107 } 108 std::string Path; 109 size_t Size = NoFileCached; 110 llvm::sys::TimePoint<> ModifiedTime; 111 FileDigest ContentHash; 112 113 static constexpr size_t NoFileCached = -1; 114 115 struct LoadResult { 116 enum { 117 FileNotFound, 118 TransientError, 119 FoundSameData, 120 FoundNewData, 121 } Result; 122 std::unique_ptr<llvm::MemoryBuffer> Buffer; // Set only if FoundNewData 123 }; 124 125 LoadResult load(llvm::vfs::FileSystem &FS, bool HasOldData); 126 }; 127 128 // If we've looked for a CDB here and found none, the time when that happened. 129 // (Atomics make it possible for get() to return without taking a lock) 130 std::atomic<stopwatch::rep> NoCDBAt = { 131 stopwatch::time_point::min().time_since_epoch().count()}; 132 133 // Guards the following cache state. 134 std::mutex Mu; 135 // When was the cache last known to be in sync with disk state? 136 stopwatch::time_point CachePopulatedAt = stopwatch::time_point::min(); 137 // Whether a new CDB has been loaded but not broadcast yet. 138 bool NeedsBroadcast = false; 139 // Last loaded CDB, meaningful if CachePopulatedAt was ever set. 140 // shared_ptr so we can overwrite this when callers are still using the CDB. 141 std::shared_ptr<tooling::CompilationDatabase> CDB; 142 // File metadata for the CDB files we support tracking directly. 143 CachedFile CompileCommandsJson; 144 CachedFile BuildCompileCommandsJson; 145 CachedFile CompileFlagsTxt; 146 // CachedFile member corresponding to CDB. 147 // CDB | ACF | Scenario 148 // null | null | no CDB found, or initial empty cache 149 // set | null | CDB was loaded via generic plugin interface 150 // null | set | found known CDB file, but parsing it failed 151 // set | set | CDB was parsed from a known file 152 CachedFile *ActiveCachedFile = nullptr; 153 154 public: 155 DirectoryCache(llvm::StringRef Path) 156 : CompileCommandsJson(Path, "compile_commands.json"), 157 BuildCompileCommandsJson(Path, "build/compile_commands.json"), 158 CompileFlagsTxt(Path, "compile_flags.txt"), Path(Path) { 159 assert(llvm::sys::path::is_absolute(Path)); 160 } 161 162 // Absolute canonical path that we're the cache for. (Not case-folded). 163 const std::string Path; 164 165 // Get the CDB associated with this directory. 166 // ShouldBroadcast: 167 // - as input, signals whether the caller is willing to broadcast a 168 // newly-discovered CDB. (e.g. to trigger background indexing) 169 // - as output, signals whether the caller should do so. 170 // (If a new CDB is discovered and ShouldBroadcast is false, we mark the 171 // CDB as needing broadcast, and broadcast it next time we can). 172 std::shared_ptr<const tooling::CompilationDatabase> 173 get(const ThreadsafeFS &TFS, bool &ShouldBroadcast, 174 stopwatch::time_point FreshTime, stopwatch::time_point FreshTimeMissing) { 175 // Fast path for common case without taking lock. 176 if (stopwatch::time_point(stopwatch::duration(NoCDBAt.load())) > 177 FreshTimeMissing) { 178 ShouldBroadcast = false; 179 return nullptr; 180 } 181 182 std::lock_guard<std::mutex> Lock(Mu); 183 auto RequestBroadcast = llvm::make_scope_exit([&, OldCDB(CDB.get())] { 184 // If we loaded a new CDB, it should be broadcast at some point. 185 if (CDB != nullptr && CDB.get() != OldCDB) 186 NeedsBroadcast = true; 187 else if (CDB == nullptr) // nothing to broadcast anymore! 188 NeedsBroadcast = false; 189 // If we have something to broadcast, then do so iff allowed. 190 if (!ShouldBroadcast) 191 return; 192 ShouldBroadcast = NeedsBroadcast; 193 NeedsBroadcast = false; 194 }); 195 196 // If our cache is valid, serve from it. 197 if (CachePopulatedAt > FreshTime) 198 return CDB; 199 200 if (/*MayCache=*/load(*TFS.view(/*CWD=*/llvm::None))) { 201 // Use new timestamp, as loading may be slow. 202 CachePopulatedAt = stopwatch::now(); 203 NoCDBAt.store((CDB ? stopwatch::time_point::min() : CachePopulatedAt) 204 .time_since_epoch() 205 .count()); 206 } 207 208 return CDB; 209 } 210 211 private: 212 // Updates `CDB` from disk state. Returns false on failure. 213 bool load(llvm::vfs::FileSystem &FS); 214 }; 215 216 DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::LoadResult 217 DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load( 218 llvm::vfs::FileSystem &FS, bool HasOldData) { 219 auto Stat = FS.status(Path); 220 if (!Stat || !Stat->isRegularFile()) { 221 Size = NoFileCached; 222 ContentHash = {}; 223 return {LoadResult::FileNotFound, nullptr}; 224 } 225 // If both the size and mtime match, presume unchanged without reading. 226 if (HasOldData && Stat->getLastModificationTime() == ModifiedTime && 227 Stat->getSize() == Size) 228 return {LoadResult::FoundSameData, nullptr}; 229 auto Buf = FS.getBufferForFile(Path); 230 if (!Buf || (*Buf)->getBufferSize() != Stat->getSize()) { 231 // Don't clear the cache - possible we're seeing inconsistent size as the 232 // file is being recreated. If it ends up identical later, great! 233 // 234 // This isn't a complete solution: if we see a partial file but stat/read 235 // agree on its size, we're ultimately going to have spurious CDB reloads. 236 // May be worth fixing if generators don't write atomically (CMake does). 237 elog("Failed to read {0}: {1}", Path, 238 Buf ? "size changed" : Buf.getError().message()); 239 return {LoadResult::TransientError, nullptr}; 240 } 241 242 FileDigest NewContentHash = digest((*Buf)->getBuffer()); 243 if (HasOldData && NewContentHash == ContentHash) { 244 // mtime changed but data is the same: avoid rebuilding the CDB. 245 ModifiedTime = Stat->getLastModificationTime(); 246 return {LoadResult::FoundSameData, nullptr}; 247 } 248 249 Size = (*Buf)->getBufferSize(); 250 ModifiedTime = Stat->getLastModificationTime(); 251 ContentHash = NewContentHash; 252 return {LoadResult::FoundNewData, std::move(*Buf)}; 253 } 254 255 // Adapt CDB-loading functions to a common interface for DirectoryCache::load(). 256 static std::unique_ptr<tooling::CompilationDatabase> 257 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) { 258 if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer( 259 Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) { 260 // FS used for expanding response files. 261 // FIXME: ExpandResponseFilesDatabase appears not to provide the usual 262 // thread-safety guarantees, as the access to FS is not locked! 263 // For now, use the real FS, which is known to be threadsafe (if we don't 264 // use/change working directory, which ExpandResponseFilesDatabase doesn't). 265 auto FS = llvm::vfs::getRealFileSystem(); 266 return tooling::inferTargetAndDriverMode( 267 tooling::inferMissingCompileCommands( 268 expandResponseFiles(std::move(CDB), std::move(FS)))); 269 } 270 return nullptr; 271 } 272 static std::unique_ptr<tooling::CompilationDatabase> 273 parseFixed(PathRef Path, llvm::StringRef Data, std::string &Error) { 274 return tooling::FixedCompilationDatabase::loadFromBuffer(Path, Data, Error); 275 } 276 277 bool DirectoryBasedGlobalCompilationDatabase::DirectoryCache::load( 278 llvm::vfs::FileSystem &FS) { 279 dlog("Probing directory {0}", Path); 280 std::string Error; 281 282 // Load from the specially-supported compilation databases (JSON + Fixed). 283 // For these, we know the files they read and cache their metadata so we can 284 // cheaply validate whether they've changed, and hot-reload if they have. 285 // (As a bonus, these are also VFS-clean)! 286 struct CDBFile { 287 CachedFile *File; 288 // Wrapper for {Fixed,JSON}CompilationDatabase::loadFromBuffer. 289 llvm::function_ref<std::unique_ptr<tooling::CompilationDatabase>( 290 PathRef, 291 /*Data*/ llvm::StringRef, 292 /*ErrorMsg*/ std::string &)> 293 Parser; 294 }; 295 for (const auto &Entry : {CDBFile{&CompileCommandsJson, parseJSON}, 296 CDBFile{&BuildCompileCommandsJson, parseJSON}, 297 CDBFile{&CompileFlagsTxt, parseFixed}}) { 298 bool Active = ActiveCachedFile == Entry.File; 299 auto Loaded = Entry.File->load(FS, Active); 300 switch (Loaded.Result) { 301 case CachedFile::LoadResult::FileNotFound: 302 if (Active) { 303 log("Unloaded compilation database from {0}", Entry.File->Path); 304 ActiveCachedFile = nullptr; 305 CDB = nullptr; 306 } 307 // Continue looking at other candidates. 308 break; 309 case CachedFile::LoadResult::TransientError: 310 // File existed but we couldn't read it. Reuse the cache, retry later. 311 return false; // Load again next time. 312 case CachedFile::LoadResult::FoundSameData: 313 assert(Active && "CachedFile may not return 'same data' if !HasOldData"); 314 // This is the critical file, and it hasn't changed. 315 return true; 316 case CachedFile::LoadResult::FoundNewData: 317 // We have a new CDB! 318 CDB = Entry.Parser(Entry.File->Path, Loaded.Buffer->getBuffer(), Error); 319 if (CDB) 320 log("{0} compilation database from {1}", Active ? "Reloaded" : "Loaded", 321 Entry.File->Path); 322 else 323 elog("Failed to load compilation database from {0}: {1}", 324 Entry.File->Path, Error); 325 ActiveCachedFile = Entry.File; 326 return true; 327 } 328 } 329 330 // Fall back to generic handling of compilation databases. 331 // We don't know what files they read, so can't efficiently check whether 332 // they need to be reloaded. So we never do that. 333 // FIXME: the interface doesn't provide a way to virtualize FS access. 334 335 // Don't try these more than once. If we've scanned before, we're done. 336 if (CachePopulatedAt > stopwatch::time_point::min()) 337 return true; 338 for (const auto &Entry : 339 tooling::CompilationDatabasePluginRegistry::entries()) { 340 // Avoid duplicating the special cases handled above. 341 if (Entry.getName() == "fixed-compilation-database" || 342 Entry.getName() == "json-compilation-database") 343 continue; 344 auto Plugin = Entry.instantiate(); 345 if (auto CDB = Plugin->loadFromDirectory(Path, Error)) { 346 log("Loaded compilation database from {0} with plugin {1}", Path, 347 Entry.getName()); 348 this->CDB = std::move(CDB); 349 return true; 350 } 351 // Don't log Error here, it's usually just "couldn't find <file>". 352 } 353 vlog("No compilation database at {0}", Path); 354 return true; 355 } 356 357 DirectoryBasedGlobalCompilationDatabase:: 358 DirectoryBasedGlobalCompilationDatabase(const Options &Opts) 359 : Opts(Opts) { 360 if (Opts.CompileCommandsDir) 361 OnlyDirCache = std::make_unique<DirectoryCache>(*Opts.CompileCommandsDir); 362 } 363 364 DirectoryBasedGlobalCompilationDatabase:: 365 ~DirectoryBasedGlobalCompilationDatabase() = default; 366 367 llvm::Optional<tooling::CompileCommand> 368 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const { 369 CDBLookupRequest Req; 370 Req.FileName = File; 371 Req.ShouldBroadcast = true; 372 auto Now = std::chrono::steady_clock::now(); 373 Req.FreshTime = Now - Opts.RevalidateAfter; 374 Req.FreshTimeMissing = Now - Opts.RevalidateMissingAfter; 375 376 auto Res = lookupCDB(Req); 377 if (!Res) { 378 log("Failed to find compilation database for {0}", File); 379 return llvm::None; 380 } 381 382 auto Candidates = Res->CDB->getCompileCommands(File); 383 if (!Candidates.empty()) 384 return std::move(Candidates.front()); 385 386 return None; 387 } 388 389 // For platforms where paths are case-insensitive (but case-preserving), 390 // we need to do case-insensitive comparisons and use lowercase keys. 391 // FIXME: Make Path a real class with desired semantics instead. 392 // This class is not the only place this problem exists. 393 // FIXME: Mac filesystems default to case-insensitive, but may be sensitive. 394 395 static std::string maybeCaseFoldPath(PathRef Path) { 396 #if defined(_WIN32) || defined(__APPLE__) 397 return Path.lower(); 398 #else 399 return std::string(Path); 400 #endif 401 } 402 403 static bool pathEqual(PathRef A, PathRef B) { 404 #if defined(_WIN32) || defined(__APPLE__) 405 return A.equals_lower(B); 406 #else 407 return A == B; 408 #endif 409 } 410 411 std::vector<DirectoryBasedGlobalCompilationDatabase::DirectoryCache *> 412 DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches( 413 llvm::ArrayRef<llvm::StringRef> Dirs) const { 414 std::vector<std::string> FoldedDirs; 415 FoldedDirs.reserve(Dirs.size()); 416 for (const auto &Dir : Dirs) { 417 #ifndef NDEBUG 418 if (!llvm::sys::path::is_absolute(Dir)) 419 elog("Trying to cache CDB for relative {0}"); 420 #endif 421 FoldedDirs.push_back(maybeCaseFoldPath(Dir)); 422 } 423 424 std::vector<DirectoryCache *> Ret; 425 Ret.reserve(Dirs.size()); 426 427 std::lock_guard<std::mutex> Lock(DirCachesMutex); 428 for (unsigned I = 0; I < Dirs.size(); ++I) 429 Ret.push_back(&DirCaches.try_emplace(FoldedDirs[I], Dirs[I]).first->second); 430 return Ret; 431 } 432 433 llvm::Optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult> 434 DirectoryBasedGlobalCompilationDatabase::lookupCDB( 435 CDBLookupRequest Request) const { 436 assert(llvm::sys::path::is_absolute(Request.FileName) && 437 "path must be absolute"); 438 439 bool ShouldBroadcast = false; 440 DirectoryCache *DirCache = nullptr; 441 std::shared_ptr<const tooling::CompilationDatabase> CDB = nullptr; 442 if (OnlyDirCache) { 443 DirCache = OnlyDirCache.get(); 444 ShouldBroadcast = Request.ShouldBroadcast; 445 CDB = DirCache->get(Opts.TFS, ShouldBroadcast, Request.FreshTime, 446 Request.FreshTimeMissing); 447 } else { 448 // Traverse the canonical version to prevent false positives. i.e.: 449 // src/build/../a.cc can detect a CDB in /src/build if not canonicalized. 450 std::string CanonicalPath = removeDots(Request.FileName); 451 std::vector<llvm::StringRef> SearchDirs; 452 actOnAllParentDirectories(CanonicalPath, [&](PathRef Path) { 453 SearchDirs.push_back(Path); 454 return false; 455 }); 456 for (DirectoryCache *Candidate : getDirectoryCaches(SearchDirs)) { 457 bool CandidateShouldBroadcast = Request.ShouldBroadcast; 458 if ((CDB = Candidate->get(Opts.TFS, CandidateShouldBroadcast, 459 Request.FreshTime, Request.FreshTimeMissing))) { 460 DirCache = Candidate; 461 ShouldBroadcast = CandidateShouldBroadcast; 462 break; 463 } 464 } 465 } 466 467 if (!CDB) 468 return llvm::None; 469 470 CDBLookupResult Result; 471 Result.CDB = std::move(CDB); 472 Result.PI.SourceRoot = DirCache->Path; 473 474 // FIXME: Maybe make the following part async, since this can block 475 // retrieval of compile commands. 476 if (ShouldBroadcast) 477 broadcastCDB(Result); 478 return Result; 479 } 480 481 void DirectoryBasedGlobalCompilationDatabase::broadcastCDB( 482 CDBLookupResult Result) const { 483 vlog("Broadcasting compilation database from {0}", Result.PI.SourceRoot); 484 assert(Result.CDB && "Trying to broadcast an invalid CDB!"); 485 486 std::vector<std::string> AllFiles = Result.CDB->getAllFiles(); 487 // We assume CDB in CompileCommandsDir owns all of its entries, since we don't 488 // perform any search in parent paths whenever it is set. 489 if (OnlyDirCache) { 490 assert(OnlyDirCache->Path == Result.PI.SourceRoot && 491 "Trying to broadcast a CDB outside of CompileCommandsDir!"); 492 OnCommandChanged.broadcast(std::move(AllFiles)); 493 return; 494 } 495 496 // Uniquify all parent directories of all files. 497 llvm::StringMap<bool> DirectoryHasCDB; 498 std::vector<llvm::StringRef> FileAncestors; 499 for (llvm::StringRef File : AllFiles) { 500 actOnAllParentDirectories(File, [&](PathRef Path) { 501 auto It = DirectoryHasCDB.try_emplace(Path); 502 // Already seen this path, and all of its parents. 503 if (!It.second) 504 return true; 505 506 FileAncestors.push_back(It.first->getKey()); 507 return pathEqual(Path, Result.PI.SourceRoot); 508 }); 509 } 510 // Work out which ones have CDBs in them. 511 // Given that we know that CDBs have been moved/generated, don't trust caches. 512 // (This should be rare, so it's OK to add a little latency). 513 constexpr auto IgnoreCache = std::chrono::steady_clock::time_point::max(); 514 auto DirectoryCaches = getDirectoryCaches(FileAncestors); 515 assert(DirectoryCaches.size() == FileAncestors.size()); 516 for (unsigned I = 0; I < DirectoryCaches.size(); ++I) { 517 bool ShouldBroadcast = false; 518 if (DirectoryCaches[I]->get(Opts.TFS, ShouldBroadcast, 519 /*FreshTime=*/IgnoreCache, 520 /*FreshTimeMissing=*/IgnoreCache)) 521 DirectoryHasCDB.find(FileAncestors[I])->setValue(true); 522 } 523 524 std::vector<std::string> GovernedFiles; 525 for (llvm::StringRef File : AllFiles) { 526 // A file is governed by this CDB if lookup for the file would find it. 527 // Independent of whether it has an entry for that file or not. 528 actOnAllParentDirectories(File, [&](PathRef Path) { 529 if (DirectoryHasCDB.lookup(Path)) { 530 if (pathEqual(Path, Result.PI.SourceRoot)) 531 // Make sure listeners always get a canonical path for the file. 532 GovernedFiles.push_back(removeDots(File)); 533 // Stop as soon as we hit a CDB. 534 return true; 535 } 536 return false; 537 }); 538 } 539 540 OnCommandChanged.broadcast(std::move(GovernedFiles)); 541 } 542 543 llvm::Optional<ProjectInfo> 544 DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const { 545 CDBLookupRequest Req; 546 Req.FileName = File; 547 Req.ShouldBroadcast = false; 548 Req.FreshTime = Req.FreshTimeMissing = 549 std::chrono::steady_clock::time_point::min(); 550 auto Res = lookupCDB(Req); 551 if (!Res) 552 return llvm::None; 553 return Res->PI; 554 } 555 556 OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base, 557 std::vector<std::string> FallbackFlags, 558 tooling::ArgumentsAdjuster Adjuster) 559 : DelegatingCDB(Base), ArgsAdjuster(std::move(Adjuster)), 560 FallbackFlags(std::move(FallbackFlags)) {} 561 562 llvm::Optional<tooling::CompileCommand> 563 OverlayCDB::getCompileCommand(PathRef File) const { 564 llvm::Optional<tooling::CompileCommand> Cmd; 565 { 566 std::lock_guard<std::mutex> Lock(Mutex); 567 auto It = Commands.find(removeDots(File)); 568 if (It != Commands.end()) 569 Cmd = It->second; 570 } 571 if (!Cmd) 572 Cmd = DelegatingCDB::getCompileCommand(File); 573 if (!Cmd) 574 return llvm::None; 575 if (ArgsAdjuster) 576 Cmd->CommandLine = ArgsAdjuster(Cmd->CommandLine, Cmd->Filename); 577 return Cmd; 578 } 579 580 tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const { 581 auto Cmd = DelegatingCDB::getFallbackCommand(File); 582 std::lock_guard<std::mutex> Lock(Mutex); 583 Cmd.CommandLine.insert(Cmd.CommandLine.end(), FallbackFlags.begin(), 584 FallbackFlags.end()); 585 if (ArgsAdjuster) 586 Cmd.CommandLine = ArgsAdjuster(Cmd.CommandLine, Cmd.Filename); 587 return Cmd; 588 } 589 590 void OverlayCDB::setCompileCommand( 591 PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) { 592 // We store a canonical version internally to prevent mismatches between set 593 // and get compile commands. Also it assures clients listening to broadcasts 594 // doesn't receive different names for the same file. 595 std::string CanonPath = removeDots(File); 596 { 597 std::unique_lock<std::mutex> Lock(Mutex); 598 if (Cmd) 599 Commands[CanonPath] = std::move(*Cmd); 600 else 601 Commands.erase(CanonPath); 602 } 603 OnCommandChanged.broadcast({CanonPath}); 604 } 605 606 DelegatingCDB::DelegatingCDB(const GlobalCompilationDatabase *Base) 607 : Base(Base) { 608 if (Base) 609 BaseChanged = Base->watch([this](const std::vector<std::string> Changes) { 610 OnCommandChanged.broadcast(Changes); 611 }); 612 } 613 614 DelegatingCDB::DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base) 615 : DelegatingCDB(Base.get()) { 616 BaseOwner = std::move(Base); 617 } 618 619 llvm::Optional<tooling::CompileCommand> 620 DelegatingCDB::getCompileCommand(PathRef File) const { 621 if (!Base) 622 return llvm::None; 623 return Base->getCompileCommand(File); 624 } 625 626 llvm::Optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const { 627 if (!Base) 628 return llvm::None; 629 return Base->getProjectInfo(File); 630 } 631 632 tooling::CompileCommand DelegatingCDB::getFallbackCommand(PathRef File) const { 633 if (!Base) 634 return GlobalCompilationDatabase::getFallbackCommand(File); 635 return Base->getFallbackCommand(File); 636 } 637 638 } // namespace clangd 639 } // namespace clang 640