Welcome to mirror list, hosted at ThFree Co, Russian Federation.

KeventWatcher.cs « System.IO « System « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5a1984f70996d868c346d34e2dab812bb55aaa4e (plain)
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
// 
// System.IO.KeventWatcher.cs: interface with osx kevent
//
// Authors:
//	Geoff Norton (gnorton@customerdna.com)
//	Cody Russell (cody@xamarin.com)
//	Alexis Christoforides (lexas@xamarin.com)
//
// (c) 2004 Geoff Norton
// Copyright 2014 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Reflection;

namespace System.IO {

        [Flags]
        enum EventFlags : ushort {
                Add         = 0x0001,
                Delete      = 0x0002,
                Enable      = 0x0004,
                Disable     = 0x0008,
                OneShot     = 0x0010,
                Clear       = 0x0020,
                Receipt     = 0x0040,
                Dispatch    = 0x0080,

                Flag0       = 0x1000,
                Flag1       = 0x2000,
                SystemFlags = unchecked (0xf000),
                        
                // Return values.
                EOF         = 0x8000,
                Error       = 0x4000,
        }
        
        enum EventFilter : short {
                Read = -1,
                Write = -2,
                Aio = -3,
                Vnode = -4,
                Proc = -5,
                Signal = -6,
                Timer = -7,
                MachPort = -8,
                FS = -9,
                User = -10,
                VM = -11
        }

	[Flags]
	enum FilterFlags : uint {
                ReadPoll          = EventFlags.Flag0,
                ReadOutOfBand     = EventFlags.Flag1,
                ReadLowWaterMark  = 0x00000001,

                WriteLowWaterMark = ReadLowWaterMark,

                NoteTrigger       = 0x01000000,
                NoteFFNop         = 0x00000000,
                NoteFFAnd         = 0x40000000,
                NoteFFOr          = 0x80000000,
                NoteFFCopy        = 0xc0000000,
                NoteFFCtrlMask    = 0xc0000000,
                NoteFFlagsMask    = 0x00ffffff,
                                  
                VNodeDelete       = 0x00000001,
                VNodeWrite        = 0x00000002,
                VNodeExtend       = 0x00000004,
                VNodeAttrib       = 0x00000008,
                VNodeLink         = 0x00000010,
                VNodeRename       = 0x00000020,
                VNodeRevoke       = 0x00000040,
                VNodeNone         = 0x00000080,
                                  
                ProcExit          = 0x80000000,
                ProcFork          = 0x40000000,
                ProcExec          = 0x20000000,
                ProcReap          = 0x10000000,
                ProcSignal        = 0x08000000,
                ProcExitStatus    = 0x04000000,
                ProcResourceEnd   = 0x02000000,

                // iOS only
                ProcAppactive     = 0x00800000,
                ProcAppBackground = 0x00400000,
                ProcAppNonUI      = 0x00200000,
                ProcAppInactive   = 0x00100000,
                ProcAppAllStates  = 0x00f00000,

                // Masks
                ProcPDataMask     = 0x000fffff,
                ProcControlMask   = 0xfff00000,

                VMPressure        = 0x80000000,
                VMPressureTerminate = 0x40000000,
                VMPressureSuddenTerminate = 0x20000000,
                VMError           = 0x10000000,
                TimerSeconds      =    0x00000001,
                TimerMicroSeconds =   0x00000002,
                TimerNanoSeconds  =   0x00000004,
                TimerAbsolute     =   0x00000008,
        }

	[StructLayout(LayoutKind.Sequential)]
	struct kevent : IDisposable {
		public UIntPtr ident;
		public EventFilter filter;
		public EventFlags flags;
		public FilterFlags fflags;
		public IntPtr data;
		public IntPtr udata;

		public void Dispose ()
		{
			if (udata != IntPtr.Zero)
				Marshal.FreeHGlobal (udata);
		}


	}

