Path: blob/main/contrib/llvm-project/clang/lib/DirectoryWatcher/mac/DirectoryWatcher-mac.cpp
35292 views
//===- DirectoryWatcher-mac.cpp - Mac-platform directory watching ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "DirectoryScanner.h"9#include "clang/DirectoryWatcher/DirectoryWatcher.h"1011#include "llvm/ADT/STLExtras.h"12#include "llvm/ADT/StringRef.h"13#include "llvm/Support/Error.h"14#include "llvm/Support/Path.h"15#include <CoreServices/CoreServices.h>16#include <TargetConditionals.h>1718using namespace llvm;19using namespace clang;2021#if TARGET_OS_OSX2223static void stopFSEventStream(FSEventStreamRef);2425namespace {2627/// This implementation is based on FSEvents API which implementation is28/// aggressively coallescing events. This can manifest as duplicate events.29///30/// For example this scenario has been observed:31///32/// create foo/bar33/// sleep 5 s34/// create DirectoryWatcherMac for dir foo35/// receive notification: bar EventKind::Modified36/// sleep 5 s37/// modify foo/bar38/// receive notification: bar EventKind::Modified39/// receive notification: bar EventKind::Modified40/// sleep 5 s41/// delete foo/bar42/// receive notification: bar EventKind::Modified43/// receive notification: bar EventKind::Modified44/// receive notification: bar EventKind::Removed45class DirectoryWatcherMac : public clang::DirectoryWatcher {46public:47DirectoryWatcherMac(48dispatch_queue_t Queue, FSEventStreamRef EventStream,49std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>50Receiver,51llvm::StringRef WatchedDirPath)52: Queue(Queue), EventStream(EventStream), Receiver(Receiver),53WatchedDirPath(WatchedDirPath) {}5455~DirectoryWatcherMac() override {56// FSEventStreamStop and Invalidate must be called after Start and57// SetDispatchQueue to follow FSEvents API contract. The call to Receiver58// also uses Queue to not race with the initial scan.59dispatch_sync(Queue, ^{60stopFSEventStream(EventStream);61EventStream = nullptr;62Receiver(63DirectoryWatcher::Event(64DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""),65false);66});6768// Balance initial creation.69dispatch_release(Queue);70}7172private:73dispatch_queue_t Queue;74FSEventStreamRef EventStream;75std::function<void(llvm::ArrayRef<Event>, bool)> Receiver;76const std::string WatchedDirPath;77};7879struct EventStreamContextData {80std::string WatchedPath;81std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver;8283EventStreamContextData(84std::string &&WatchedPath,85std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>86Receiver)87: WatchedPath(std::move(WatchedPath)), Receiver(Receiver) {}8889// Needed for FSEvents90static void dispose(const void *ctx) {91delete static_cast<const EventStreamContextData *>(ctx);92}93};94} // namespace9596constexpr const FSEventStreamEventFlags StreamInvalidatingFlags =97kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped |98kFSEventStreamEventFlagMustScanSubDirs;99100constexpr const FSEventStreamEventFlags ModifyingFileEvents =101kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRenamed |102kFSEventStreamEventFlagItemModified;103104static void eventStreamCallback(ConstFSEventStreamRef Stream,105void *ClientCallBackInfo, size_t NumEvents,106void *EventPaths,107const FSEventStreamEventFlags EventFlags[],108const FSEventStreamEventId EventIds[]) {109auto *ctx = static_cast<EventStreamContextData *>(ClientCallBackInfo);110111std::vector<DirectoryWatcher::Event> Events;112for (size_t i = 0; i < NumEvents; ++i) {113StringRef Path = ((const char **)EventPaths)[i];114const FSEventStreamEventFlags Flags = EventFlags[i];115116if (Flags & StreamInvalidatingFlags) {117Events.emplace_back(DirectoryWatcher::Event{118DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});119break;120} else if (!(Flags & kFSEventStreamEventFlagItemIsFile)) {121// Subdirectories aren't supported - if some directory got removed it122// must've been the watched directory itself.123if ((Flags & kFSEventStreamEventFlagItemRemoved) &&124Path == ctx->WatchedPath) {125Events.emplace_back(DirectoryWatcher::Event{126DirectoryWatcher::Event::EventKind::WatchedDirRemoved, ""});127Events.emplace_back(DirectoryWatcher::Event{128DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});129break;130}131// No support for subdirectories - just ignore everything.132continue;133} else if (Flags & kFSEventStreamEventFlagItemRemoved) {134Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,135llvm::sys::path::filename(Path));136continue;137} else if (Flags & ModifyingFileEvents) {138if (!getFileStatus(Path).has_value()) {139Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,140llvm::sys::path::filename(Path));141} else {142Events.emplace_back(DirectoryWatcher::Event::EventKind::Modified,143llvm::sys::path::filename(Path));144}145continue;146}147148// default149Events.emplace_back(DirectoryWatcher::Event{150DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});151llvm_unreachable("Unknown FSEvent type.");152}153154if (!Events.empty()) {155ctx->Receiver(Events, /*IsInitial=*/false);156}157}158159FSEventStreamRef createFSEventStream(160StringRef Path,161std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,162dispatch_queue_t Queue) {163if (Path.empty())164return nullptr;165166CFMutableArrayRef PathsToWatch = [&]() {167CFMutableArrayRef PathsToWatch =168CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);169CFStringRef CfPathStr =170CFStringCreateWithBytes(nullptr, (const UInt8 *)Path.data(),171Path.size(), kCFStringEncodingUTF8, false);172CFArrayAppendValue(PathsToWatch, CfPathStr);173CFRelease(CfPathStr);174return PathsToWatch;175}();176177FSEventStreamContext Context = [&]() {178std::string RealPath;179{180SmallString<128> Storage;181StringRef P = llvm::Twine(Path).toNullTerminatedStringRef(Storage);182char Buffer[PATH_MAX];183if (::realpath(P.begin(), Buffer) != nullptr)184RealPath = Buffer;185else186RealPath = Path.str();187}188189FSEventStreamContext Context;190Context.version = 0;191Context.info = new EventStreamContextData(std::move(RealPath), Receiver);192Context.retain = nullptr;193Context.release = EventStreamContextData::dispose;194Context.copyDescription = nullptr;195return Context;196}();197198FSEventStreamRef Result = FSEventStreamCreate(199nullptr, eventStreamCallback, &Context, PathsToWatch,200kFSEventStreamEventIdSinceNow, /* latency in seconds */ 0.0,201kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer);202CFRelease(PathsToWatch);203204return Result;205}206207void stopFSEventStream(FSEventStreamRef EventStream) {208if (!EventStream)209return;210FSEventStreamStop(EventStream);211FSEventStreamInvalidate(EventStream);212FSEventStreamRelease(EventStream);213}214215llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::create(216StringRef Path,217std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,218bool WaitForInitialSync) {219dispatch_queue_t Queue =220dispatch_queue_create("DirectoryWatcher", DISPATCH_QUEUE_SERIAL);221222if (Path.empty())223llvm::report_fatal_error(224"DirectoryWatcher::create can not accept an empty Path.");225226auto EventStream = createFSEventStream(Path, Receiver, Queue);227assert(EventStream && "EventStream expected to be non-null");228229std::unique_ptr<DirectoryWatcher> Result =230std::make_unique<DirectoryWatcherMac>(Queue, EventStream, Receiver, Path);231232// We need to copy the data so the lifetime is ok after a const copy is made233// for the block.234const std::string CopiedPath = Path.str();235236auto InitWork = ^{237// We need to start watching the directory before we start scanning in order238// to not miss any event. By dispatching this on the same serial Queue as239// the FSEvents will be handled we manage to start watching BEFORE the240// inital scan and handling events ONLY AFTER the scan finishes.241FSEventStreamSetDispatchQueue(EventStream, Queue);242FSEventStreamStart(EventStream);243Receiver(getAsFileEvents(scanDirectory(CopiedPath)), /*IsInitial=*/true);244};245246if (WaitForInitialSync) {247dispatch_sync(Queue, InitWork);248} else {249dispatch_async(Queue, InitWork);250}251252return Result;253}254255#else // TARGET_OS_OSX256257llvm::Expected<std::unique_ptr<DirectoryWatcher>>258clang::DirectoryWatcher::create(259StringRef Path,260std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,261bool WaitForInitialSync) {262return llvm::make_error<llvm::StringError>(263"DirectoryWatcher is not implemented for this platform!",264llvm::inconvertibleErrorCode());265}266267#endif // TARGET_OS_OSX268269270