reference, declarationdefinition
definition → references, declarations, derived classes, virtual overrides
reference to multiple definitions → definitions
unreferenced
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
//===- DirectoryWatcher-mac.cpp - Mac-platform directory watching ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "DirectoryScanner.h"
#include "clang/DirectoryWatcher/DirectoryWatcher.h"

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include <CoreServices/CoreServices.h>

using namespace llvm;
using namespace clang;

static void stopFSEventStream(FSEventStreamRef);

namespace {

/// This implementation is based on FSEvents API which implementation is
/// aggressively coallescing events. This can manifest as duplicate events.
///
/// For example this scenario has been observed:
///
/// create foo/bar
/// sleep 5 s
/// create DirectoryWatcherMac for dir foo
/// receive notification: bar EventKind::Modified
/// sleep 5 s
/// modify foo/bar
/// receive notification: bar EventKind::Modified
/// receive notification: bar EventKind::Modified
/// sleep 5 s
/// delete foo/bar
/// receive notification: bar EventKind::Modified
/// receive notification: bar EventKind::Modified
/// receive notification: bar EventKind::Removed
class DirectoryWatcherMac : public clang::DirectoryWatcher {
public:
  DirectoryWatcherMac(
      FSEventStreamRef EventStream,
      std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>
          Receiver,
      llvm::StringRef WatchedDirPath)
      : EventStream(EventStream), Receiver(Receiver),
        WatchedDirPath(WatchedDirPath) {}

  ~DirectoryWatcherMac() override {
    stopFSEventStream(EventStream);
    EventStream = nullptr;
    // Now it's safe to use Receiver as the only other concurrent use would have
    // been in EventStream processing.
    Receiver(DirectoryWatcher::Event(
                 DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""),
             false);
  }

private:
  FSEventStreamRef EventStream;
  std::function<void(llvm::ArrayRef<Event>, bool)> Receiver;
  const std::string WatchedDirPath;
};

struct EventStreamContextData {
  std::string WatchedPath;
  std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver;

  EventStreamContextData(
      std::string &&WatchedPath,
      std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>
          Receiver)
      : WatchedPath(std::move(WatchedPath)), Receiver(Receiver) {}

  // Needed for FSEvents
  static void dispose(const void *ctx) {
    delete static_cast<const EventStreamContextData *>(ctx);
  }
};
} // namespace

constexpr const FSEventStreamEventFlags StreamInvalidatingFlags =
    kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped |
    kFSEventStreamEventFlagMustScanSubDirs;

constexpr const FSEventStreamEventFlags ModifyingFileEvents =
    kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRenamed |
    kFSEventStreamEventFlagItemModified;