	[StructLayout(LayoutKind.Sequential)]
	struct timespec {
		public IntPtr tv_sec;
		public IntPtr tv_nsec;
	}

	class PathData
	{
		public string Path;
		public bool IsDirectory;
		public int Fd;
	}

	class KqueueMonitor : IDisposable
	{
		static bool initialized;
		
		public int Connection
		{
			get { return conn; }
		}

		public KqueueMonitor (FileSystemWatcher fsw)
		{
			this.fsw = fsw;
			this.conn = -1;
			if (!initialized){
				int t;
				initialized = true;
				var maxenv = Environment.GetEnvironmentVariable ("MONO_DARWIN_WATCHER_MAXFDS");
				if (maxenv != null && Int32.TryParse (maxenv, out t))
					maxFds = t;
			}
		}

		public void Dispose ()
		{
			CleanUp ();
		}

		public void Start ()
		{
			lock (stateLock) {
				if (started)
					return;

				conn = kqueue ();

				if (conn == -1)
					throw new IOException (String.Format (
						"kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
					
				thread = new Thread (() => DoMonitor ());
				thread.IsBackground = true;
				thread.Start ();

				startedEvent.WaitOne ();

				if (exc != null) {
					thread.Join ();
					CleanUp ();
					throw exc;
				}
 
				started = true;
			}
		}

		public void Stop ()
		{
			lock (stateLock) {
				if (!started)
					return;
					
				requestStop = true;

				if (inDispatch)
					return;
				// This will break the wait in Monitor ()
				lock (connLock) {
					if (conn != -1)
						close (conn);
					conn = -1;
				}

				if (!thread.Join (2000))
					thread.Abort ();

				requestStop = false;
				started = false;

				if (exc != null)
					throw exc;
			}
		}

		void CleanUp ()
		{
			lock (connLock) {
				if (conn != -1)
					close (conn);
				conn = -1;
			}

			foreach (int fd in fdsDict.Keys)
				close (fd); 

			fdsDict.Clear ();
			pathsDict.Clear ();
		}

		void DoMonitor ()
		{			
			try {
				Setup ();
			} catch (Exception e) {
				exc = e;
			} finally {
				startedEvent.Set ();
			}

			if (exc != null) {
				fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
				return;
			}

			try {
				Monitor ();
			} catch (Exception e) {
				exc = e;
			} finally {
				CleanUp ();
				if (!requestStop) { // failure
					started = false;
					inDispatch = false;
					fsw.EnableRaisingEvents = false;
				}
				if (exc != null)
					fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
				requestStop = false;
			}
		}

		void Setup ()
		{	
			var initialFds = new List<int> ();

			// fsw.FullPath may end in '/', see https://bugzilla.xamarin.com/show_bug.cgi?id=5747
			if (fsw.FullPath != "/" && fsw.FullPath.EndsWith ("/", StringComparison.Ordinal))
				fullPathNoLastSlash = fsw.FullPath.Substring (0, fsw.FullPath.Length - 1);
			else
				fullPathNoLastSlash = fsw.FullPath;
				
			// realpath() returns the *realpath* which can be different than fsw.FullPath because symlinks.
			// If so, introduce a fixup step.
			var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
			if (realpath(fsw.FullPath, sb) == IntPtr.Zero) {
				var errMsg = String.Format ("realpath({0}) failed, error code = '{1}'", fsw.FullPath, Marshal.GetLastWin32Error ());
				throw new IOException (errMsg);
			}
			var resolvedFullPath = sb.ToString();

			if (resolvedFullPath != fullPathNoLastSlash)
				fixupPath = resolvedFullPath;
			else
				fixupPath = null;

			Scan (fullPathNoLastSlash, false, ref initialFds);

			var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_nsec = (IntPtr)0 };
			var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
			var changes = CreateChangeList (ref initialFds);

			int numEvents;
			int errno = 0;
			do {
				numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
				if (numEvents == -1) {
					errno = Marshal.GetLastWin32Error ();
				}
			} while (numEvents == -1 && errno == EINTR);

			if (numEvents == -1) {
				var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", errno);
				throw new IOException (errMsg);
			}
		}

		kevent[] CreateChangeList (ref List<int> FdList)
		{
			if (FdList.Count == 0)
				return emptyEventList;

			var changes = new List<kevent> ();
			foreach (int fd in FdList) {
				var change = new kevent {

					ident = (UIntPtr)fd,
					filter = EventFilter.Vnode,
					flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
					fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
						FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
						FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
						FilterFlags.VNodeWrite,
					data = IntPtr.Zero,
					udata = IntPtr.Zero
				};

				changes.Add (change);
			}
			FdList.Clear ();

			return changes.ToArray ();
		}

		void Monitor ()
		{
			var eventBuffer = new kevent[32];
			var newFds = new List<int> ();
			List<PathData> removeQueue = new List<PathData> ();
			List<string> rescanQueue = new List<string> ();

			int retries = 0; 

			while (!requestStop) {
				var changes = CreateChangeList (ref newFds);

				// We are calling an icall, so have to marshal manually
				// Marshal in
				int ksize = Marshal.SizeOf<kevent> ();
				var changesNative = Marshal.AllocHGlobal (ksize * changes.Length);
				for (int i = 0; i < changes.Length; ++i)
					Marshal.StructureToPtr (changes [i], changesNative + (i * ksize), false);
				var eventBufferNative = Marshal.AllocHGlobal (ksize * eventBuffer.Length);

				int numEvents = kevent_notimeout (ref conn, changesNative, changes.Length, eventBufferNative, eventBuffer.Length);

				// Marshal out
				Marshal.FreeHGlobal (changesNative);
				for (int i = 0; i < numEvents; ++i)
					eventBuffer [i] = Marshal.PtrToStructure<kevent> (eventBufferNative + (i * ksize));
				Marshal.FreeHGlobal (eventBufferNative);

				if (numEvents == -1) {
					// Stop () signals us to stop by closing the connection
					if (requestStop)
						break;
					int errno = Marshal.GetLastWin32Error ();
					if (errno != EINTR && ++retries == 3)
						throw new IOException (String.Format (
							"persistent kevent() error, error code = '{0}'", errno));

					continue;
				}
				retries = 0;

				for (var i = 0; i < numEvents; i++) {
					var kevt = eventBuffer [i];

					if (!fdsDict.ContainsKey ((int)kevt.ident))
						// The event is for a file that was removed
						continue;

					var pathData = fdsDict [(int)kevt.ident];

					if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
						var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
						fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (errMsg)));
						continue;
					}
						
					if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
						if (pathData.Path == fullPathNoLastSlash)
							// The root path is deleted; exit silently
							return;
								
						removeQueue.Add (pathData);
						continue;
					}

