Debian Codegraph @

node/@parcel/watcher/src/macos/FSEventsBackend.cc

raw
1 #include <CoreServices/CoreServices.h>
2 #include <sys/stat.h>
3 #include <string>
4 #include <fstream>
5 #include <unordered_set>
6 #include "../Event.hh"
7 #include "../Backend.hh"
8 #include "./FSEventsBackend.hh"
9 #include "../Watcher.hh"
10
11 #define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
12 #define IGNORED_FLAGS (kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink | kFSEventStreamEventFlagItemIsSymlink | kFSEventStreamEventFlagItemIsDir | kFSEventStreamEventFlagItemIsFile)
13
14 void stopStream(FSEventStreamRef stream, CFRunLoopRef runLoop) {
15 FSEventStreamStop(stream);
16 FSEventStreamUnscheduleFromRunLoop(stream, runLoop, kCFRunLoopDefaultMode);
17 FSEventStreamInvalidate(stream);
18 FSEventStreamRelease(stream);
19 }
20
21 // macOS has a case insensitive file system by default. In order to detect
22 // file renames that only affect case, we need to get the canonical path
23 // and compare it with the input path to determine if a file was created or deleted.
24 bool pathExists(char *path) {
25 int fd = open(path, O_RDONLY | O_SYMLINK);
26 if (fd == -1) {
27 return false;
28 }
29
30 char buf[PATH_MAX];
31 if (fcntl(fd, F_GETPATH, buf) == -1) {
32 close(fd);
33 return false;
34 }
35
36 bool res = strncmp(path, buf, PATH_MAX) == 0;
37 close(fd);
38 return res;
39 }
40
41 class State: public WatcherState {
42 public:
43 FSEventStreamRef stream;
44 std::shared_ptr<DirTree> tree;
45 uint64_t since;
46 };
47
48 void FSEventsCallback(
49 ConstFSEventStreamRef streamRef,
50 void *clientCallBackInfo,
51 size_t numEvents,
52 void *eventPaths,
53 const FSEventStreamEventFlags eventFlags[],
54 const FSEventStreamEventId eventIds[]
55 ) {
56 char **paths = (char **)eventPaths;
57 std::shared_ptr<Watcher>& watcher = *static_cast<std::shared_ptr<Watcher> *>(clientCallBackInfo);
58
59 EventList& list = watcher->mEvents;
60 if (watcher->state == nullptr) {
61 return;
62 }
63
64 auto stateGuard = watcher->state;
65 auto* state = static_cast<State*>(stateGuard.get());
66 uint64_t since = state->since;
67 bool deletedRoot = false;
68
69 for (size_t i = 0; i < numEvents; ++i) {
70 bool isCreated = (eventFlags[i] & kFSEventStreamEventFlagItemCreated) == kFSEventStreamEventFlagItemCreated;
71 bool isRemoved = (eventFlags[i] & kFSEventStreamEventFlagItemRemoved) == kFSEventStreamEventFlagItemRemoved;
72 bool isModified = (eventFlags[i] & kFSEventStreamEventFlagItemModified) == kFSEventStreamEventFlagItemModified ||
73 (eventFlags[i] & kFSEventStreamEventFlagItemInodeMetaMod) == kFSEventStreamEventFlagItemInodeMetaMod ||
74 (eventFlags[i] & kFSEventStreamEventFlagItemFinderInfoMod) == kFSEventStreamEventFlagItemFinderInfoMod ||
75 (eventFlags[i] & kFSEventStreamEventFlagItemChangeOwner) == kFSEventStreamEventFlagItemChangeOwner ||
76 (eventFlags[i] & kFSEventStreamEventFlagItemXattrMod) == kFSEventStreamEventFlagItemXattrMod;
77 bool isRenamed = (eventFlags[i] & kFSEventStreamEventFlagItemRenamed) == kFSEventStreamEventFlagItemRenamed;
78 bool isDone = (eventFlags[i] & kFSEventStreamEventFlagHistoryDone) == kFSEventStreamEventFlagHistoryDone;
79 bool isDir = (eventFlags[i] & kFSEventStreamEventFlagItemIsDir) == kFSEventStreamEventFlagItemIsDir;
80
81
82 if (eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs) {
83 if (eventFlags[i] & kFSEventStreamEventFlagUserDropped) {
84 list.error("Events were dropped by the FSEvents client. File system must be re-scanned.");
85 } else if (eventFlags[i] & kFSEventStreamEventFlagKernelDropped) {
86 list.error("Events were dropped by the kernel. File system must be re-scanned.");
87 } else {
88 list.error("Too many events. File system must be re-scanned.");
89 }
90 }
91
92 if (isDone) {
93 watcher->notify();
94 break;
95 }
96
97 auto ignoredFlags = IGNORED_FLAGS;
98 if (__builtin_available(macOS 10.13, *)) {
99 ignoredFlags |= kFSEventStreamEventFlagItemCloned;
100 }
101
102 // If we don't care about any of the flags that are set, ignore this event.
103 if ((eventFlags[i] & ~ignoredFlags) == 0) {
104 continue;
105 }
106
107 // FSEvents exclusion paths only apply to files, not directories.
108 if (watcher->isIgnored(paths[i])) {
109 continue;
110 }
111
112 // Handle unambiguous events first
113 if (isCreated && !(isRemoved || isModified || isRenamed)) {
114 state->tree->add(paths[i], 0, isDir);
115 list.create(paths[i]);
116 } else if (isRemoved && !(isCreated || isModified || isRenamed)) {
117 state->tree->remove(paths[i]);
118 list.remove(paths[i]);
119 if (paths[i] == watcher->mDir) {
120 deletedRoot = true;
121 }
122 } else if (isModified && !(isCreated || isRemoved || isRenamed)) {
123 struct stat file;
124 if (stat(paths[i], &file)) {
125 continue;
126 }
127
128 // Ignore if mtime is the same as the last event.
129 // This prevents duplicate events from being emitted.
130 // If tv_nsec is zero, the file system probably only has second-level
131 // granularity so allow the even through in that case.
132 uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
133 DirEntry *entry = state->tree->find(paths[i]);
134 if (entry && mtime == entry->mtime && file.st_mtimespec.tv_nsec != 0) {
135 continue;
136 }
137
138 if (entry) {
139 // Update mtime.
140 entry->mtime = mtime;
141 } else {
142 // Add to tree if this path has not been discovered yet.
143 state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
144 }
145
146 list.update(paths[i]);
147 } else {
148 // If multiple flags were set, then we need to call `stat` to determine if the file really exists.
149 // This helps disambiguate creates, updates, and deletes.
150 struct stat file;
151 if (stat(paths[i], &file) || !pathExists(paths[i])) {
152 // File does not exist, so we have to assume it was removed. This is not exact since the
153 // flags set by fsevents get coalesced together (e.g. created & deleted), so there is no way to
154 // know whether the create and delete both happened since our snapshot (in which case
155 // we'd rather ignore this event completely). This will result in some extra delete events
156 // being emitted for files we don't know about, but that is the best we can do.
157 state->tree->remove(paths[i]);
158 list.remove(paths[i]);
159 if (paths[i] == watcher->mDir) {
160 deletedRoot = true;
161 }
162 continue;
163 }
164
165 // If the file was modified, and existed before, then this is an update, otherwise a create.
166 uint64_t ctime = CONVERT_TIME(file.st_birthtimespec);
167 uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
168 DirEntry *entry = !since ? state->tree->find(paths[i]) : NULL;
169 if (entry && entry->mtime == mtime && file.st_mtimespec.tv_nsec != 0) {
170 continue;
171 }
172
173 // Some mounted file systems report a creation time of 0/unix epoch which we special case.
174 if (isModified && (entry || (ctime <= since && ctime != 0))) {
175 state->tree->update(paths[i], mtime);
176 list.update(paths[i]);
177 } else {
178 state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
179 list.create(paths[i]);
180 }
181 }
182 }
183
184 if (!since) {
185 watcher->notify();
186 }
187
188 // Stop watching if the root directory was deleted.
189 if (deletedRoot) {
190 stopStream((FSEventStreamRef)streamRef, CFRunLoopGetCurrent());
191 watcher->state = nullptr;
192 }
193 }
194
195 void checkWatcher(WatcherRef watcher) {
196 struct stat file;
197 if (stat(watcher->mDir.c_str(), &file)) {
198 throw WatcherError(strerror(errno), watcher);
199 }
200
201 if (!S_ISDIR(file.st_mode)) {
202 throw WatcherError(strerror(ENOTDIR), watcher);
203 }
204 }
205
206 void FSEventsBackend::startStream(WatcherRef watcher, FSEventStreamEventId id) {
207 checkWatcher(watcher);
208
209 CFAbsoluteTime latency = 0.001;
210 CFStringRef fileWatchPath = CFStringCreateWithCString(
211 NULL,
212 watcher->mDir.c_str(),
213 kCFStringEncodingUTF8
214 );
215
216 CFArrayRef pathsToWatch = CFArrayCreate(
217 NULL,
218 (const void **)&fileWatchPath,
219 1,
220 NULL
221 );
222
223 // Make a watcher reference we can pass into the callback. This ensures bumped ref-count.
224 std::shared_ptr<Watcher>* callbackWatcher = new std::shared_ptr<Watcher> (watcher);
225 FSEventStreamContext callbackInfo {0, static_cast<void*> (callbackWatcher), nullptr, nullptr, nullptr};
226 FSEventStreamRef stream = FSEventStreamCreate(
227 NULL,
228 &FSEventsCallback,
229 &callbackInfo,
230 pathsToWatch,
231 id,
232 latency,
233 kFSEventStreamCreateFlagFileEvents
234 );
235
236 CFMutableArrayRef exclusions = CFArrayCreateMutable(NULL, watcher->mIgnorePaths.size(), NULL);
237 for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
238 CFStringRef path = CFStringCreateWithCString(
239 NULL,
240 it->c_str(),
241 kCFStringEncodingUTF8
242 );
243
244 CFArrayAppendValue(exclusions, (const void *)path);
245 }
246
247 FSEventStreamSetExclusionPaths(stream, exclusions);
248
249 FSEventStreamScheduleWithRunLoop(stream, mRunLoop, kCFRunLoopDefaultMode);
250 bool started = FSEventStreamStart(stream);
251
252 CFRelease(pathsToWatch);
253 CFRelease(fileWatchPath);
254
255 if (!started) {
256 FSEventStreamRelease(stream);
257 throw WatcherError("Error starting FSEvents stream", watcher);
258 }
259
260 auto stateGuard = watcher->state;
261 State* s = static_cast<State*>(stateGuard.get());
262 s->tree = std::make_shared<DirTree>(watcher->mDir);
263 s->stream = stream;
264 }
265
266 void FSEventsBackend::start() {
267 mRunLoop = CFRunLoopGetCurrent();
268 CFRetain(mRunLoop);
269
270 // Unlock once run loop has started.
271 CFRunLoopPerformBlock(mRunLoop, kCFRunLoopDefaultMode, ^ {
272 notifyStarted();
273 });
274
275 CFRunLoopWakeUp(mRunLoop);
276 CFRunLoopRun();
277 }
278
279 FSEventsBackend::~FSEventsBackend() {
280 std::unique_lock<std::mutex> lock(mMutex);
281 CFRunLoopStop(mRunLoop);
282 CFRelease(mRunLoop);
283 }
284
285 void FSEventsBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
286 std::unique_lock<std::mutex> lock(mMutex);
287 checkWatcher(watcher);
288
289 FSEventStreamEventId id = FSEventsGetCurrentEventId();
290 std::ofstream ofs(*snapshotPath);
291 ofs << id;
292 ofs << "\n";
293
294 struct timespec now;
295 clock_gettime(CLOCK_REALTIME, &now);
296 ofs << CONVERT_TIME(now);
297 }
298
299 void FSEventsBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
300 std::unique_lock<std::mutex> lock(mMutex);
301 std::ifstream ifs(*snapshotPath);
302 if (ifs.fail()) {
303 return;
304 }
305
306 FSEventStreamEventId id;
307 uint64_t since;
308 ifs >> id;
309 ifs >> since;
310
311 auto s = std::make_shared<State>();
312 s->since = since;
313 watcher->state = s;
314
315 startStream(watcher, id);
316 watcher->wait();
317 stopStream(s->stream, mRunLoop);
318
319 watcher->state = nullptr;
320 }
321
322 // This function is called by Backend::watch which takes a lock on mMutex
323 void FSEventsBackend::subscribe(WatcherRef watcher) {
324 auto s = std::make_shared<State>();
325 s->since = 0;
326 watcher->state = s;
327 startStream(watcher, kFSEventStreamEventIdSinceNow);
328 }
329
330 // This function is called by Backend::unwatch which takes a lock on mMutex
331 void FSEventsBackend::unsubscribe(WatcherRef watcher) {
332 auto stateGuard = watcher->state;
333 State* s = static_cast<State*>(stateGuard.get());
334 if (s != nullptr) {
335 stopStream(s->stream, mRunLoop);
336 watcher->state = nullptr;
337 }
338 }