Merge pull request #704 from jgagnon/master
[mono.git] / mcs / class / System / System.IO / KeventWatcher.cs
1 // 
2 // System.IO.KeventWatcher.cs: interface with osx kevent
3 //
4 // Authors:
5 //      Geoff Norton (gnorton@customerdna.com)
6 //      Cody Russell (cody@xamarin.com)
7 //      Alexis Christoforides (lexas@xamarin.com)
8 //
9 // (c) 2004 Geoff Norton
10 // Copyright 2014 Xamarin Inc
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.ComponentModel;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Text;
39 using System.Threading;
40 using System.Reflection;
41
42 namespace System.IO {
43
44         [Flags]
45         enum EventFlags : ushort {
46                 Add         = 0x0001,
47                 Delete      = 0x0002,
48                 Enable      = 0x0004,
49                 Disable     = 0x0008,
50                 OneShot     = 0x0010,
51                 Clear       = 0x0020,
52                 Receipt     = 0x0040,
53                 Dispatch    = 0x0080,
54
55                 Flag0       = 0x1000,
56                 Flag1       = 0x2000,
57                 SystemFlags = unchecked (0xf000),
58                         
59                 // Return values.
60                 EOF         = 0x8000,
61                 Error       = 0x4000,
62         }
63         
64         enum EventFilter : short {
65                 Read = -1,
66                 Write = -2,
67                 Aio = -3,
68                 Vnode = -4,
69                 Proc = -5,
70                 Signal = -6,
71                 Timer = -7,
72                 MachPort = -8,
73                 FS = -9,
74                 User = -10,
75                 VM = -11
76         }
77
78         [Flags]
79         enum FilterFlags : uint {
80                 ReadPoll          = EventFlags.Flag0,
81                 ReadOutOfBand     = EventFlags.Flag1,
82                 ReadLowWaterMark  = 0x00000001,
83
84                 WriteLowWaterMark = ReadLowWaterMark,
85
86                 NoteTrigger       = 0x01000000,
87                 NoteFFNop         = 0x00000000,
88                 NoteFFAnd         = 0x40000000,
89                 NoteFFOr          = 0x80000000,
90                 NoteFFCopy        = 0xc0000000,
91                 NoteFFCtrlMask    = 0xc0000000,
92                 NoteFFlagsMask    = 0x00ffffff,
93                                   
94                 VNodeDelete       = 0x00000001,
95                 VNodeWrite        = 0x00000002,
96                 VNodeExtend       = 0x00000004,
97                 VNodeAttrib       = 0x00000008,
98                 VNodeLink         = 0x00000010,
99                 VNodeRename       = 0x00000020,
100                 VNodeRevoke       = 0x00000040,
101                 VNodeNone         = 0x00000080,
102                                   
103                 ProcExit          = 0x80000000,
104                 ProcFork          = 0x40000000,
105                 ProcExec          = 0x20000000,
106                 ProcReap          = 0x10000000,
107                 ProcSignal        = 0x08000000,
108                 ProcExitStatus    = 0x04000000,
109                 ProcResourceEnd   = 0x02000000,
110
111                 // iOS only
112                 ProcAppactive     = 0x00800000,
113                 ProcAppBackground = 0x00400000,
114                 ProcAppNonUI      = 0x00200000,
115                 ProcAppInactive   = 0x00100000,
116                 ProcAppAllStates  = 0x00f00000,
117
118                 // Masks
119                 ProcPDataMask     = 0x000fffff,
120                 ProcControlMask   = 0xfff00000,
121
122                 VMPressure        = 0x80000000,
123                 VMPressureTerminate = 0x40000000,
124                 VMPressureSuddenTerminate = 0x20000000,
125                 VMError           = 0x10000000,
126                 TimerSeconds      =    0x00000001,
127                 TimerMicroSeconds =   0x00000002,
128                 TimerNanoSeconds  =   0x00000004,
129                 TimerAbsolute     =   0x00000008,
130         }
131
132         [StructLayout(LayoutKind.Sequential)]
133         struct kevent : IDisposable {
134                 public UIntPtr ident;
135                 public EventFilter filter;
136                 public EventFlags flags;
137                 public FilterFlags fflags;
138                 public IntPtr data;
139                 public IntPtr udata;
140
141                 public void Dispose ()
142                 {
143                         if (udata != IntPtr.Zero)
144                                 Marshal.FreeHGlobal (udata);
145                 }
146
147
148         }
149
150         [StructLayout(LayoutKind.Sequential)]
151         struct timespec {
152                 public IntPtr tv_sec;
153                 public IntPtr tv_usec;
154         }
155
156         class PathData
157         {
158                 public string Path;
159                 public bool IsDirectory;
160                 public int Fd;
161         }
162
163         class KqueueMonitor : IDisposable
164         {
165                 public int Connection
166                 {
167                         get { return conn; }
168                 }
169
170                 public KqueueMonitor (FileSystemWatcher fsw)
171                 {
172                         this.fsw = fsw;
173                         this.conn = -1;
174                 }
175
176                 public void Dispose ()
177                 {
178                         CleanUp ();
179                 }
180
181                 public void Start ()
182                 {
183                         lock (stateLock) {
184                                 if (started)
185                                         return;
186
187                                 conn = kqueue ();
188
189                                 if (conn == -1)
190                                         throw new IOException (String.Format (
191                                                 "kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
192                                         
193                                 thread = new Thread (() => DoMonitor ());
194                                 thread.IsBackground = true;
195                                 thread.Start ();
196
197                                 startedEvent.WaitOne ();
198
199                                 if (exc != null) {
200                                         thread.Join ();
201                                         CleanUp ();
202                                         throw exc;
203                                 }
204  
205                                 started = true;
206                         }
207                 }
208
209                 public void Stop ()
210                 {
211                         lock (stateLock) {
212                                 if (!started)
213                                         return;
214                                         
215                                 requestStop = true;
216
217                                 if (inDispatch)
218                                         return;
219                                 // This will break the wait in Monitor ()
220                                 lock (connLock) {
221                                         if (conn != -1)
222                                                 close (conn);
223                                         conn = -1;
224                                 }
225
226                                 if (!thread.Join (2000))
227                                         thread.Abort ();
228
229                                 requestStop = false;
230                                 started = false;
231
232                                 if (exc != null)
233                                         throw exc;
234                         }
235                 }
236
237                 void CleanUp ()
238                 {
239                         lock (connLock) {
240                                 if (conn != -1)
241                                         close (conn);
242                                 conn = -1;
243                         }
244
245                         foreach (int fd in fdsDict.Keys)
246                                 close (fd); 
247
248                         fdsDict.Clear ();
249                         pathsDict.Clear ();
250                 }
251
252                 void DoMonitor ()
253                 {                       
254                         try {
255                                 Setup ();
256                         } catch (Exception e) {
257                                 exc = e;
258                         } finally {
259                                 startedEvent.Set ();
260                         }
261
262                         if (exc != null) {
263                                 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
264                                 return;
265                         }
266
267                         try {
268                                 Monitor ();
269                         } catch (Exception e) {
270                                 exc = e;
271                         } finally {
272                                 CleanUp ();
273                                 if (!requestStop) { // failure
274                                         started = false;
275                                         inDispatch = false;
276                                         fsw.EnableRaisingEvents = false;
277                                 }
278                                 if (exc != null)
279                                         fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
280                                 requestStop = false;
281                         }
282                 }
283
284                 void Setup ()
285                 {       
286                         var initialFds = new List<int> ();
287
288                         // fsw.FullPath may end in '/', see https://bugzilla.xamarin.com/show_bug.cgi?id=5747
289                         if (fsw.FullPath != "/" && fsw.FullPath.EndsWith ("/", StringComparison.Ordinal))
290                                 fullPathNoLastSlash = fsw.FullPath.Substring (0, fsw.FullPath.Length - 1);
291                         else
292                                 fullPathNoLastSlash = fsw.FullPath;
293                                 
294                         // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
295                         // If so, introduce a fixup step.
296                         int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
297                         var resolvedFullPath = GetFilenameFromFd (fd);
298                         close (fd);
299
300                         if (resolvedFullPath != fullPathNoLastSlash)
301                                 fixupPath = resolvedFullPath;
302                         else
303                                 fixupPath = null;
304
305                         Scan (fullPathNoLastSlash, false, ref initialFds);
306
307                         var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_usec = (IntPtr)0 };
308                         var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
309                         var changes = CreateChangeList (ref initialFds);
310
311                         int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
312
313                         if (numEvents == -1) {
314                                 var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", Marshal.GetLastWin32Error ());
315                                 throw new IOException (errMsg);
316                         }
317                 }
318
319                 kevent[] CreateChangeList (ref List<int> FdList)
320                 {
321                         if (FdList.Count == 0)
322                                 return emptyEventList;
323
324                         var changes = new List<kevent> ();
325                         foreach (int fd in FdList) {
326                                 var change = new kevent {
327
328                                         ident = (UIntPtr)fd,
329                                         filter = EventFilter.Vnode,
330                                         flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
331                                         fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
332                                                 FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
333                                                 FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
334                                                 FilterFlags.VNodeWrite,
335                                         data = IntPtr.Zero,
336                                         udata = IntPtr.Zero
337                                 };
338
339                                 changes.Add (change);
340                         }
341                         FdList.Clear ();
342
343                         return changes.ToArray ();
344                 }
345
346                 void Monitor ()
347                 {
348                         var eventBuffer = new kevent[32];
349                         var newFds = new List<int> ();
350                         List<PathData> removeQueue = new List<PathData> ();
351                         List<string> rescanQueue = new List<string> ();
352
353                         int retries = 0; 
354
355                         while (!requestStop) {
356                                 var changes = CreateChangeList (ref newFds);
357
358                                 // We are calling an icall, so have to marshal manually
359                                 // Marshal in
360                                 int ksize = Marshal.SizeOf<kevent> ();
361                                 var changesNative = Marshal.AllocHGlobal (ksize * changes.Length);
362                                 for (int i = 0; i < changes.Length; ++i)
363                                         Marshal.StructureToPtr (changes [i], changesNative + (i * ksize), false);
364                                 var eventBufferNative = Marshal.AllocHGlobal (ksize * eventBuffer.Length);
365
366                                 int numEvents = kevent_notimeout (ref conn, changesNative, changes.Length, eventBufferNative, eventBuffer.Length);
367
368                                 // Marshal out
369                                 Marshal.FreeHGlobal (changesNative);
370                                 for (int i = 0; i < numEvents; ++i)
371                                         eventBuffer [i] = Marshal.PtrToStructure<kevent> (eventBufferNative + (i * ksize));
372                                 Marshal.FreeHGlobal (eventBufferNative);
373
374                                 if (numEvents == -1) {
375                                         // Stop () signals us to stop by closing the connection
376                                         if (requestStop)
377                                                 break;
378                                         if (++retries == 3)
379                                                 throw new IOException (String.Format (
380                                                         "persistent kevent() error, error code = '{0}'", Marshal.GetLastWin32Error ()));
381
382                                         continue;
383                                 }
384                                 retries = 0;
385
386                                 for (var i = 0; i < numEvents; i++) {
387                                         var kevt = eventBuffer [i];
388
389                                         if (!fdsDict.ContainsKey ((int)kevt.ident))
390                                                 // The event is for a file that was removed
391                                                 continue;
392
393                                         var pathData = fdsDict [(int)kevt.ident];
394
395                                         if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
396                                                 var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
397                                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (errMsg)));
398                                                 continue;
399                                         }
400                                                 
401                                         if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
402                                                 if (pathData.Path == fullPathNoLastSlash)
403                                                         // The root path is deleted; exit silently
404                                                         return;
405                                                                 
406                                                 removeQueue.Add (pathData);
407                                                 continue;
408                                         }
409
410                                         if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
411                                                         UpdatePath (pathData);
412                                         } 
413
414                                         if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
415                                                 if (pathData.IsDirectory) //TODO: Check if dirs trigger Changed events on .NET
416                                                         rescanQueue.Add (pathData.Path);
417                                                 else
418                                                         PostEvent (FileAction.Modified, pathData.Path);
419                                         }
420                                                 
421                                         if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
422                                                 PostEvent (FileAction.Modified, pathData.Path);
423                                 }
424
425                                 removeQueue.ForEach (Remove);
426                                 removeQueue.Clear ();
427
428                                 rescanQueue.ForEach (path => {
429                                         Scan (path, true, ref newFds);
430                                 });
431                                 rescanQueue.Clear ();
432                         }
433                 }
434
435                 PathData Add (string path, bool postEvents, ref List<int> fds)
436                 {
437                         PathData pathData;
438                         pathsDict.TryGetValue (path, out pathData);
439
440                         if (pathData != null)
441                                 return pathData;
442
443                         if (fdsDict.Count >= maxFds)
444                                 throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch."); 
445
446                         var fd = open (path, O_EVTONLY, 0);
447
448                         if (fd == -1) {
449                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
450                                         "open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
451                                 return null;
452                         }
453
454                         try {
455                                 fds.Add (fd);
456
457                                 var attrs = File.GetAttributes (path);
458
459                                 pathData = new PathData {
460                                         Path = path,
461                                         Fd = fd,
462                                         IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
463                                 };
464                                 
465                                 pathsDict.Add (path, pathData);
466                                 fdsDict.Add (fd, pathData);
467
468                                 if (postEvents)
469                                         PostEvent (FileAction.Added, path);
470
471                                 return pathData;
472                         } catch (Exception e) {
473                                 close (fd);
474                                 fsw.DispatchErrorEvents (new ErrorEventArgs (e));
475                                 return null;
476                         }
477
478                 }
479
480                 void Remove (PathData pathData)
481                 {
482                         fdsDict.Remove (pathData.Fd);
483                         pathsDict.Remove (pathData.Path);
484                         close (pathData.Fd);
485                         PostEvent (FileAction.Removed, pathData.Path);
486                 }
487
488                 void RemoveTree (PathData pathData)
489                 {
490                         var toRemove = new List<PathData> ();
491
492                         toRemove.Add (pathData);
493
494                         if (pathData.IsDirectory) {
495                                 var prefix = pathData.Path + Path.DirectorySeparatorChar;
496                                 foreach (var path in pathsDict.Keys)
497                                         if (path.StartsWith (prefix)) {
498                                                 toRemove.Add (pathsDict [path]);
499                                         }
500                         }
501                         toRemove.ForEach (Remove);
502                 }
503
504                 void UpdatePath (PathData pathData)
505                 {
506                         var newRoot = GetFilenameFromFd (pathData.Fd);
507                         if (!newRoot.StartsWith (fullPathNoLastSlash)) { // moved outside of our watched path (so stop observing it)
508                                 RemoveTree (pathData);
509                                 return;
510                         }
511                                 
512                         var toRename = new List<PathData> ();
513                         var oldRoot = pathData.Path;
514
515                         toRename.Add (pathData);
516                                                                                                                         
517                         if (pathData.IsDirectory) { // anything under the directory must have their paths updated
518                                 var prefix = oldRoot + Path.DirectorySeparatorChar;
519                                 foreach (var path in pathsDict.Keys)
520                                         if (path.StartsWith (prefix))
521                                                 toRename.Add (pathsDict [path]);
522                         }
523                 
524                         foreach (var renaming in toRename) {
525                                 var oldPath = renaming.Path;
526                                 var newPath = newRoot + oldPath.Substring (oldRoot.Length);
527
528                                 renaming.Path = newPath;
529                                 pathsDict.Remove (oldPath);
530
531                                 // destination may exist in our records from a Created event, take care of it
532                                 if (pathsDict.ContainsKey (newPath)) {
533                                         var conflict = pathsDict [newPath];
534                                         if (GetFilenameFromFd (renaming.Fd) == GetFilenameFromFd (conflict.Fd))
535                                                 Remove (conflict);
536                                         else
537                                                 UpdatePath (conflict);
538                                 }
539                                         
540                                 pathsDict.Add (newPath, renaming);
541                         }
542                         
543                         PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
544                 }
545
546                 void Scan (string path, bool postEvents, ref List<int> fds)
547                 {
548                         if (requestStop)
549                                 return;
550                                 
551                         var pathData = Add (path, postEvents, ref fds);
552
553                         if (pathData == null)
554                                 return;
555                                 
556                         if (!pathData.IsDirectory)
557                                 return;
558
559                         var dirsToProcess = new List<string> ();
560                         dirsToProcess.Add (path);
561
562                         while (dirsToProcess.Count > 0) {
563                                 var tmp = dirsToProcess [0];
564                                 dirsToProcess.RemoveAt (0);
565
566                                 var info = new DirectoryInfo (tmp);
567                                 FileSystemInfo[] fsInfos = null;
568                                 try {
569                                         fsInfos = info.GetFileSystemInfos ();
570                                                 
571                                 } catch (IOException) {
572                                         // this can happen if the directory has been deleted already.
573                                         // that's okay, just keep processing the other dirs.
574                                         fsInfos = new FileSystemInfo[0];
575                                 }
576
577                                 foreach (var fsi in fsInfos) {
578                                         if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
579                                                 continue;
580
581                                         if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
582                                                 continue;
583
584                                         var currentPathData = Add (fsi.FullName, postEvents, ref fds);
585
586                                         if (currentPathData != null && currentPathData.IsDirectory)
587                                                 dirsToProcess.Add (fsi.FullName);
588                                 }
589                         }
590                 }
591                         
592                 void PostEvent (FileAction action, string path, string newPath = null)
593                 {
594                         RenamedEventArgs renamed = null;
595
596                         if (requestStop || action == 0)
597                                 return;
598
599                         // e.Name
600                         string name = path.Substring (fullPathNoLastSlash.Length + 1); 
601
602                         // only post events that match filter pattern. check both old and new paths for renames
603                         if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
604                                 return;
605                                 
606                         if (action == FileAction.RenamedNewName) {
607                                 string newName = newPath.Substring (fullPathNoLastSlash.Length + 1);
608                                 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
609                         }
610                                 
611                         fsw.DispatchEvents (action, name, ref renamed);
612
613                         if (fsw.Waiting) {
614                                 lock (fsw) {
615                                         fsw.Waiting = false;
616                                         System.Threading.Monitor.PulseAll (fsw);
617                                 }
618                         }
619                 }
620
621                 private string GetFilenameFromFd (int fd)
622                 {
623                         var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
624
625                         if (fcntl (fd, F_GETPATH, sb) != -1) {
626                                 if (fixupPath != null) 
627                                         sb.Replace (fixupPath, fullPathNoLastSlash, 0, fixupPath.Length); // see Setup()
628
629                                 return sb.ToString ();
630                         } else {
631                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
632                                         "fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
633                                 return String.Empty;
634                         }
635                 }
636
637                 const int O_EVTONLY = 0x8000;
638                 const int F_GETPATH = 50;
639                 const int __DARWIN_MAXPATHLEN = 1024;
640                 static readonly kevent[] emptyEventList = new System.IO.kevent[0];
641                 const int maxFds = 200;
642
643                 FileSystemWatcher fsw;
644                 int conn;
645                 Thread thread;
646                 volatile bool requestStop = false;
647                 AutoResetEvent startedEvent = new AutoResetEvent (false);
648                 bool started = false;
649                 bool inDispatch = false;
650                 Exception exc = null;
651                 object stateLock = new object ();
652                 object connLock = new object ();
653
654                 readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
655                 readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
656                 string fixupPath = null;
657                 string fullPathNoLastSlash = null;
658
659                 [DllImport ("libc", EntryPoint="fcntl", CharSet=CharSet.Auto, SetLastError=true)]
660                 static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
661
662                 [DllImport ("libc")]
663                 extern static int open (string path, int flags, int mode_t);
664
665                 [DllImport ("libc")]
666                 extern static int close (int fd);
667
668                 [DllImport ("libc")]
669                 extern static int kqueue ();
670
671                 [DllImport ("libc")]
672                 extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
673
674                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
675                 extern static int kevent_notimeout (ref int kq, IntPtr ev, int nchanges, IntPtr evtlist, int nevents);
676         }
677
678         class KeventWatcher : IFileWatcher
679         {
680                 static bool failed;
681                 static KeventWatcher instance;
682                 static Hashtable watches;  // <FileSystemWatcher, KqueueMonitor>
683
684                 private KeventWatcher ()
685                 {
686                 }
687
688                 // Locked by caller
689                 public static bool GetInstance (out IFileWatcher watcher)
690                 {
691                         if (failed == true) {
692                                 watcher = null;
693                                 return false;
694                         }
695
696                         if (instance != null) {
697                                 watcher = instance;
698                                 return true;
699                         }
700
701                         watches = Hashtable.Synchronized (new Hashtable ());
702                         var conn = kqueue();
703                         if (conn == -1) {
704                                 failed = true;
705                                 watcher = null;
706                                 return false;
707                         }
708                         close (conn);
709
710                         instance = new KeventWatcher ();
711                         watcher = instance;
712                         return true;
713                 }
714
715                 public void StartDispatching (FileSystemWatcher fsw)
716                 {
717                         KqueueMonitor monitor;
718
719                         if (watches.ContainsKey (fsw)) {
720                                 monitor = (KqueueMonitor)watches [fsw];
721                         } else {
722                                 monitor = new KqueueMonitor (fsw);
723                                 watches.Add (fsw, monitor);
724                         }
725                                 
726                         monitor.Start ();
727                 }
728
729                 public void StopDispatching (FileSystemWatcher fsw)
730                 {
731                         KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
732                         if (monitor == null)
733                                 return;
734
735                         monitor.Stop ();
736                 }
737                         
738                 [DllImport ("libc")]
739                 extern static int close (int fd);
740
741                 [DllImport ("libc")]
742                 extern static int kqueue ();
743         }
744 }
745