					if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
							UpdatePath (pathData);
					} 

					if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
						if (pathData.IsDirectory) //TODO: Check if dirs trigger Changed events on .NET
							rescanQueue.Add (pathData.Path);
						else
							PostEvent (FileAction.Modified, pathData.Path);
					}
						
					if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
						PostEvent (FileAction.Modified, pathData.Path);
				}

				removeQueue.ForEach (Remove);
				removeQueue.Clear ();

				rescanQueue.ForEach (path => {
					Scan (path, true, ref newFds);
				});
				rescanQueue.Clear ();
			}
		}

		PathData Add (string path, bool postEvents, ref List<int> fds)
		{
			PathData pathData;
			pathsDict.TryGetValue (path, out pathData);

			if (pathData != null)
				return pathData;

			if (fdsDict.Count >= maxFds)
				throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch."); 

			var fd = open (path, O_EVTONLY, 0);

			if (fd == -1) {
				fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
					"open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
				return null;
			}

			try {
				fds.Add (fd);

				var attrs = File.GetAttributes (path);

				pathData = new PathData {
					Path = path,
					Fd = fd,
					IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
				};
				
				pathsDict.Add (path, pathData);
				fdsDict.Add (fd, pathData);

				if (postEvents)
					PostEvent (FileAction.Added, path);

				return pathData;
			} catch (Exception e) {
				close (fd);
				fsw.DispatchErrorEvents (new ErrorEventArgs (e));
				return null;
			}

		}

		void Remove (PathData pathData)
		{
			fdsDict.Remove (pathData.Fd);
			pathsDict.Remove (pathData.Path);
			close (pathData.Fd);
			PostEvent (FileAction.Removed, pathData.Path);
		}

		void RemoveTree (PathData pathData)
		{
			var toRemove = new List<PathData> ();

			toRemove.Add (pathData);

			if (pathData.IsDirectory) {
				var prefix = pathData.Path + Path.DirectorySeparatorChar;
				foreach (var path in pathsDict.Keys)
					if (path.StartsWith (prefix)) {
						toRemove.Add (pathsDict [path]);
					}
			}
			toRemove.ForEach (Remove);
		}

		void UpdatePath (PathData pathData)
		{
			var newRoot = GetFilenameFromFd (pathData.Fd);
			if (!newRoot.StartsWith (fullPathNoLastSlash)) { // moved outside of our watched path (so stop observing it)
				RemoveTree (pathData);
				return;
			}
				
			var toRename = new List<PathData> ();
			var oldRoot = pathData.Path;

			toRename.Add (pathData);
															
			if (pathData.IsDirectory) { // anything under the directory must have their paths updated
				var prefix = oldRoot + Path.DirectorySeparatorChar;
				foreach (var path in pathsDict.Keys)
					if (path.StartsWith (prefix))
						toRename.Add (pathsDict [path]);
			}
		
			foreach (var renaming in toRename) {
				var oldPath = renaming.Path;
				var newPath = newRoot + oldPath.Substring (oldRoot.Length);

				renaming.Path = newPath;
				pathsDict.Remove (oldPath);

				// destination may exist in our records from a Created event, take care of it
				if (pathsDict.ContainsKey (newPath)) {
					var conflict = pathsDict [newPath];
					if (GetFilenameFromFd (renaming.Fd) == GetFilenameFromFd (conflict.Fd))
						Remove (conflict);
					else
						UpdatePath (conflict);
				}
					
				pathsDict.Add (newPath, renaming);
			}
			
			PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
		}

		void Scan (string path, bool postEvents, ref List<int> fds)
		{
			if (requestStop)
				return;
				
			var pathData = Add (path, postEvents, ref fds);

			if (pathData == null)
				return;
				
			if (!pathData.IsDirectory)
				return;

			var dirsToProcess = new List<string> ();
			dirsToProcess.Add (path);

			while (dirsToProcess.Count > 0) {
				var tmp = dirsToProcess [0];
				dirsToProcess.RemoveAt (0);

				var info = new DirectoryInfo (tmp);
				FileSystemInfo[] fsInfos = null;
				try {
					fsInfos = info.GetFileSystemInfos ();
						
				} catch (IOException) {
					// this can happen if the directory has been deleted already.
					// that's okay, just keep processing the other dirs.
					fsInfos = new FileSystemInfo[0];
				}

				foreach (var fsi in fsInfos) {
					if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
						continue;

					if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
						continue;

					var currentPathData = Add (fsi.FullName, postEvents, ref fds);

					if (currentPathData != null && currentPathData.IsDirectory)
						dirsToProcess.Add (fsi.FullName);
				}
			}
		}
			
		void PostEvent (FileAction action, string path, string newPath = null)
		{
			RenamedEventArgs renamed = null;

			if (requestStop || action == 0)
				return;

			// e.Name
			string name = (path.Length > fullPathNoLastSlash.Length) ? path.Substring (fullPathNoLastSlash.Length + 1) : String.Empty;

			// only post events that match filter pattern. check both old and new paths for renames
			if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
				return;
				
			if (action == FileAction.RenamedNewName) {
				string newName = (newPath.Length > fullPathNoLastSlash.Length) ? newPath.Substring (fullPathNoLastSlash.Length + 1) : String.Empty;
				renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
			}
				
			fsw.DispatchEvents (action, name, ref renamed);

			if (fsw.Waiting) {
				lock (fsw) {
					fsw.Waiting = false;
					System.Threading.Monitor.PulseAll (fsw);
				}
			}
		}

		private string GetFilenameFromFd (int fd)
		{
			var sb = new StringBuilder (__DARWIN_MAXPATHLEN);

			if (fcntl (fd, F_GETPATH, sb) != -1) {
				if (fixupPath != null) 
					sb.Replace (fixupPath, fullPathNoLastSlash, 0, fixupPath.Length); // see Setup()

				return sb.ToString ();
			} else {
				fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
					"fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
				return String.Empty;
			}
		}

		const int O_EVTONLY = 0x8000;
		const int F_GETPATH = 50;
		const int __DARWIN_MAXPATHLEN = 1024;
		const int EINTR = 4;
		static readonly kevent[] emptyEventList = new System.IO.kevent[0];
		int maxFds = Int32.MaxValue;

		FileSystemWatcher fsw;
		int conn;
		Thread thread;
		volatile bool requestStop = false;
		AutoResetEvent startedEvent = new AutoResetEvent (false);
		bool started = false;
		bool inDispatch = false;
		Exception exc = null;
		object stateLock = new object ();
		object connLock = new object ();

		readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
		readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
		string fixupPath = null;
		string fullPathNoLastSlash = null;

		[DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
		static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);

		[DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
		static extern IntPtr realpath (string pathname, StringBuilder sb);

		[DllImport ("libc", SetLastError=true)]
		extern static int open (string path, int flags, int mode_t);

		[DllImport ("libc")]
		extern static int close (int fd);

		[DllImport ("libc", SetLastError=true)]
		extern static int kqueue ();

		[DllImport ("libc", SetLastError=true)]
		extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static int kevent_notimeout (ref int kq, IntPtr ev, int nchanges, IntPtr evtlist, int nevents);
	}

	class KeventWatcher : IFileWatcher
	{
		static bool failed;
		static KeventWatcher instance;
		static Hashtable watches;  // <FileSystemWatcher, KqueueMonitor>

		private KeventWatcher ()
		{
		}

		// Locked by caller
		public static bool GetInstance (out IFileWatcher watcher)
		{
			if (failed == true) {
				watcher = null;
				return false;
			}

			if (instance != null) {
				watcher = instance;
				return true;
			}

			watches = Hashtable.Synchronized (new Hashtable ());
			var conn = kqueue();
			if (conn == -1) {
				failed = true;
				watcher = null;
				return false;
			}
			close (conn);

			instance = new KeventWatcher ();
			watcher = instance;
			return true;
		}

		public void StartDispatching (object handle)
		{
			var fsw = handle as FileSystemWatcher;
			KqueueMonitor monitor;

			if (watches.ContainsKey (fsw)) {
				monitor = (KqueueMonitor)watches [fsw];
			} else {
				monitor = new KqueueMonitor (fsw);
				watches.Add (fsw, monitor);
			}
				
			monitor.Start ();
		}

		public void StopDispatching (object handle)
		{
			var fsw = handle as FileSystemWatcher;
			KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
			if (monitor == null)
				return;

			monitor.Stop ();
		}

		public void Dispose (object handle)
		{
			// does nothing
		}
			
		[DllImport ("libc")]
		extern static int close (int fd);

		[DllImport ("libc")]
		extern static int kqueue ();
	}
}