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 "Config.h"
11 #include "FS.h"
12 #include "SourceCode.h"
13 #include "support/Logger.h"
14 #include "support/Path.h"
15 #include "support/Threading.h"
16 #include "support/ThreadsafeFS.h"
17 #include "clang/Frontend/CompilerInvocation.h"
18 #include "clang/Tooling/ArgumentsAdjusters.h"
19 #include "clang/Tooling/CompilationDatabase.h"
20 #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
21 #include "clang/Tooling/JSONCompilationDatabase.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/ScopeExit.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/VirtualFileSystem.h"
34 #include <atomic>
35 #include <chrono>
36 #include <condition_variable>
37 #include <mutex>
38 #include <string>
39 #include <tuple>
40 #include <vector>
41 
42 namespace clang {
43 namespace clangd {
44 namespace {
45 
46 // Runs the given action on all parent directories of filename, starting from
47 // deepest directory and going up to root. Stops whenever action succeeds.
48 void actOnAllParentDirectories(PathRef FileName,
49                                llvm::function_ref<bool(PathRef)> Action) {
50   for (auto Path = absoluteParent(FileName); !Path.empty() && !Action(Path);
51        Path = absoluteParent(Path))
52     ;
53 }
54 
55 } // namespace
56 
57 tooling::CompileCommand
58 GlobalCompilationDatabase::getFallbackCommand(PathRef File) const {
59   std::vector<std::string> Argv = {"clang"};
60   // Clang treats .h files as C by default and files without extension as linker
61   // input, resulting in unhelpful diagnostics.
62   // Parsing as Objective C++ is friendly to more cases.
63   auto FileExtension = llvm::sys::path::extension(File);
64   if (FileExtension.empty() || FileExtension == ".h")
65     Argv.push_back("-xobjective-c++-header");
66   Argv.push_back(std::string(File));
67   tooling::CompileCommand Cmd(llvm::sys::path::parent_path(File),
68                               llvm::sys::path::filename(File), std::move(Argv),
69                               /*Output=*/"");
70   Cmd.Heuristic = "clangd fallback";
71   return Cmd;
72 }
73 
74 // Loads and caches the CDB from a single directory.
75 //
76 // This class is threadsafe, which is to say we have independent locks for each
77 // directory we're searching for a CDB.
78 // Loading is deferred until first access.
79 //
80 // The DirectoryBasedCDB keeps a map from path => DirectoryCache.
81 // Typical usage is to:
82 //  - 1) determine all the paths that might be searched
83 //  - 2) acquire the map lock and get-or-create all the DirectoryCache entries
84 //  - 3) release the map lock and query the caches as desired
85 class DirectoryBasedGlobalCompilationDatabase::DirectoryCache {
86   using stopwatch = std::chrono::steady_clock;
87 
88   // CachedFile is used to read a CDB file on disk (e.g. compile_commands.json).
89   // It specializes in being able to quickly bail out if the file is unchanged,
90   // which is the common case.
91   // Internally, it stores file metadata so a stat() can verify it's unchanged.
92   // We don't actually cache the content as it's not needed - if the file is
93   // unchanged then the previous CDB is valid.
94   struct CachedFile {
95     CachedFile(llvm::StringRef Parent, llvm::StringRef Rel) {
96       llvm::SmallString<256> Path = Parent;
97       llvm::sys::path::append(Path, Rel);
98       this->Path = Path.str().str();
99     }
100     std::string Path;
101     size_t Size = NoFileCached;
102     llvm::sys::TimePoint<> ModifiedTime;
103     FileDigest ContentHash;
104 
105     static constexpr size_t NoFileCached = -1;
106 
107     struct LoadResult {
108       enum {
109         FileNotFound,
110         TransientError,
111         FoundSameData,
112         FoundNewData,
113       } Result;
114       std::unique_ptr<llvm::MemoryBuffer> Buffer; // Set only if FoundNewData
115     };
116 
117     LoadResult load(llvm::vfs::FileSystem &FS, bool HasOldData);
118   };
119 
120   // If we've looked for a CDB here and found none, the time when that happened.
121   // (Atomics make it possible for get() to return without taking a lock)
122   std::atomic<stopwatch::rep> NoCDBAt = {
123       stopwatch::time_point::min().time_since_epoch().count()};
124 
125   // Guards the following cache state.
126   std::mutex Mu;
127   // When was the cache last known to be in sync with disk state?
128   stopwatch::time_point CachePopulatedAt = stopwatch::time_point::min();
129   // Whether a new CDB has been loaded but not broadcast yet.
130   bool NeedsBroadcast = false;
131   // Last loaded CDB, meaningful if CachePopulatedAt was ever set.
132   // shared_ptr so we can overwrite this when callers are still using the CDB.
133   std::shared_ptr<tooling::CompilationDatabase> CDB;
134   // File metadata for the CDB files we support tracking directly.
135   CachedFile CompileCommandsJson;
136   CachedFile BuildCompileCommandsJson;
137   CachedFile CompileFlagsTxt;
138   // CachedFile member corresponding to CDB.
139   //   CDB  | ACF  | Scenario
140   //   null | null | no CDB found, or initial empty cache
141   //   set  | null | CDB was loaded via generic plugin interface
142   //   null | set  | found known CDB file, but parsing it failed
143   //   set  | set  | CDB was parsed from a known file
144   CachedFile *ActiveCachedFile = nullptr;
145 
146 public:
147   DirectoryCache(llvm::StringRef Path)
148       : CompileCommandsJson(Path, "compile_commands.json"),
149         BuildCompileCommandsJson(Path, "build/compile_commands.json"),
150         CompileFlagsTxt(Path, "compile_flags.txt"), Path(Path) {
151     assert(llvm::sys::path::is_absolute(Path));
152   }
153 
154   // Absolute canonical path that we're the cache for. (Not case-folded).
155   const std::string Path;
156 
157   // Get the CDB associated with this directory.
158   // ShouldBroadcast:
159   //  - as input, signals whether the caller is willing to broadcast a
160   //    newly-discovered CDB. (e.g. to trigger background indexing)
161   //  - as output, signals whether the caller should do so.
162   // (If a new CDB is discovered and ShouldBroadcast is false, we mark the
163   // CDB as needing broadcast, and broadcast it next time we can).
164   std::shared_ptr<const tooling::CompilationDatabase>
165   get(const ThreadsafeFS &TFS, bool &ShouldBroadcast,
166       stopwatch::time_point FreshTime, stopwatch::time_point FreshTimeMissing) {
167     // Fast path for common case without taking lock.
168     if (stopwatch::time_point(stopwatch::duration(NoCDBAt.load())) >
169         FreshTimeMissing) {
170       ShouldBroadcast = false;
171       return nullptr;
172     }
173 
174     std::lock_guard<std::mutex> Lock(Mu);
175     auto RequestBroadcast = llvm::make_scope_exit([&, OldCDB(CDB.get())] {
176       // If we loaded a new CDB, it should be broadcast at some point.
177       if (CDB != nullptr && CDB.get() != OldCDB)
178         NeedsBroadcast = true;
179       else if (CDB == nullptr) // nothing to broadcast anymore!
180         NeedsBroadcast = false;
181       // If we have something to broadcast, then do so iff allowed.
182       if (!ShouldBroadcast)
183         return;
184       ShouldBroadcast = NeedsBroadcast;
185       NeedsBroadcast = false;
186     });
187 
188     // If our cache is valid, serve from it.
189     if (CachePopulatedAt > FreshTime)
190       return CDB;
191 
192     if (/*MayCache=*/load(*TFS.view(/*CWD=*/llvm::None))) {
193       // Use new timestamp, as loading may be slow.
194       CachePopulatedAt = stopwatch::now();
195       NoCDBAt.store((CDB ? stopwatch::time_point::min() : CachePopulatedAt)
196                         .time_since_epoch()
197                         .count());
198     }
199 
200     return CDB;
201   }
202 
203 private:
204   // Updates `CDB` from disk state. Returns false on failure.
205   bool load(llvm::vfs::FileSystem &FS);
206 };
207 
208 DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::LoadResult
209 DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
210     llvm::vfs::FileSystem &FS, bool HasOldData) {
211   auto Stat = FS.status(Path);
212   if (!Stat || !Stat->isRegularFile()) {
213     Size = NoFileCached;
214     ContentHash = {};
215     return {LoadResult::FileNotFound, nullptr};
216   }
217   // If both the size and mtime match, presume unchanged without reading.
218   if (HasOldData && Stat->getLastModificationTime() == ModifiedTime &&
219       Stat->getSize() == Size)
220     return {LoadResult::FoundSameData, nullptr};
221   auto Buf = FS.getBufferForFile(Path);
222   if (!Buf || (*Buf)->getBufferSize() != Stat->getSize()) {
223     // Don't clear the cache - possible we're seeing inconsistent size as the
224     // file is being recreated. If it ends up identical later, great!
225     //
226     // This isn't a complete solution: if we see a partial file but stat/read
227     // agree on its size, we're ultimately going to have spurious CDB reloads.
228     // May be worth fixing if generators don't write atomically (CMake does).
229     elog("Failed to read {0}: {1}", Path,
230          Buf ? "size changed" : Buf.getError().message());
231     return {LoadResult::TransientError, nullptr};
232   }
233 
234   FileDigest NewContentHash = digest((*Buf)->getBuffer());
235   if (HasOldData && NewContentHash == ContentHash) {
236     // mtime changed but data is the same: avoid rebuilding the CDB.
237     ModifiedTime = Stat->getLastModificationTime();
238     return {LoadResult::FoundSameData, nullptr};
239   }
240 
241   Size = (*Buf)->getBufferSize();
242   ModifiedTime = Stat->getLastModificationTime();
243   ContentHash = NewContentHash;
244   return {LoadResult::FoundNewData, std::move(*Buf)};
245 }
246 
247 // Adapt CDB-loading functions to a common interface for DirectoryCache::load().
248 static std::unique_ptr<tooling::CompilationDatabase>
249 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
250   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
251           Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
252     // FS used for expanding response files.
253     // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
254     // thread-safety guarantees, as the access to FS is not locked!
255     // For now, use the real FS, which is known to be threadsafe (if we don't
256     // use/change working directory, which ExpandResponseFilesDatabase doesn't).
257     auto FS = llvm::vfs::getRealFileSystem();
258     return tooling::inferTargetAndDriverMode(
259         tooling::inferMissingCompileCommands(
260             expandResponseFiles(std::move(CDB), std::move(FS))));
261   }
262   return nullptr;
263 }
264 static std::unique_ptr<tooling::CompilationDatabase>
265 parseFixed(PathRef Path, llvm::StringRef Data, std::string &Error) {
266   return tooling::FixedCompilationDatabase::loadFromBuffer(
267       llvm::sys::path::parent_path(Path), Data, Error);
268 }
269 
270 bool DirectoryBasedGlobalCompilationDatabase::DirectoryCache::load(
271     llvm::vfs::FileSystem &FS) {
272   dlog("Probing directory {0}", Path);
273   std::string Error;
274 
275   // Load from the specially-supported compilation databases (JSON + Fixed).
276   // For these, we know the files they read and cache their metadata so we can
277   // cheaply validate whether they've changed, and hot-reload if they have.
278   // (As a bonus, these are also VFS-clean)!
279   struct {
280     CachedFile *File;
281     // Wrapper for {Fixed,JSON}CompilationDatabase::loadFromBuffer.
282     llvm::function_ref<std::unique_ptr<tooling::CompilationDatabase>(
283         PathRef,
284         /*Data*/ llvm::StringRef,
285         /*ErrorMsg*/ std::string &)>
286         Parser;
287   } Files[] = {
288       {&CompileCommandsJson, parseJSON},
289       {&BuildCompileCommandsJson, parseJSON},
290       {&CompileFlagsTxt, parseFixed},
291   };
292   for (const auto &Entry : Files) {
293     bool Active = ActiveCachedFile == Entry.File;
294     auto Loaded = Entry.File->load(FS, Active);
295     switch (Loaded.Result) {
296     case CachedFile::LoadResult::FileNotFound:
297       if (Active) {
298         log("Unloaded compilation database from {0}", Entry.File->Path);
299         ActiveCachedFile = nullptr;
300         CDB = nullptr;
301       }
302       // Continue looking at other candidates.
303       break;
304     case CachedFile::LoadResult::TransientError:
305       // File existed but we couldn't read it. Reuse the cache, retry later.
306       return false; // Load again next time.
307     case CachedFile::LoadResult::FoundSameData:
308       assert(Active && "CachedFile may not return 'same data' if !HasOldData");
309       // This is the critical file, and it hasn't changed.
310       return true;
311     case CachedFile::LoadResult::FoundNewData:
312       // We have a new CDB!
313       CDB = Entry.Parser(Entry.File->Path, Loaded.Buffer->getBuffer(), Error);
314       if (CDB)
315         log("{0} compilation database from {1}", Active ? "Reloaded" : "Loaded",
316             Entry.File->Path);
317       else
318         elog("Failed to load compilation database from {0}: {1}",
319              Entry.File->Path, Error);
320       ActiveCachedFile = Entry.File;
321       return true;
322     }
323   }
324 
325   // Fall back to generic handling of compilation databases.
326   // We don't know what files they read, so can't efficiently check whether
327   // they need to be reloaded. So we never do that.
328   // FIXME: the interface doesn't provide a way to virtualize FS access.
329 
330   // Don't try these more than once. If we've scanned before, we're done.
331   if (CachePopulatedAt > stopwatch::time_point::min())
332     return true;
333   for (const auto &Entry :
334        tooling::CompilationDatabasePluginRegistry::entries()) {
335     // Avoid duplicating the special cases handled above.
336     if (Entry.getName() == "fixed-compilation-database" ||
337         Entry.getName() == "json-compilation-database")
338       continue;
339     auto Plugin = Entry.instantiate();
340     if (auto CDB = Plugin->loadFromDirectory(Path, Error)) {
341       log("Loaded compilation database from {0} with plugin {1}", Path,
342           Entry.getName());
343       this->CDB = std::move(CDB);
344       return true;
345     }
346     // Don't log Error here, it's usually just "couldn't find <file>".
347   }
348   dlog("No compilation database at {0}", Path);
349   return true;
350 }
351 
352 DirectoryBasedGlobalCompilationDatabase::
353     DirectoryBasedGlobalCompilationDatabase(const Options &Opts)
354     : Opts(Opts), Broadcaster(std::make_unique<BroadcastThread>(*this)) {
355   if (!this->Opts.ContextProvider)
356     this->Opts.ContextProvider = [](llvm::StringRef) {
357       return Context::current().clone();
358     };
359 }
360 
361 DirectoryBasedGlobalCompilationDatabase::
362     ~DirectoryBasedGlobalCompilationDatabase() = default;
363 
364 llvm::Optional<tooling::CompileCommand>
365 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
366   CDBLookupRequest Req;
367   Req.FileName = File;
368   Req.ShouldBroadcast = true;
369   auto Now = std::chrono::steady_clock::now();
370   Req.FreshTime = Now - Opts.RevalidateAfter;
371   Req.FreshTimeMissing = Now - Opts.RevalidateMissingAfter;
372 
373   auto Res = lookupCDB(Req);
374   if (!Res) {
375     log("Failed to find compilation database for {0}", File);
376     return llvm::None;
377   }
378 
379   auto Candidates = Res->CDB->getCompileCommands(File);
380   if (!Candidates.empty())
381     return std::move(Candidates.front());
382 
383   return None;
384 }
385 
386 std::vector<DirectoryBasedGlobalCompilationDatabase::DirectoryCache *>
387 DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches(
388     llvm::ArrayRef<llvm::StringRef> Dirs) const {
389   std::vector<std::string> FoldedDirs;
390   FoldedDirs.reserve(Dirs.size());
391   for (const auto &Dir : Dirs) {
392 #ifndef NDEBUG
393     if (!llvm::sys::path::is_absolute(Dir))
394       elog("Trying to cache CDB for relative {0}");
395 #endif
396     FoldedDirs.push_back(maybeCaseFoldPath(Dir));
397   }
398 
399   std::vector<DirectoryCache *> Ret;
400   Ret.reserve(Dirs.size());
401 
402   std::lock_guard<std::mutex> Lock(DirCachesMutex);
403   for (unsigned I = 0; I < Dirs.size(); ++I)
404     Ret.push_back(&DirCaches.try_emplace(FoldedDirs[I], Dirs[I]).first->second);
405   return Ret;
406 }
407 
408 llvm::Optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
409 DirectoryBasedGlobalCompilationDatabase::lookupCDB(
410     CDBLookupRequest Request) const {
411   assert(llvm::sys::path::is_absolute(Request.FileName) &&
412          "path must be absolute");
413 
414   std::string Storage;
415   std::vector<llvm::StringRef> SearchDirs;
416   if (Opts.CompileCommandsDir) // FIXME: unify this case with config.
417     SearchDirs = {Opts.CompileCommandsDir.getValue()};
418   else {
419     WithContext WithProvidedContext(Opts.ContextProvider(Request.FileName));
420     const auto &Spec = Config::current().CompileFlags.CDBSearch;
421     switch (Spec.Policy) {
422     case Config::CDBSearchSpec::NoCDBSearch:
423       return llvm::None;
424     case Config::CDBSearchSpec::FixedDir:
425       Storage = Spec.FixedCDBPath.getValue();
426       SearchDirs = {Storage};
427       break;
428     case Config::CDBSearchSpec::Ancestors:
429       // Traverse the canonical version to prevent false positives. i.e.:
430       // src/build/../a.cc can detect a CDB in /src/build if not
431       // canonicalized.
432       Storage = removeDots(Request.FileName);
433       actOnAllParentDirectories(Storage, [&](llvm::StringRef Dir) {
434         SearchDirs.push_back(Dir);
435         return false;
436       });
437     }
438   }
439 
440   std::shared_ptr<const tooling::CompilationDatabase> CDB = nullptr;
441   bool ShouldBroadcast = false;
442   DirectoryCache *DirCache = nullptr;
443   for (DirectoryCache *Candidate : getDirectoryCaches(SearchDirs)) {
444     bool CandidateShouldBroadcast = Request.ShouldBroadcast;
445     if ((CDB = Candidate->get(Opts.TFS, CandidateShouldBroadcast,
446                               Request.FreshTime, Request.FreshTimeMissing))) {
447       DirCache = Candidate;
448       ShouldBroadcast = CandidateShouldBroadcast;
449       break;
450     }
451   }
452 
453   if (!CDB)
454     return llvm::None;
455 
456   CDBLookupResult Result;
457   Result.CDB = std::move(CDB);
458   Result.PI.SourceRoot = DirCache->Path;
459 
460   if (ShouldBroadcast)
461     broadcastCDB(Result);
462   return Result;
463 }
464 
465 // The broadcast thread announces files with new compile commands to the world.
466 // Primarily this is used to enqueue them for background indexing.
467 //
468 // It's on a separate thread because:
469 //  - otherwise it would block the first parse of the initial file
470 //  - we need to enumerate all files in the CDB, of which there are many
471 //  - we (will) have to evaluate config for every file in the CDB, which is slow
472 class DirectoryBasedGlobalCompilationDatabase::BroadcastThread {
473   class Filter;
474   DirectoryBasedGlobalCompilationDatabase &Parent;
475 
476   std::mutex Mu;
477   std::condition_variable CV;
478   // Shutdown flag (CV is notified after writing).
479   // This is atomic so that broadcasts can also observe it and abort early.
480   std::atomic<bool> ShouldStop = {false};
481   struct Task {
482     CDBLookupResult Lookup;
483     Context Ctx;
484   };
485   std::deque<Task> Queue;
486   llvm::Optional<Task> ActiveTask;
487   std::thread Thread; // Must be last member.
488 
489   // Thread body: this is just the basic queue procesing boilerplate.
490   void run() {
491     std::unique_lock<std::mutex> Lock(Mu);
492     while (true) {
493       bool Stopping = false;
494       CV.wait(Lock, [&] {
495         return (Stopping = ShouldStop.load(std::memory_order_acquire)) ||
496                !Queue.empty();
497       });
498       if (Stopping) {
499         Queue.clear();
500         CV.notify_all();
501         return;
502       }
503       ActiveTask = std::move(Queue.front());
504       Queue.pop_front();
505 
506       Lock.unlock();
507       {
508         WithContext WithCtx(std::move(ActiveTask->Ctx));
509         process(ActiveTask->Lookup);
510       }
511       Lock.lock();
512       ActiveTask.reset();
513       CV.notify_all();
514     }
515   }
516 
517   // Inspects a new CDB and broadcasts the files it owns.
518   void process(const CDBLookupResult &T);
519 
520 public:
521   BroadcastThread(DirectoryBasedGlobalCompilationDatabase &Parent)
522       : Parent(Parent), Thread([this] { run(); }) {}
523 
524   void enqueue(CDBLookupResult Lookup) {
525     {
526       assert(!Lookup.PI.SourceRoot.empty());
527       std::lock_guard<std::mutex> Lock(Mu);
528       // New CDB takes precedence over any queued one for the same directory.
529       llvm::erase_if(Queue, [&](const Task &T) {
530         return T.Lookup.PI.SourceRoot == Lookup.PI.SourceRoot;
531       });
532       Queue.push_back({std::move(Lookup), Context::current().clone()});
533     }
534     CV.notify_all();
535   }
536 
537   bool blockUntilIdle(Deadline Timeout) {
538     std::unique_lock<std::mutex> Lock(Mu);
539     return wait(Lock, CV, Timeout,
540                 [&] { return Queue.empty() && !ActiveTask.hasValue(); });
541   }
542 
543   ~BroadcastThread() {
544     {
545       std::lock_guard<std::mutex> Lock(Mu);
546       ShouldStop.store(true, std::memory_order_release);
547     }
548     CV.notify_all();
549     Thread.join();
550   }
551 };
552 
553 // The DirBasedCDB associates each file with a specific CDB.
554 // When a CDB is discovered, it may claim to describe files that we associate
555 // with a different CDB. We do not want to broadcast discovery of these, and
556 // trigger background indexing of them.
557 //
558 // We must filter the list, and check whether they are associated with this CDB.
559 // This class attempts to do so efficiently.
560 //
561 // Roughly, it:
562 //  - loads the config for each file, and determines the relevant search path
563 //  - gathers all directories that are part of any search path
564 //  - (lazily) checks for a CDB in each such directory at most once
565 //  - walks the search path for each file and determines whether to include it.
566 class DirectoryBasedGlobalCompilationDatabase::BroadcastThread::Filter {
567   llvm::StringRef ThisDir;
568   DirectoryBasedGlobalCompilationDatabase &Parent;
569 
570   // Keep track of all directories we might check for CDBs.
571   struct DirInfo {
572     DirectoryCache *Cache = nullptr;
573     enum { Unknown, Missing, TargetCDB, OtherCDB } State = Unknown;
574     DirInfo *Parent = nullptr;
575   };
576   llvm::StringMap<DirInfo> Dirs;
577 
578   // A search path starts at a directory, and either includes ancestors or not.
579   using SearchPath = llvm::PointerIntPair<DirInfo *, 1>;
580 
581   // Add all ancestor directories of FilePath to the tracked set.
582   // Returns the immediate parent of the file.
583   DirInfo *addParents(llvm::StringRef FilePath) {
584     DirInfo *Leaf = nullptr;
585     DirInfo *Child = nullptr;
586     actOnAllParentDirectories(FilePath, [&](llvm::StringRef Dir) {
587       auto &Info = Dirs[Dir];
588       // If this is the first iteration, then this node is the overall result.
589       if (!Leaf)
590         Leaf = &Info;
591       // Fill in the parent link from the previous iteration to this parent.
592       if (Child)
593         Child->Parent = &Info;
594       // Keep walking, whether we inserted or not, if parent link is missing.
595       // (If it's present, parent links must be present up to the root, so stop)
596       Child = &Info;
597       return Info.Parent != nullptr;
598     });
599     return Leaf;
600   }
601 
602   // Populates DirInfo::Cache (and State, if it is TargetCDB).
603   void grabCaches() {
604     // Fast path out if there were no files, or CDB loading is off.
605     if (Dirs.empty())
606       return;
607 
608     std::vector<llvm::StringRef> DirKeys;
609     std::vector<DirInfo *> DirValues;
610     DirKeys.reserve(Dirs.size() + 1);
611     DirValues.reserve(Dirs.size());
612     for (auto &E : Dirs) {
613       DirKeys.push_back(E.first());
614       DirValues.push_back(&E.second);
615     }
616 
617     // Also look up the cache entry for the CDB we're broadcasting.
618     // Comparing DirectoryCache pointers is more robust than checking string
619     // equality, e.g. reuses the case-sensitivity handling.
620     DirKeys.push_back(ThisDir);
621     auto DirCaches = Parent.getDirectoryCaches(DirKeys);
622     const DirectoryCache *ThisCache = DirCaches.back();
623     DirCaches.pop_back();
624     DirKeys.pop_back();
625 
626     for (unsigned I = 0; I < DirKeys.size(); ++I) {
627       DirValues[I]->Cache = DirCaches[I];
628       if (DirCaches[I] == ThisCache)
629         DirValues[I]->State = DirInfo::TargetCDB;
630     }
631   }
632 
633   // Should we include a file from this search path?
634   bool shouldInclude(SearchPath P) {
635     DirInfo *Info = P.getPointer();
636     if (!Info)
637       return false;
638     if (Info->State == DirInfo::Unknown) {
639       assert(Info->Cache && "grabCaches() should have filled this");
640       // Given that we know that CDBs have been moved/generated, don't trust
641       // caches. (This should be rare, so it's OK to add a little latency).
642       constexpr auto IgnoreCache = std::chrono::steady_clock::time_point::max();
643       // Don't broadcast CDBs discovered while broadcasting!
644       bool ShouldBroadcast = false;
645       bool Exists =
646           nullptr != Info->Cache->get(Parent.Opts.TFS, ShouldBroadcast,
647                                       /*FreshTime=*/IgnoreCache,
648                                       /*FreshTimeMissing=*/IgnoreCache);
649       Info->State = Exists ? DirInfo::OtherCDB : DirInfo::Missing;
650     }
651     // If we have a CDB, include the file if it's the target CDB only.
652     if (Info->State != DirInfo::Missing)
653       return Info->State == DirInfo::TargetCDB;
654     // If we have no CDB and no relevant parent, don't include the file.
655     if (!P.getInt() || !Info->Parent)
656       return false;
657     // Walk up to the next parent.
658     return shouldInclude(SearchPath(Info->Parent, 1));
659   }
660 
661 public:
662   Filter(llvm::StringRef ThisDir,
663          DirectoryBasedGlobalCompilationDatabase &Parent)
664       : ThisDir(ThisDir), Parent(Parent) {}
665 
666   std::vector<std::string> filter(std::vector<std::string> AllFiles,
667                                   std::atomic<bool> &ShouldStop) {
668     std::vector<std::string> Filtered;
669     // Allow for clean early-exit of the slow parts.
670     auto ExitEarly = [&] {
671       if (ShouldStop.load(std::memory_order_acquire)) {
672         log("Giving up on broadcasting CDB, as we're shutting down");
673         Filtered.clear();
674         return true;
675       }
676       return false;
677     };
678     // Compute search path for each file.
679     std::vector<SearchPath> SearchPaths(AllFiles.size());
680     for (unsigned I = 0; I < AllFiles.size(); ++I) {
681       if (Parent.Opts.CompileCommandsDir) { // FIXME: unify with config
682         SearchPaths[I].setPointer(
683             &Dirs[Parent.Opts.CompileCommandsDir.getValue()]);
684         continue;
685       }
686       if (ExitEarly()) // loading config may be slow
687         return Filtered;
688       WithContext WithProvidedContent(Parent.Opts.ContextProvider(AllFiles[I]));
689       const Config::CDBSearchSpec &Spec =
690           Config::current().CompileFlags.CDBSearch;
691       switch (Spec.Policy) {
692       case Config::CDBSearchSpec::NoCDBSearch:
693         break;
694       case Config::CDBSearchSpec::Ancestors:
695         SearchPaths[I].setInt(/*Recursive=*/1);
696         SearchPaths[I].setPointer(addParents(AllFiles[I]));
697         break;
698       case Config::CDBSearchSpec::FixedDir:
699         SearchPaths[I].setPointer(&Dirs[Spec.FixedCDBPath.getValue()]);
700         break;
701       }
702     }
703     // Get the CDB cache for each dir on the search path, but don't load yet.
704     grabCaches();
705     // Now work out which files we want to keep, loading CDBs where needed.
706     for (unsigned I = 0; I < AllFiles.size(); ++I) {
707       if (ExitEarly()) // loading CDBs may be slow
708         return Filtered;
709       if (shouldInclude(SearchPaths[I]))
710         Filtered.push_back(std::move(AllFiles[I]));
711     }
712     return Filtered;
713   }
714 };
715 
716 void DirectoryBasedGlobalCompilationDatabase::BroadcastThread::process(
717     const CDBLookupResult &T) {
718   vlog("Broadcasting compilation database from {0}", T.PI.SourceRoot);
719   std::vector<std::string> GovernedFiles =
720       Filter(T.PI.SourceRoot, Parent).filter(T.CDB->getAllFiles(), ShouldStop);
721   if (!GovernedFiles.empty())
722     Parent.OnCommandChanged.broadcast(std::move(GovernedFiles));
723 }
724 
725 void DirectoryBasedGlobalCompilationDatabase::broadcastCDB(
726     CDBLookupResult Result) const {
727   assert(Result.CDB && "Trying to broadcast an invalid CDB!");
728   Broadcaster->enqueue(Result);
729 }
730 
731 bool DirectoryBasedGlobalCompilationDatabase::blockUntilIdle(
732     Deadline Timeout) const {
733   return Broadcaster->blockUntilIdle(Timeout);
734 }
735 
736 llvm::Optional<ProjectInfo>
737 DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const {
738   CDBLookupRequest Req;
739   Req.FileName = File;
740   Req.ShouldBroadcast = false;
741   Req.FreshTime = Req.FreshTimeMissing =
742       std::chrono::steady_clock::time_point::min();
743   auto Res = lookupCDB(Req);
744   if (!Res)
745     return llvm::None;
746   return Res->PI;
747 }
748 
749 OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
750                        std::vector<std::string> FallbackFlags,
751                        tooling::ArgumentsAdjuster Adjuster)
752     : DelegatingCDB(Base), ArgsAdjuster(std::move(Adjuster)),
753       FallbackFlags(std::move(FallbackFlags)) {}
754 
755 llvm::Optional<tooling::CompileCommand>
756 OverlayCDB::getCompileCommand(PathRef File) const {
757   llvm::Optional<tooling::CompileCommand> Cmd;
758   {
759     std::lock_guard<std::mutex> Lock(Mutex);
760     auto It = Commands.find(removeDots(File));
761     if (It != Commands.end())
762       Cmd = It->second;
763   }
764   if (!Cmd)
765     Cmd = DelegatingCDB::getCompileCommand(File);
766   if (!Cmd)
767     return llvm::None;
768   if (ArgsAdjuster)
769     Cmd->CommandLine = ArgsAdjuster(Cmd->CommandLine, Cmd->Filename);
770   return Cmd;
771 }
772 
773 tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const {
774   auto Cmd = DelegatingCDB::getFallbackCommand(File);
775   std::lock_guard<std::mutex> Lock(Mutex);
776   Cmd.CommandLine.insert(Cmd.CommandLine.end(), FallbackFlags.begin(),
777                          FallbackFlags.end());
778   if (ArgsAdjuster)
779     Cmd.CommandLine = ArgsAdjuster(Cmd.CommandLine, Cmd.Filename);
780   return Cmd;
781 }
782 
783 void OverlayCDB::setCompileCommand(
784     PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
785   // We store a canonical version internally to prevent mismatches between set
786   // and get compile commands. Also it assures clients listening to broadcasts
787   // doesn't receive different names for the same file.
788   std::string CanonPath = removeDots(File);
789   {
790     std::unique_lock<std::mutex> Lock(Mutex);
791     if (Cmd)
792       Commands[CanonPath] = std::move(*Cmd);
793     else
794       Commands.erase(CanonPath);
795   }
796   OnCommandChanged.broadcast({CanonPath});
797 }
798 
799 DelegatingCDB::DelegatingCDB(const GlobalCompilationDatabase *Base)
800     : Base(Base) {
801   if (Base)
802     BaseChanged = Base->watch([this](const std::vector<std::string> Changes) {
803       OnCommandChanged.broadcast(Changes);
804     });
805 }
806 
807 DelegatingCDB::DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base)
808     : DelegatingCDB(Base.get()) {
809   BaseOwner = std::move(Base);
810 }
811 
812 llvm::Optional<tooling::CompileCommand>
813 DelegatingCDB::getCompileCommand(PathRef File) const {
814   if (!Base)
815     return llvm::None;
816   return Base->getCompileCommand(File);
817 }
818 
819 llvm::Optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
820   if (!Base)
821     return llvm::None;
822   return Base->getProjectInfo(File);
823 }
824 
825 tooling::CompileCommand DelegatingCDB::getFallbackCommand(PathRef File) const {
826   if (!Base)
827     return GlobalCompilationDatabase::getFallbackCommand(File);
828   return Base->getFallbackCommand(File);
829 }
830 
831 bool DelegatingCDB::blockUntilIdle(Deadline D) const {
832   if (!Base)
833     return true;
834   return Base->blockUntilIdle(D);
835 }
836 
837 } // namespace clangd
838 } // namespace clang
839