static void eventStreamCallback(ConstFSEventStreamRef Stream,
                                void *ClientCallBackInfo, size_t NumEvents,
                                void *EventPaths,
                                const FSEventStreamEventFlags EventFlags[],
                                const FSEventStreamEventId EventIds[]) {
  auto *ctx = static_cast<EventStreamContextData *>(ClientCallBackInfo);

  std::vector<DirectoryWatcher::Event> Events;
  for (size_t i = 0; i < NumEvents; ++i) {
    StringRef Path = ((const char **)EventPaths)[i];
    const FSEventStreamEventFlags Flags = EventFlags[i];

    if (Flags & StreamInvalidatingFlags) {
      Events.emplace_back(DirectoryWatcher::Event{
          DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
      break;
    } else if (!(Flags & kFSEventStreamEventFlagItemIsFile)) {
      // Subdirectories aren't supported - if some directory got removed it
      // must've been the watched directory itself.
      if ((Flags & kFSEventStreamEventFlagItemRemoved) &&
          Path == ctx->WatchedPath) {
        Events.emplace_back(DirectoryWatcher::Event{
            DirectoryWatcher::Event::EventKind::WatchedDirRemoved, ""});
        Events.emplace_back(DirectoryWatcher::Event{
            DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
        break;
      }
      // No support for subdirectories - just ignore everything.
      continue;
    } else if (Flags & kFSEventStreamEventFlagItemRemoved) {
      Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,
                          llvm::sys::path::filename(Path));
      continue;
    } else if (Flags & ModifyingFileEvents) {
      if (!getFileStatus(Path).hasValue()) {
        Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,
                            llvm::sys::path::filename(Path));
      } else {
        Events.emplace_back(DirectoryWatcher::Event::EventKind::Modified,
                            llvm::sys::path::filename(Path));
      }
      continue;
    }

    // default
    Events.emplace_back(DirectoryWatcher::Event{
        DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
    llvm_unreachable("Unknown FSEvent type.");
  }

  if (!Events.empty()) {
    ctx->Receiver(Events, /*IsInitial=*/false);
  }
}

FSEventStreamRef createFSEventStream(
    StringRef Path,
    std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
    dispatch_queue_t Queue) {
  if (Path.empty())
    return nullptr;

  CFMutableArrayRef PathsToWatch = [&]() {
    CFMutableArrayRef PathsToWatch =
        CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
    CFStringRef CfPathStr =
        CFStringCreateWithBytes(nullptr, (const UInt8 *)Path.data(),
                                Path.size(), kCFStringEncodingUTF8, false);
    CFArrayAppendValue(PathsToWatch, CfPathStr);
    CFRelease(CfPathStr);
    return PathsToWatch;
  }();

  FSEventStreamContext Context = [&]() {
    std::string RealPath;
    {
      SmallString<128> Storage;
      StringRef P = llvm::Twine(Path).toNullTerminatedStringRef(Storage);
      char Buffer[PATH_MAX];
      if (::realpath(P.begin(), Buffer) != nullptr)
        RealPath = Buffer;
      else
        RealPath = Path;
    }

    FSEventStreamContext Context;
    Context.version = 0;
    Context.info = new EventStreamContextData(std::move(RealPath), Receiver);
    Context.retain = nullptr;
    Context.release = EventStreamContextData::dispose;
    Context.copyDescription = nullptr;
    return Context;
  }();

  FSEventStreamRef Result = FSEventStreamCreate(
      nullptr, eventStreamCallback, &Context, PathsToWatch,
      kFSEventStreamEventIdSinceNow, /* latency in seconds */ 0.0,
      kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer);
  CFRelease(PathsToWatch);

  return Result;
}

void stopFSEventStream(FSEventStreamRef EventStream) {
  if (!EventStream)
    return;
  FSEventStreamStop(EventStream);
  FSEventStreamInvalidate(EventStream);
  FSEventStreamRelease(EventStream);
}

llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::create(
    StringRef Path,
    std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
    bool WaitForInitialSync) {
  dispatch_queue_t Queue =
      dispatch_queue_create("DirectoryWatcher", DISPATCH_QUEUE_SERIAL);

  if (Path.empty())
    llvm::report_fatal_error(
        "DirectoryWatcher::create can not accept an empty Path.");

  auto EventStream = createFSEventStream(Path, Receiver, Queue);
  assert(EventStream && "EventStream expected to be non-null");

  std::unique_ptr<DirectoryWatcher> Result =
      std::make_unique<DirectoryWatcherMac>(EventStream, Receiver, Path);

  // We need to copy the data so the lifetime is ok after a const copy is made
  // for the block.
  const std::string CopiedPath = Path;

  auto InitWork = ^{
    // We need to start watching the directory before we start scanning in order
    // to not miss any event. By dispatching this on the same serial Queue as
    // the FSEvents will be handled we manage to start watching BEFORE the
    // inital scan and handling events ONLY AFTER the scan finishes.
    FSEventStreamSetDispatchQueue(EventStream, Queue);
    FSEventStreamStart(EventStream);
    // We need to decrement the ref count for Queue as initialize() will return
    // and FSEvents has incremented it. Since we have to wait for FSEvents to
    // take ownership it's the easiest to do it here rather than main thread.
    dispatch_release(Queue);
    Receiver(getAsFileEvents(scanDirectory(CopiedPath)), /*IsInitial=*/true);
  };

  if (WaitForInitialSync) {
    dispatch_sync(Queue, InitWork);
  } else {
    dispatch_async(Queue, InitWork);
  }

  return Result;
}