forked from bdkjones/VDKQueue
-
Notifications
You must be signed in to change notification settings - Fork 2
/
VDKQueue.m
459 lines (348 loc) · 12.2 KB
/
VDKQueue.m
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// VDKQueue.m
// Created by Bryan D K Jones on 28 March 2012
// Copyright 2013 Bryan D K Jones
//
// Based heavily on UKKQueue, which was created and copyrighted by Uli Kusterer on 21 Dec 2003.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source
// distribution.
#import "VDKQueue.h"
#import <unistd.h>
#import <fcntl.h>
#include <sys/stat.h>
NSString * VDKQueueRenameNotification = @"VDKQueueFileRenamedNotification";
NSString * VDKQueueWriteNotification = @"VDKQueueFileWrittenToNotification";
NSString * VDKQueueDeleteNotification = @"VDKQueueFileDeletedNotification";
NSString * VDKQueueAttributeChangeNotification = @"VDKQueueFileAttributesChangedNotification";
NSString * VDKQueueSizeIncreaseNotification = @"VDKQueueFileSizeIncreasedNotification";
NSString * VDKQueueLinkCountChangeNotification = @"VDKQueueLinkCountChangedNotification";
NSString * VDKQueueAccessRevocationNotification = @"VDKQueueAccessWasRevokedNotification";
#pragma mark -
#pragma mark VDKQueuePathEntry
#pragma mark -
#pragma ------------------------------------------------------------------------------------------------------------------------------------------------------------
// This is a simple model class used to hold info about each path we watch.
@interface VDKQueuePathEntry : NSObject
{
NSString* _path;
int _watchedFD;
u_int _subscriptionFlags;
}
- (id) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags;
@property (atomic, copy) NSString *path;
@property (atomic, assign) int watchedFD;
@property (atomic, assign) u_int subscriptionFlags;
@end
@implementation VDKQueuePathEntry
@synthesize path = _path, watchedFD = _watchedFD, subscriptionFlags = _subscriptionFlags;
- (id) initWithPath:(NSString*)inPath andSubscriptionFlags:(u_int)flags;
{
self = [super init];
if (self)
{
_path = [inPath copy];
_watchedFD = open([_path fileSystemRepresentation], O_EVTONLY, 0);
if (_watchedFD < 0)
{
ARCCompatAutorelease(self)
return nil;
}
_subscriptionFlags = flags;
}
return self;
}
-(void) dealloc
{
ARCCompatRelease(_path)
_path = nil;
if (_watchedFD >= 0) close(_watchedFD);
_watchedFD = -1;
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
@end
#pragma mark -
#pragma mark VDKQueue
#pragma mark -
#pragma ------------------------------------------------------------------------------------------------------------------------------------------------------------
@interface VDKQueue ()
- (void) watcherThread:(id)sender;
@end
@implementation VDKQueue
@synthesize delegate = _delegate, alwaysPostNotifications = _alwaysPostNotifications, sleepInterval = _sleepInterval;
#pragma mark -
#pragma mark INIT/DEALLOC
- (id) init
{
self = [super init];
if (self)
{
_coreQueueFD = kqueue();
if (_coreQueueFD == -1)
{
ARCCompatAutorelease(self)
return nil;
}
_alwaysPostNotifications = NO;
#if TARGET_OS_IPHONE
_sleepInterval = 60;
#else
_sleepInterval = 0;
#endif
_watchedPathEntries = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) dealloc
{
// Shut down the thread that's scanning for kQueue events
_keepWatcherThreadRunning = NO;
// Do this to close all the open file descriptors for files we're watching
[self removeAllPaths];
ARCCompatRelease(_watchedPathEntries)
_watchedPathEntries = nil;
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
#pragma mark -
#pragma mark PRIVATE METHODS
- (VDKQueuePathEntry *) addPathToQueue:(NSString *)path notifyingAbout:(u_int)flags
{
@synchronized(self)
{
// Are we already watching this path?
VDKQueuePathEntry *pathEntry = [_watchedPathEntries objectForKey:path];
if (pathEntry)
{
// All flags already set?
if(([pathEntry subscriptionFlags] & flags) == flags)
{
return ARCCompatAutoreleaseInline( ARCCompatRetainInline(pathEntry) );
}
flags |= [pathEntry subscriptionFlags];
}
struct timespec nullts = { 0, 0 };
struct kevent ev;
if (!pathEntry)
{
pathEntry = ARCCompatAutoreleaseInline([[VDKQueuePathEntry alloc] initWithPath:path andSubscriptionFlags:flags]);
}
if (pathEntry)
{
EV_SET(&ev, [pathEntry watchedFD], EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, flags, 0, ARCCompatBridge(void*, pathEntry));
[pathEntry setSubscriptionFlags:flags];
[_watchedPathEntries setObject:pathEntry forKey:path];
kevent(_coreQueueFD, &ev, 1, NULL, 0, &nullts);
// Start the thread that fetches and processes our events if it's not already running.
if(!_keepWatcherThreadRunning)
{
_keepWatcherThreadRunning = YES;
[NSThread detachNewThreadSelector:@selector(watcherThread:) toTarget:self withObject:nil];
}
}
return ARCCompatAutoreleaseInline( ARCCompatRetainInline(pathEntry) );
}
return nil;
}
//
// WARNING: This thread has no active autorelease pool, so if you make changes, you must manually manage
// memory without relying on autorelease. Otherwise, you will leak!
//
- (void) watcherThread:(id)sender
{
int n;
struct kevent ev;
struct timespec timeout = { 1, 0 }; // 1 second timeout. Should be longer, but we need this thread to exit when a kqueue is dealloced, so 1 second timeout is quite a while to wait.
int theFD = _coreQueueFD; // So we don't have to risk accessing iVars when the thread is terminated.
NSMutableArray *notesToPost = [[NSMutableArray alloc] initWithCapacity:5];
#if DEBUG_LOG_THREAD_LIFETIME
NSLog(@"watcherThread started.");
#endif
while(_keepWatcherThreadRunning)
{
@try
{
n = kevent(theFD, NULL, 0, &ev, 1, &timeout);
if (n > 0)
{
//NSLog( @"KEVENT returned %d", n );
if (ev.filter == EVFILT_VNODE)
{
//NSLog( @"KEVENT filter is EVFILT_VNODE" );
if (ev.fflags)
{
//NSLog( @"KEVENT flags are set" );
//
// Note: VDKQueue gets tested by thousands of CodeKit users who each watch several thousand files at once.
// I was receiving about 3 EXC_BAD_ACCESS (SIGSEGV) crash reports a month that listed the 'path' objc_msgSend
// as the culprit. That suggests the KEVENT is being sent back to us with a udata value that is NOT what we assigned
// to the queue, though I don't know why and I don't know why it's intermittent. Regardless, I've added an extra
// check here to try to eliminate this (infrequent) problem. In theory, a KEVENT that does not have a VDKQueuePathEntry
// object attached as the udata parameter is not an event we registered for, so we should not be "missing" any events. In theory.
//
id pe = ARCCompatBridge(id, ev.udata);
if (pe && [pe respondsToSelector:@selector(path)])
{
NSString *fpath = ARCCompatRetainInline( ((VDKQueuePathEntry *)pe).path ); // Need to retain so it does not disappear while the block at the bottom is waiting to run on the main thread. Released in that block.
if (!fpath) continue;
#if !TARGET_OS_IPHONE
[[NSWorkspace sharedWorkspace] noteFileSystemChanged:fpath];
#endif
// Clear any old notifications
[notesToPost removeAllObjects];
// Figure out which notifications we need to issue
if ((ev.fflags & NOTE_RENAME) == NOTE_RENAME)
{
[notesToPost addObject:VDKQueueRenameNotification];
}
if ((ev.fflags & NOTE_WRITE) == NOTE_WRITE)
{
[notesToPost addObject:VDKQueueWriteNotification];
}
if ((ev.fflags & NOTE_DELETE) == NOTE_DELETE)
{
[notesToPost addObject:VDKQueueDeleteNotification];
}
if ((ev.fflags & NOTE_ATTRIB) == NOTE_ATTRIB)
{
[notesToPost addObject:VDKQueueAttributeChangeNotification];
}
if ((ev.fflags & NOTE_EXTEND) == NOTE_EXTEND)
{
[notesToPost addObject:VDKQueueSizeIncreaseNotification];
}
if ((ev.fflags & NOTE_LINK) == NOTE_LINK)
{
[notesToPost addObject:VDKQueueLinkCountChangeNotification];
}
if ((ev.fflags & NOTE_REVOKE) == NOTE_REVOKE)
{
[notesToPost addObject:VDKQueueAccessRevocationNotification];
}
NSArray *notes = [[NSArray alloc] initWithArray:notesToPost]; // notesToPost will be changed in the next loop iteration, which will likely occur before the block below runs.
// Post the notifications (or call the delegate method) on the main thread.
dispatch_async(dispatch_get_main_queue(),
^{
for (NSString *note in notes)
{
[_delegate VDKQueue:self receivedNotification:note forPath:fpath];
if (!_delegate || _alwaysPostNotifications)
{
NSDictionary *userInfoDict = [[NSDictionary alloc] initWithObjectsAndKeys:fpath, @"path", nil];
#if TARGET_OS_IPHONE
[[NSNotificationCenter defaultCenter] postNotificationName:note object:self userInfo:userInfoDict];
#else
[[[NSWorkspace sharedWorkspace] notificationCenter] postNotificationName:note object:self userInfo:userInfoDict];
#endif
ARCCompatRelease(userInfoDict)
}
}
ARCCompatRelease(fpath)
ARCCompatRelease(notes)
});
}
}
}
}
}
@catch (NSException *localException)
{
NSLog(@"Error in VDKQueue watcherThread: %@", localException);
}
#if TARGET_OS_IPHONE
[NSThread sleepForTimeInterval:_sleepInterval]; // To save power on iOS
#endif
}
// Close our kqueue's file descriptor
if(close(theFD) == -1) {
NSLog(@"VDKQueue watcherThread: Couldn't close main kqueue (%d)", errno);
}
ARCCompatRelease(notesToPost)
#if DEBUG_LOG_THREAD_LIFETIME
NSLog(@"watcherThread finished.");
#endif
}
#pragma mark -
#pragma mark PUBLIC METHODS
#pragma -----------------------------------------------------------------------------------------------------------------------------------------------------
- (void) addPath:(NSString *)aPath
{
if (!aPath) return;
ARCCompatRetain(aPath)
@synchronized(self)
{
VDKQueuePathEntry *entry = [_watchedPathEntries objectForKey:aPath];
// Only add this path if we don't already have it.
if (!entry)
{
entry = [self addPathToQueue:aPath notifyingAbout:VDKQueueNotifyDefault];
if (!entry) {
NSLog(@"VDKQueue tried to add the path %@ to watchedPathEntries, but the VDKQueuePathEntry was nil. \nIt's possible that the host process has hit its max open file descriptors limit.", aPath);
}
}
}
ARCCompatRelease(aPath)
}
- (void) addPath:(NSString *)aPath notifyingAbout:(u_int)flags
{
if (!aPath) return;
ARCCompatRetain(aPath)
@synchronized(self)
{
VDKQueuePathEntry *entry = [_watchedPathEntries objectForKey:aPath];
// Only add this path if we don't already have it.
if (!entry)
{
entry = [self addPathToQueue:aPath notifyingAbout:flags];
if (!entry) {
NSLog(@"VDKQueue tried to add the path %@ to watchedPathEntries, but the VDKQueuePathEntry was nil. \nIt's possible that the host process has hit its max open file descriptors limit.", aPath);
}
}
}
ARCCompatRelease(aPath)
}
- (void) removePath:(NSString *)aPath
{
if (!aPath) return;
ARCCompatRetain(aPath)
@synchronized(self)
{
VDKQueuePathEntry *entry = [_watchedPathEntries objectForKey:aPath];
// Remove it only if we're watching it.
if (entry) {
[_watchedPathEntries removeObjectForKey:aPath];
}
}
ARCCompatRelease(aPath)
}
- (void) removeAllPaths
{
@synchronized(self)
{
[_watchedPathEntries removeAllObjects];
}
}
- (NSUInteger) numberOfWatchedPaths
{
NSUInteger count;
@synchronized(self)
{
count = [_watchedPathEntries count];
}
return count;
}
@end