Merge pull request #2831 from razzfazz/fix_dllimport
[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_nsec;
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                 static bool initialized;
166                 
167                 public int Connection
168                 {
169                         get { return conn; }
170                 }
171
172                 public KqueueMonitor (FileSystemWatcher fsw)
173                 {
174                         this.fsw = fsw;
175                         this.conn = -1;
176                         if (!initialized){
177                                 int t;
178                                 initialized = true;
179                                 var maxenv = Environment.GetEnvironmentVariable ("MONO_DARWIN_WATCHER_MAXFDS");
180                                 if (maxenv != null && Int32.TryParse (maxenv, out t))
181                                         maxFds = t;
182                         }
183                 }
184
185                 public void Dispose ()
186                 {
187                         CleanUp ();
188                 }
189
190                 public void Start ()
191                 {
192                         lock (stateLock) {
193                                 if (started)
194                                         return;
195
196                                 conn = kqueue ();
197
198                                 if (conn == -1)
199                                         throw new IOException (String.Format (
200                                                 "kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
201                                         
202                                 thread = new Thread (() => DoMonitor ());
203                                 thread.IsBackground = true;
204                                 thread.Start ();
205
206                                 startedEvent.WaitOne ();
207
208                                 if (exc != null) {
209                                         thread.Join ();
210                                         CleanUp ();
211                                         throw exc;
212                                 }
213  
214                                 started = true;
215                         }
216                 }
217
218                 public void Stop ()
219                 {
220                         lock (stateLock) {
221                                 if (!started)
222                                         return;
223                                         
224                                 requestStop = true;
225
226                                 if (inDispatch)
227                                         return;
228                                 // This will break the wait in Monitor ()
229                                 lock (connLock) {
230                                         if (conn != -1)
231                                                 close (conn);
232                                         conn = -1;
233                                 }
234
235                                 if (!thread.Join (2000))
236                                         thread.Abort ();
237
238                                 requestStop = false;
239                                 started = false;
240
241                                 if (exc != null)
242                                         throw exc;
243                         }
244                 }
245
246                 void CleanUp ()
247                 {
248                         lock (connLock) {
249                                 if (conn != -1)
250                                         close (conn);
251                                 conn = -1;
252                         }
253
254                         foreach (int fd in fdsDict.Keys)
255                                 close (fd); 
256
257                         fdsDict.Clear ();
258                         pathsDict.Clear ();
259                 }
260
261                 void DoMonitor ()
262                 {                       
263                         try {
264                                 Setup ();
265                         } catch (Exception e) {
266                                 exc = e;
267                         } finally {
268                                 startedEvent.Set ();
269                         }
270
271                         if (exc != null) {
272                                 fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
273                                 return;
274                         }
275
276                         try {
277                                 Monitor ();
278                         } catch (Exception e) {
279                                 exc = e;
280                         } finally {
281                                 CleanUp ();
282                                 if (!requestStop) { // failure
283                                         started = false;
284                                         inDispatch = false;
285                                         fsw.EnableRaisingEvents = false;
286                                 }
287                                 if (exc != null)
288                                         fsw.DispatchErrorEvents (new ErrorEventArgs (exc));
289                                 requestStop = false;
290                         }
291                 }
292
293                 void Setup ()
294                 {       
295                         var initialFds = new List<int> ();
296
297                         // fsw.FullPath may end in '/', see https://bugzilla.xamarin.com/show_bug.cgi?id=5747
298                         if (fsw.FullPath != "/" && fsw.FullPath.EndsWith ("/", StringComparison.Ordinal))
299                                 fullPathNoLastSlash = fsw.FullPath.Substring (0, fsw.FullPath.Length - 1);
300                         else
301                                 fullPathNoLastSlash = fsw.FullPath;
302                                 
303                         // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
304                         // If so, introduce a fixup step.
305                         int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
306                         var resolvedFullPath = GetFilenameFromFd (fd);
307                         close (fd);
308
309                         if (resolvedFullPath != fullPathNoLastSlash)
310                                 fixupPath = resolvedFullPath;
311                         else
312                                 fixupPath = null;
313
314                         Scan (fullPathNoLastSlash, false, ref initialFds);
315
316                         var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_nsec = (IntPtr)0 };
317                         var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
318                         var changes = CreateChangeList (ref initialFds);
319
320                         int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);
321
322                         if (numEvents == -1) {
323                                 var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", Marshal.GetLastWin32Error ());
324                                 throw new IOException (errMsg);
325                         }
326                 }
327
328                 kevent[] CreateChangeList (ref List<int> FdList)
329                 {
330                         if (FdList.Count == 0)
331                                 return emptyEventList;
332
333                         var changes = new List<kevent> ();
334                         foreach (int fd in FdList) {
335                                 var change = new kevent {
336
337                                         ident = (UIntPtr)fd,
338                                         filter = EventFilter.Vnode,
339                                         flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
340                                         fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
341                                                 FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
342                                                 FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
343                                                 FilterFlags.VNodeWrite,
344                                         data = IntPtr.Zero,
345                                         udata = IntPtr.Zero
346                                 };
347
348                                 changes.Add (change);
349                         }
350                         FdList.Clear ();
351
352                         return changes.ToArray ();
353                 }
354
355                 void Monitor ()
356                 {
357                         var eventBuffer = new kevent[32];
358                         var newFds = new List<int> ();
359                         List<PathData> removeQueue = new List<PathData> ();
360                         List<string> rescanQueue = new List<string> ();
361
362                         int retries = 0; 
363
364                         while (!requestStop) {
365                                 var changes = CreateChangeList (ref newFds);
366
367                                 // We are calling an icall, so have to marshal manually
368                                 // Marshal in
369                                 int ksize = Marshal.SizeOf<kevent> ();
370                                 var changesNative = Marshal.AllocHGlobal (ksize * changes.Length);
371                                 for (int i = 0; i < changes.Length; ++i)
372                                         Marshal.StructureToPtr (changes [i], changesNative + (i * ksize), false);
373                                 var eventBufferNative = Marshal.AllocHGlobal (ksize * eventBuffer.Length);
374
375                                 int numEvents = kevent_notimeout (ref conn, changesNative, changes.Length, eventBufferNative, eventBuffer.Length);
376
377                                 // Marshal out
378                                 Marshal.FreeHGlobal (changesNative);
379                                 for (int i = 0; i < numEvents; ++i)
380                                         eventBuffer [i] = Marshal.PtrToStructure<kevent> (eventBufferNative + (i * ksize));
381                                 Marshal.FreeHGlobal (eventBufferNative);
382
383                                 if (numEvents == -1) {
384                                         // Stop () signals us to stop by closing the connection
385                                         if (requestStop)
386                                                 break;
387                                         if (++retries == 3)
388                                                 throw new IOException (String.Format (
389                                                         "persistent kevent() error, error code = '{0}'", Marshal.GetLastWin32Error ()));
390
391                                         continue;
392                                 }
393                                 retries = 0;
394
395                                 for (var i = 0; i < numEvents; i++) {
396                                         var kevt = eventBuffer [i];
397
398                                         if (!fdsDict.ContainsKey ((int)kevt.ident))
399                                                 // The event is for a file that was removed
400                                                 continue;
401
402                                         var pathData = fdsDict [(int)kevt.ident];
403
404                                         if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
405                                                 var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
406                                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (errMsg)));
407                                                 continue;
408                                         }
409                                                 
410                                         if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke) {
411                                                 if (pathData.Path == fullPathNoLastSlash)
412                                                         // The root path is deleted; exit silently
413                                                         return;
414                                                                 
415                                                 removeQueue.Add (pathData);
416                                                 continue;
417                                         }
418
419                                         if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
420                                                         UpdatePath (pathData);
421                                         } 
422
423                                         if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
424                                                 if (pathData.IsDirectory) //TODO: Check if dirs trigger Changed events on .NET
425                                                         rescanQueue.Add (pathData.Path);
426                                                 else
427                                                         PostEvent (FileAction.Modified, pathData.Path);
428                                         }
429                                                 
430                                         if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
431                                                 PostEvent (FileAction.Modified, pathData.Path);
432                                 }
433
434                                 removeQueue.ForEach (Remove);
435                                 removeQueue.Clear ();
436
437                                 rescanQueue.ForEach (path => {
438                                         Scan (path, true, ref newFds);
439                                 });
440                                 rescanQueue.Clear ();
441                         }
442                 }
443
444                 PathData Add (string path, bool postEvents, ref List<int> fds)
445                 {
446                         PathData pathData;
447                         pathsDict.TryGetValue (path, out pathData);
448
449                         if (pathData != null)
450                                 return pathData;
451
452                         if (fdsDict.Count >= maxFds)
453                                 throw new IOException ("kqueue() FileSystemWatcher has reached the maximum number of files to watch."); 
454
455                         var fd = open (path, O_EVTONLY, 0);
456
457                         if (fd == -1) {
458                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
459                                         "open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
460                                 return null;
461                         }
462
463                         try {
464                                 fds.Add (fd);
465
466                                 var attrs = File.GetAttributes (path);
467
468                                 pathData = new PathData {
469                                         Path = path,
470                                         Fd = fd,
471                                         IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
472                                 };
473                                 
474                                 pathsDict.Add (path, pathData);
475                                 fdsDict.Add (fd, pathData);
476
477                                 if (postEvents)
478                                         PostEvent (FileAction.Added, path);
479
480                                 return pathData;
481                         } catch (Exception e) {
482                                 close (fd);
483                                 fsw.DispatchErrorEvents (new ErrorEventArgs (e));
484                                 return null;
485                         }
486
487                 }
488
489                 void Remove (PathData pathData)
490                 {
491                         fdsDict.Remove (pathData.Fd);
492                         pathsDict.Remove (pathData.Path);
493                         close (pathData.Fd);
494                         PostEvent (FileAction.Removed, pathData.Path);
495                 }
496
497                 void RemoveTree (PathData pathData)
498                 {
499                         var toRemove = new List<PathData> ();
500
501                         toRemove.Add (pathData);
502
503                         if (pathData.IsDirectory) {
504                                 var prefix = pathData.Path + Path.DirectorySeparatorChar;
505                                 foreach (var path in pathsDict.Keys)
506                                         if (path.StartsWith (prefix)) {
507                                                 toRemove.Add (pathsDict [path]);
508                                         }
509                         }
510                         toRemove.ForEach (Remove);
511                 }
512
513                 void UpdatePath (PathData pathData)
514                 {
515                         var newRoot = GetFilenameFromFd (pathData.Fd);
516                         if (!newRoot.StartsWith (fullPathNoLastSlash)) { // moved outside of our watched path (so stop observing it)
517                                 RemoveTree (pathData);
518                                 return;
519                         }
520                                 
521                         var toRename = new List<PathData> ();
522                         var oldRoot = pathData.Path;
523
524                         toRename.Add (pathData);
525                                                                                                                         
526                         if (pathData.IsDirectory) { // anything under the directory must have their paths updated
527                                 var prefix = oldRoot + Path.DirectorySeparatorChar;
528                                 foreach (var path in pathsDict.Keys)
529                                         if (path.StartsWith (prefix))
530                                                 toRename.Add (pathsDict [path]);
531                         }
532                 
533                         foreach (var renaming in toRename) {
534                                 var oldPath = renaming.Path;
535                                 var newPath = newRoot + oldPath.Substring (oldRoot.Length);
536
537                                 renaming.Path = newPath;
538                                 pathsDict.Remove (oldPath);
539
540                                 // destination may exist in our records from a Created event, take care of it
541                                 if (pathsDict.ContainsKey (newPath)) {
542                                         var conflict = pathsDict [newPath];
543                                         if (GetFilenameFromFd (renaming.Fd) == GetFilenameFromFd (conflict.Fd))
544                                                 Remove (conflict);
545                                         else
546                                                 UpdatePath (conflict);
547                                 }
548                                         
549                                 pathsDict.Add (newPath, renaming);
550                         }
551                         
552                         PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
553                 }
554
555                 void Scan (string path, bool postEvents, ref List<int> fds)
556                 {
557                         if (requestStop)
558                                 return;
559                                 
560                         var pathData = Add (path, postEvents, ref fds);
561
562                         if (pathData == null)
563                                 return;
564                                 
565                         if (!pathData.IsDirectory)
566                                 return;
567
568                         var dirsToProcess = new List<string> ();
569                         dirsToProcess.Add (path);
570
571                         while (dirsToProcess.Count > 0) {
572                                 var tmp = dirsToProcess [0];
573                                 dirsToProcess.RemoveAt (0);
574
575                                 var info = new DirectoryInfo (tmp);
576                                 FileSystemInfo[] fsInfos = null;
577                                 try {
578                                         fsInfos = info.GetFileSystemInfos ();
579                                                 
580                                 } catch (IOException) {
581                                         // this can happen if the directory has been deleted already.
582                                         // that's okay, just keep processing the other dirs.
583                                         fsInfos = new FileSystemInfo[0];
584                                 }
585
586                                 foreach (var fsi in fsInfos) {
587                                         if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
588                                                 continue;
589
590                                         if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
591                                                 continue;
592
593                                         var currentPathData = Add (fsi.FullName, postEvents, ref fds);
594
595                                         if (currentPathData != null && currentPathData.IsDirectory)
596                                                 dirsToProcess.Add (fsi.FullName);
597                                 }
598                         }
599                 }
600                         
601                 void PostEvent (FileAction action, string path, string newPath = null)
602                 {
603                         RenamedEventArgs renamed = null;
604
605                         if (requestStop || action == 0)
606                                 return;
607
608                         // e.Name
609                         string name = path.Substring (fullPathNoLastSlash.Length + 1); 
610
611                         // only post events that match filter pattern. check both old and new paths for renames
612                         if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
613                                 return;
614                                 
615                         if (action == FileAction.RenamedNewName) {
616                                 string newName = newPath.Substring (fullPathNoLastSlash.Length + 1);
617                                 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
618                         }
619                                 
620                         fsw.DispatchEvents (action, name, ref renamed);
621
622                         if (fsw.Waiting) {
623                                 lock (fsw) {
624                                         fsw.Waiting = false;
625                                         System.Threading.Monitor.PulseAll (fsw);
626                                 }
627                         }
628                 }
629
630                 private string GetFilenameFromFd (int fd)
631                 {
632                         var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
633
634                         if (fcntl (fd, F_GETPATH, sb) != -1) {
635                                 if (fixupPath != null) 
636                                         sb.Replace (fixupPath, fullPathNoLastSlash, 0, fixupPath.Length); // see Setup()
637
638                                 return sb.ToString ();
639                         } else {
640                                 fsw.DispatchErrorEvents (new ErrorEventArgs (new IOException (String.Format (
641                                         "fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
642                                 return String.Empty;
643                         }
644                 }
645
646                 const int O_EVTONLY = 0x8000;
647                 const int F_GETPATH = 50;
648                 const int __DARWIN_MAXPATHLEN = 1024;
649                 static readonly kevent[] emptyEventList = new System.IO.kevent[0];
650                 int maxFds = Int32.MaxValue;
651
652                 FileSystemWatcher fsw;
653                 int conn;
654                 Thread thread;
655                 volatile bool requestStop = false;
656                 AutoResetEvent startedEvent = new AutoResetEvent (false);
657                 bool started = false;
658                 bool inDispatch = false;
659                 Exception exc = null;
660                 object stateLock = new object ();
661                 object connLock = new object ();
662
663                 readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
664                 readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
665                 string fixupPath = null;
666                 string fullPathNoLastSlash = null;
667
668                 [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
669                 static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
670
671                 [DllImport ("libc", SetLastError=true)]
672                 extern static int open (string path, int flags, int mode_t);
673
674                 [DllImport ("libc")]
675                 extern static int close (int fd);
676
677                 [DllImport ("libc", SetLastError=true)]
678                 extern static int kqueue ();
679
680                 [DllImport ("libc", SetLastError=true)]
681                 extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
682
683                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
684                 extern static int kevent_notimeout (ref int kq, IntPtr ev, int nchanges, IntPtr evtlist, int nevents);
685         }
686
687         class KeventWatcher : IFileWatcher
688         {
689                 static bool failed;
690                 static KeventWatcher instance;
691                 static Hashtable watches;  // <FileSystemWatcher, KqueueMonitor>
692
693                 private KeventWatcher ()
694                 {
695                 }
696
697                 // Locked by caller
698                 public static bool GetInstance (out IFileWatcher watcher)
699                 {
700                         if (failed == true) {
701                                 watcher = null;
702                                 return false;
703                         }
704
705                         if (instance != null) {
706                                 watcher = instance;
707                                 return true;
708                         }
709
710                         watches = Hashtable.Synchronized (new Hashtable ());
711                         var conn = kqueue();
712                         if (conn == -1) {
713                                 failed = true;
714                                 watcher = null;
715                                 return false;
716                         }
717                         close (conn);
718
719                         instance = new KeventWatcher ();
720                         watcher = instance;
721                         return true;
722                 }
723
724                 public void StartDispatching (FileSystemWatcher fsw)
725                 {
726                         KqueueMonitor monitor;
727
728                         if (watches.ContainsKey (fsw)) {
729                                 monitor = (KqueueMonitor)watches [fsw];
730                         } else {
731                                 monitor = new KqueueMonitor (fsw);
732                                 watches.Add (fsw, monitor);
733                         }
734                                 
735                         monitor.Start ();
736                 }
737
738                 public void StopDispatching (FileSystemWatcher fsw)
739                 {
740                         KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
741                         if (monitor == null)
742                                 return;
743
744                         monitor.Stop ();
745                 }
746                         
747                 [DllImport ("libc")]
748                 extern static int close (int fd);
749
750                 [DllImport ("libc")]
751                 extern static int kqueue ();
752         }
753 }
754