Add socket-related functions and data structures to Mono.Posix
[mono.git] / mcs / class / Mono.Posix / Mono.Unix.Native / Syscall.cs
1 //
2 // Mono.Unix/Syscall.cs
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@novell.com)
6 //   Jonathan Pryor (jonpryor@vt.edu)
7 //
8 // (C) 2003 Novell, Inc.
9 // (C) 2004-2006 Jonathan Pryor
10 //
11 // This file implements the low-level syscall interface to the POSIX
12 // subsystem.
13 //
14 // This file tries to stay close to the low-level API as much as possible
15 // using enumerations, structures and in a few cases, using existing .NET
16 // data types.
17 //
18 // Implementation notes:
19 //
20 //    Since the values for the various constants on the API changes
21 //    from system to system (even Linux on different architectures will
22 //    have different values), we define our own set of values, and we
23 //    use a set of C helper routines to map from the constants we define
24 //    to the values of the native OS.
25 //
26 //    Bitfields are flagged with the [Map] attribute, and a helper program
27 //    generates a set of routines that we can call to convert from our value 
28 //    definitions to the value definitions expected by the OS; see
29 //    NativeConvert for the conversion routines.
30 //
31 //    Methods that require tuning are bound as `private sys_NAME' methods
32 //    and then a `NAME' method is exposed.
33 //
34
35 //
36 // Permission is hereby granted, free of charge, to any person obtaining
37 // a copy of this software and associated documentation files (the
38 // "Software"), to deal in the Software without restriction, including
39 // without limitation the rights to use, copy, modify, merge, publish,
40 // distribute, sublicense, and/or sell copies of the Software, and to
41 // permit persons to whom the Software is furnished to do so, subject to
42 // the following conditions:
43 // 
44 // The above copyright notice and this permission notice shall be
45 // included in all copies or substantial portions of the Software.
46 // 
47 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
51 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
52 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
53 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
54 //
55
56 using System;
57 using System.Collections;
58 using System.Collections.Generic;
59 using System.Runtime.InteropServices;
60 using System.Security;
61 using System.Text;
62 using Mono.Unix.Native;
63
64 namespace Mono.Unix.Native {
65
66         #region Enumerations
67
68         [Flags][Map]
69         [CLSCompliant (false)]
70         public enum SyslogOptions {
71                 LOG_PID    = 0x01,  // log the pid with each message
72                 LOG_CONS   = 0x02,  // log on the console if errors in sending
73                 LOG_ODELAY = 0x04,  // delay open until first syslog (default)
74                 LOG_NDELAY = 0x08,  // don't delay open
75                 LOG_NOWAIT = 0x10,  // don't wait for console forks; DEPRECATED
76                 LOG_PERROR = 0x20   // log to stderr as well
77         }
78
79         [Map]
80         [CLSCompliant (false)]
81         public enum SyslogFacility {
82                 LOG_KERN      = 0 << 3,
83                 LOG_USER      = 1 << 3,
84                 LOG_MAIL      = 2 << 3,
85                 LOG_DAEMON    = 3 << 3,
86                 LOG_AUTH      = 4 << 3,
87                 LOG_SYSLOG    = 5 << 3,
88                 LOG_LPR       = 6 << 3,
89                 LOG_NEWS      = 7 << 3,
90                 LOG_UUCP      = 8 << 3,
91                 LOG_CRON      = 9 << 3,
92                 LOG_AUTHPRIV  = 10 << 3,
93                 LOG_FTP       = 11 << 3,
94                 LOG_LOCAL0    = 16 << 3,
95                 LOG_LOCAL1    = 17 << 3,
96                 LOG_LOCAL2    = 18 << 3,
97                 LOG_LOCAL3    = 19 << 3,
98                 LOG_LOCAL4    = 20 << 3,
99                 LOG_LOCAL5    = 21 << 3,
100                 LOG_LOCAL6    = 22 << 3,
101                 LOG_LOCAL7    = 23 << 3,
102         }
103
104         [Map]
105         [CLSCompliant (false)]
106         public enum SyslogLevel {
107                 LOG_EMERG   = 0,  // system is unusable
108                 LOG_ALERT   = 1,  // action must be taken immediately
109                 LOG_CRIT    = 2,  // critical conditions
110                 LOG_ERR     = 3,  // warning conditions
111                 LOG_WARNING = 4,  // warning conditions
112                 LOG_NOTICE  = 5,  // normal but significant condition
113                 LOG_INFO    = 6,  // informational
114                 LOG_DEBUG   = 7   // debug-level messages
115         }
116
117         [Map][Flags]
118         [CLSCompliant (false)]
119         public enum OpenFlags : int {
120                 //
121                 // One of these
122                 //
123                 O_RDONLY    = 0x00000000,
124                 O_WRONLY    = 0x00000001,
125                 O_RDWR      = 0x00000002,
126
127                 //
128                 // Or-ed with zero or more of these
129                 //
130                 O_CREAT     = 0x00000040,
131                 O_EXCL      = 0x00000080,
132                 O_NOCTTY    = 0x00000100,
133                 O_TRUNC     = 0x00000200,
134                 O_APPEND    = 0x00000400,
135                 O_NONBLOCK  = 0x00000800,
136                 O_SYNC      = 0x00001000,
137
138                 //
139                 // These are non-Posix.  Using them will result in errors/exceptions on
140                 // non-supported platforms.
141                 //
142                 // (For example, "C-wrapped" system calls -- calls with implementation in
143                 // MonoPosixHelper -- will return -1 with errno=EINVAL.  C#-wrapped system
144                 // calls will generate an exception in NativeConvert, as the value can't be
145                 // converted on the target platform.)
146                 //
147                 
148                 O_NOFOLLOW  = 0x00020000,
149                 O_DIRECTORY = 0x00010000,
150                 O_DIRECT    = 0x00004000,
151                 O_ASYNC     = 0x00002000,
152                 O_LARGEFILE = 0x00008000,
153                 O_CLOEXEC   = 0x00080000,
154                 O_PATH      = 0x00200000
155         }
156         
157         [Map][Flags]
158         [CLSCompliant (false)]
159         public enum AtFlags : int {
160                 AT_SYMLINK_NOFOLLOW = 0x00000100,
161                 AT_REMOVEDIR        = 0x00000200,
162                 AT_SYMLINK_FOLLOW   = 0x00000400,
163                 AT_NO_AUTOMOUNT     = 0x00000800,
164                 AT_EMPTY_PATH       = 0x00001000
165         }
166         
167         // mode_t
168         [Flags][Map]
169         [CLSCompliant (false)]
170         public enum FilePermissions : uint {
171                 S_ISUID     = 0x0800, // Set user ID on execution
172                 S_ISGID     = 0x0400, // Set group ID on execution
173                 S_ISVTX     = 0x0200, // Save swapped text after use (sticky).
174                 S_IRUSR     = 0x0100, // Read by owner
175                 S_IWUSR     = 0x0080, // Write by owner
176                 S_IXUSR     = 0x0040, // Execute by owner
177                 S_IRGRP     = 0x0020, // Read by group
178                 S_IWGRP     = 0x0010, // Write by group
179                 S_IXGRP     = 0x0008, // Execute by group
180                 S_IROTH     = 0x0004, // Read by other
181                 S_IWOTH     = 0x0002, // Write by other
182                 S_IXOTH     = 0x0001, // Execute by other
183
184                 S_IRWXG     = (S_IRGRP | S_IWGRP | S_IXGRP),
185                 S_IRWXU     = (S_IRUSR | S_IWUSR | S_IXUSR),
186                 S_IRWXO     = (S_IROTH | S_IWOTH | S_IXOTH),
187                 ACCESSPERMS = (S_IRWXU | S_IRWXG | S_IRWXO), // 0777
188                 ALLPERMS    = (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO), // 07777
189                 DEFFILEMODE = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH), // 0666
190
191                 // Device types
192                 // Why these are held in "mode_t" is beyond me...
193                 S_IFMT      = 0xF000, // Bits which determine file type
194                 [Map(SuppressFlags="S_IFMT")]
195                 S_IFDIR     = 0x4000, // Directory
196                 [Map(SuppressFlags="S_IFMT")]
197                 S_IFCHR     = 0x2000, // Character device
198                 [Map(SuppressFlags="S_IFMT")]
199                 S_IFBLK     = 0x6000, // Block device
200                 [Map(SuppressFlags="S_IFMT")]
201                 S_IFREG     = 0x8000, // Regular file
202                 [Map(SuppressFlags="S_IFMT")]
203                 S_IFIFO     = 0x1000, // FIFO
204                 [Map(SuppressFlags="S_IFMT")]
205                 S_IFLNK     = 0xA000, // Symbolic link
206                 [Map(SuppressFlags="S_IFMT")]
207                 S_IFSOCK    = 0xC000, // Socket
208         }
209
210         [Map]
211         [CLSCompliant (false)]
212         public enum FcntlCommand : int {
213                 // Form /usr/include/bits/fcntl.h
214                 F_DUPFD    =    0, // Duplicate file descriptor.
215                 F_GETFD    =    1, // Get file descriptor flags.
216                 F_SETFD    =    2, // Set file descriptor flags.
217                 F_GETFL    =    3, // Get file status flags.
218                 F_SETFL    =    4, // Set file status flags.
219                 F_GETLK    =   12, // Get record locking info. [64]
220                 F_SETLK    =   13, // Set record locking info (non-blocking). [64]
221                 F_SETLKW   =   14, // Set record locking info (blocking). [64]
222                 F_SETOWN   =    8, // Set owner of socket (receiver of SIGIO).
223                 F_GETOWN   =    9, // Get owner of socket (receiver of SIGIO).
224                 F_SETSIG   =   10, // Set number of signal to be sent.
225                 F_GETSIG   =   11, // Get number of signal to be sent.
226                 F_NOCACHE  =   48, // OSX: turn data caching off/on for this fd.
227                 F_SETLEASE = 1024, // Set a lease.
228                 F_GETLEASE = 1025, // Enquire what lease is active.
229                 F_NOTIFY   = 1026, // Required notifications on a directory
230         }
231
232         [Map]
233         [CLSCompliant (false)]
234         public enum LockType : short {
235                 F_RDLCK = 0, // Read lock.
236                 F_WRLCK = 1, // Write lock.
237                 F_UNLCK = 2, // Remove lock.
238         }
239
240         [Map]
241         [CLSCompliant (false)]
242         public enum SeekFlags : short {
243                 // values liberally copied from /usr/include/unistd.h
244                 SEEK_SET = 0, // Seek from beginning of file.
245                 SEEK_CUR = 1, // Seek from current position.
246                 SEEK_END = 2, // Seek from end of file.
247
248                 L_SET    = SEEK_SET, // BSD alias for SEEK_SET
249                 L_INCR   = SEEK_CUR, // BSD alias for SEEK_CUR
250                 L_XTND   = SEEK_END, // BSD alias for SEEK_END
251         }
252         
253         [Map, Flags]
254         [CLSCompliant (false)]
255         public enum DirectoryNotifyFlags : int {
256                 // from /usr/include/bits/fcntl.h
257                 DN_ACCESS    = 0x00000001, // File accessed.
258                 DN_MODIFY    = 0x00000002, // File modified.
259                 DN_CREATE    = 0x00000004, // File created.
260                 DN_DELETE    = 0x00000008, // File removed.
261                 DN_RENAME    = 0x00000010, // File renamed.
262                 DN_ATTRIB    = 0x00000020, // File changed attributes.
263                 DN_MULTISHOT = unchecked ((int)0x80000000), // Don't remove notifier
264         }
265
266         [Map]
267         [CLSCompliant (false)]
268         public enum PosixFadviseAdvice : int {
269                 POSIX_FADV_NORMAL     = 0,  // No further special treatment.
270                 POSIX_FADV_RANDOM     = 1,  // Expect random page references.
271                 POSIX_FADV_SEQUENTIAL = 2,  // Expect sequential page references.
272                 POSIX_FADV_WILLNEED   = 3,  // Will need these pages.
273                 POSIX_FADV_DONTNEED   = 4,  // Don't need these pages.
274                 POSIX_FADV_NOREUSE    = 5,  // Data will be accessed once.
275         }
276
277         [Map]
278         [CLSCompliant (false)]
279         public enum PosixMadviseAdvice : int {
280                 POSIX_MADV_NORMAL     = 0,  // No further special treatment.
281                 POSIX_MADV_RANDOM     = 1,  // Expect random page references.
282                 POSIX_MADV_SEQUENTIAL = 2,  // Expect sequential page references.
283                 POSIX_MADV_WILLNEED   = 3,  // Will need these pages.
284                 POSIX_MADV_DONTNEED   = 4,  // Don't need these pages.
285         }
286
287         [Map]
288         public enum Signum : int {
289                 SIGHUP    =  1, // Hangup (POSIX).
290                 SIGINT    =  2, // Interrupt (ANSI).
291                 SIGQUIT   =  3, // Quit (POSIX).
292                 SIGILL    =  4, // Illegal instruction (ANSI).
293                 SIGTRAP   =  5, // Trace trap (POSIX).
294                 SIGABRT   =  6, // Abort (ANSI).
295                 SIGIOT    =  6, // IOT trap (4.2 BSD).
296                 SIGBUS    =  7, // BUS error (4.2 BSD).
297                 SIGFPE    =  8, // Floating-point exception (ANSI).
298                 SIGKILL   =  9, // Kill, unblockable (POSIX).
299                 SIGUSR1   = 10, // User-defined signal 1 (POSIX).
300                 SIGSEGV   = 11, // Segmentation violation (ANSI).
301                 SIGUSR2   = 12, // User-defined signal 2 (POSIX).
302                 SIGPIPE   = 13, // Broken pipe (POSIX).
303                 SIGALRM   = 14, // Alarm clock (POSIX).
304                 SIGTERM   = 15, // Termination (ANSI).
305                 SIGSTKFLT = 16, // Stack fault.
306                 SIGCLD    = SIGCHLD, // Same as SIGCHLD (System V).
307                 SIGCHLD   = 17, // Child status has changed (POSIX).
308                 SIGCONT   = 18, // Continue (POSIX).
309                 SIGSTOP   = 19, // Stop, unblockable (POSIX).
310                 SIGTSTP   = 20, // Keyboard stop (POSIX).
311                 SIGTTIN   = 21, // Background read from tty (POSIX).
312                 SIGTTOU   = 22, // Background write to tty (POSIX).
313                 SIGURG    = 23, // Urgent condition on socket (4.2 BSD).
314                 SIGXCPU   = 24, // CPU limit exceeded (4.2 BSD).
315                 SIGXFSZ   = 25, // File size limit exceeded (4.2 BSD).
316                 SIGVTALRM = 26, // Virtual alarm clock (4.2 BSD).
317                 SIGPROF   = 27, // Profiling alarm clock (4.2 BSD).
318                 SIGWINCH  = 28, // Window size change (4.3 BSD, Sun).
319                 SIGPOLL   = SIGIO, // Pollable event occurred (System V).
320                 SIGIO     = 29, // I/O now possible (4.2 BSD).
321                 SIGPWR    = 30, // Power failure restart (System V).
322                 SIGSYS    = 31, // Bad system call.
323                 SIGUNUSED = 31
324         }
325
326         [Flags][Map]
327         public enum WaitOptions : int {
328                 WNOHANG   = 1,  // Don't block waiting
329                 WUNTRACED = 2,  // Report status of stopped children
330         }
331
332   [Flags][Map]
333         [CLSCompliant (false)]
334         public enum AccessModes : int {
335                 R_OK = 1,
336                 W_OK = 2,
337                 X_OK = 4,
338                 F_OK = 8,
339         }
340
341         [Map]
342         [CLSCompliant (false)]
343         public enum PathconfName : int {
344                 _PC_LINK_MAX,
345                 _PC_MAX_CANON,
346                 _PC_MAX_INPUT,
347                 _PC_NAME_MAX,
348                 _PC_PATH_MAX,
349                 _PC_PIPE_BUF,
350                 _PC_CHOWN_RESTRICTED,
351                 _PC_NO_TRUNC,
352                 _PC_VDISABLE,
353                 _PC_SYNC_IO,
354                 _PC_ASYNC_IO,
355                 _PC_PRIO_IO,
356                 _PC_SOCK_MAXBUF,
357                 _PC_FILESIZEBITS,
358                 _PC_REC_INCR_XFER_SIZE,
359                 _PC_REC_MAX_XFER_SIZE,
360                 _PC_REC_MIN_XFER_SIZE,
361                 _PC_REC_XFER_ALIGN,
362                 _PC_ALLOC_SIZE_MIN,
363                 _PC_SYMLINK_MAX,
364                 _PC_2_SYMLINKS
365         }
366
367         [Map]
368         [CLSCompliant (false)]
369         public enum SysconfName : int {
370                 _SC_ARG_MAX,
371                 _SC_CHILD_MAX,
372                 _SC_CLK_TCK,
373                 _SC_NGROUPS_MAX,
374                 _SC_OPEN_MAX,
375                 _SC_STREAM_MAX,
376                 _SC_TZNAME_MAX,
377                 _SC_JOB_CONTROL,
378                 _SC_SAVED_IDS,
379                 _SC_REALTIME_SIGNALS,
380                 _SC_PRIORITY_SCHEDULING,
381                 _SC_TIMERS,
382                 _SC_ASYNCHRONOUS_IO,
383                 _SC_PRIORITIZED_IO,
384                 _SC_SYNCHRONIZED_IO,
385                 _SC_FSYNC,
386                 _SC_MAPPED_FILES,
387                 _SC_MEMLOCK,
388                 _SC_MEMLOCK_RANGE,
389                 _SC_MEMORY_PROTECTION,
390                 _SC_MESSAGE_PASSING,
391                 _SC_SEMAPHORES,
392                 _SC_SHARED_MEMORY_OBJECTS,
393                 _SC_AIO_LISTIO_MAX,
394                 _SC_AIO_MAX,
395                 _SC_AIO_PRIO_DELTA_MAX,
396                 _SC_DELAYTIMER_MAX,
397                 _SC_MQ_OPEN_MAX,
398                 _SC_MQ_PRIO_MAX,
399                 _SC_VERSION,
400                 _SC_PAGESIZE,
401                 _SC_RTSIG_MAX,
402                 _SC_SEM_NSEMS_MAX,
403                 _SC_SEM_VALUE_MAX,
404                 _SC_SIGQUEUE_MAX,
405                 _SC_TIMER_MAX,
406                 /* Values for the argument to `sysconf'
407                          corresponding to _POSIX2_* symbols.  */
408                 _SC_BC_BASE_MAX,
409                 _SC_BC_DIM_MAX,
410                 _SC_BC_SCALE_MAX,
411                 _SC_BC_STRING_MAX,
412                 _SC_COLL_WEIGHTS_MAX,
413                 _SC_EQUIV_CLASS_MAX,
414                 _SC_EXPR_NEST_MAX,
415                 _SC_LINE_MAX,
416                 _SC_RE_DUP_MAX,
417                 _SC_CHARCLASS_NAME_MAX,
418                 _SC_2_VERSION,
419                 _SC_2_C_BIND,
420                 _SC_2_C_DEV,
421                 _SC_2_FORT_DEV,
422                 _SC_2_FORT_RUN,
423                 _SC_2_SW_DEV,
424                 _SC_2_LOCALEDEF,
425                 _SC_PII,
426                 _SC_PII_XTI,
427                 _SC_PII_SOCKET,
428                 _SC_PII_INTERNET,
429                 _SC_PII_OSI,
430                 _SC_POLL,
431                 _SC_SELECT,
432                 _SC_UIO_MAXIOV,
433                 _SC_IOV_MAX = _SC_UIO_MAXIOV,
434                 _SC_PII_INTERNET_STREAM,
435                 _SC_PII_INTERNET_DGRAM,
436                 _SC_PII_OSI_COTS,
437                 _SC_PII_OSI_CLTS,
438                 _SC_PII_OSI_M,
439                 _SC_T_IOV_MAX,
440                 /* Values according to POSIX 1003.1c (POSIX threads).  */
441                 _SC_THREADS,
442                 _SC_THREAD_SAFE_FUNCTIONS,
443                 _SC_GETGR_R_SIZE_MAX,
444                 _SC_GETPW_R_SIZE_MAX,
445                 _SC_LOGIN_NAME_MAX,
446                 _SC_TTY_NAME_MAX,
447                 _SC_THREAD_DESTRUCTOR_ITERATIONS,
448                 _SC_THREAD_KEYS_MAX,
449                 _SC_THREAD_STACK_MIN,
450                 _SC_THREAD_THREADS_MAX,
451                 _SC_THREAD_ATTR_STACKADDR,
452                 _SC_THREAD_ATTR_STACKSIZE,
453                 _SC_THREAD_PRIORITY_SCHEDULING,
454                 _SC_THREAD_PRIO_INHERIT,
455                 _SC_THREAD_PRIO_PROTECT,
456                 _SC_THREAD_PROCESS_SHARED,
457                 _SC_NPROCESSORS_CONF,
458                 _SC_NPROCESSORS_ONLN,
459                 _SC_PHYS_PAGES,
460                 _SC_AVPHYS_PAGES,
461                 _SC_ATEXIT_MAX,
462                 _SC_PASS_MAX,
463                 _SC_XOPEN_VERSION,
464                 _SC_XOPEN_XCU_VERSION,
465                 _SC_XOPEN_UNIX,
466                 _SC_XOPEN_CRYPT,
467                 _SC_XOPEN_ENH_I18N,
468                 _SC_XOPEN_SHM,
469                 _SC_2_CHAR_TERM,
470                 _SC_2_C_VERSION,
471                 _SC_2_UPE,
472                 _SC_XOPEN_XPG2,
473                 _SC_XOPEN_XPG3,
474                 _SC_XOPEN_XPG4,
475                 _SC_CHAR_BIT,
476                 _SC_CHAR_MAX,
477                 _SC_CHAR_MIN,
478                 _SC_INT_MAX,
479                 _SC_INT_MIN,
480                 _SC_LONG_BIT,
481                 _SC_WORD_BIT,
482                 _SC_MB_LEN_MAX,
483                 _SC_NZERO,
484                 _SC_SSIZE_MAX,
485                 _SC_SCHAR_MAX,
486                 _SC_SCHAR_MIN,
487                 _SC_SHRT_MAX,
488                 _SC_SHRT_MIN,
489                 _SC_UCHAR_MAX,
490                 _SC_UINT_MAX,
491                 _SC_ULONG_MAX,
492                 _SC_USHRT_MAX,
493                 _SC_NL_ARGMAX,
494                 _SC_NL_LANGMAX,
495                 _SC_NL_MSGMAX,
496                 _SC_NL_NMAX,
497                 _SC_NL_SETMAX,
498                 _SC_NL_TEXTMAX,
499                 _SC_XBS5_ILP32_OFF32,
500                 _SC_XBS5_ILP32_OFFBIG,
501                 _SC_XBS5_LP64_OFF64,
502                 _SC_XBS5_LPBIG_OFFBIG,
503                 _SC_XOPEN_LEGACY,
504                 _SC_XOPEN_REALTIME,
505                 _SC_XOPEN_REALTIME_THREADS,
506                 _SC_ADVISORY_INFO,
507                 _SC_BARRIERS,
508                 _SC_BASE,
509                 _SC_C_LANG_SUPPORT,
510                 _SC_C_LANG_SUPPORT_R,
511                 _SC_CLOCK_SELECTION,
512                 _SC_CPUTIME,
513                 _SC_THREAD_CPUTIME,
514                 _SC_DEVICE_IO,
515                 _SC_DEVICE_SPECIFIC,
516                 _SC_DEVICE_SPECIFIC_R,
517                 _SC_FD_MGMT,
518                 _SC_FIFO,
519                 _SC_PIPE,
520                 _SC_FILE_ATTRIBUTES,
521                 _SC_FILE_LOCKING,
522                 _SC_FILE_SYSTEM,
523                 _SC_MONOTONIC_CLOCK,
524                 _SC_MULTI_PROCESS,
525                 _SC_SINGLE_PROCESS,
526                 _SC_NETWORKING,
527                 _SC_READER_WRITER_LOCKS,
528                 _SC_SPIN_LOCKS,
529                 _SC_REGEXP,
530                 _SC_REGEX_VERSION,
531                 _SC_SHELL,
532                 _SC_SIGNALS,
533                 _SC_SPAWN,
534                 _SC_SPORADIC_SERVER,
535                 _SC_THREAD_SPORADIC_SERVER,
536                 _SC_SYSTEM_DATABASE,
537                 _SC_SYSTEM_DATABASE_R,
538                 _SC_TIMEOUTS,
539                 _SC_TYPED_MEMORY_OBJECTS,
540                 _SC_USER_GROUPS,
541                 _SC_USER_GROUPS_R,
542                 _SC_2_PBS,
543                 _SC_2_PBS_ACCOUNTING,
544                 _SC_2_PBS_LOCATE,
545                 _SC_2_PBS_MESSAGE,
546                 _SC_2_PBS_TRACK,
547                 _SC_SYMLOOP_MAX,
548                 _SC_STREAMS,
549                 _SC_2_PBS_CHECKPOINT,
550                 _SC_V6_ILP32_OFF32,
551                 _SC_V6_ILP32_OFFBIG,
552                 _SC_V6_LP64_OFF64,
553                 _SC_V6_LPBIG_OFFBIG,
554                 _SC_HOST_NAME_MAX,
555                 _SC_TRACE,
556                 _SC_TRACE_EVENT_FILTER,
557                 _SC_TRACE_INHERIT,
558                 _SC_TRACE_LOG,
559                 _SC_LEVEL1_ICACHE_SIZE,
560                 _SC_LEVEL1_ICACHE_ASSOC,
561                 _SC_LEVEL1_ICACHE_LINESIZE,
562                 _SC_LEVEL1_DCACHE_SIZE,
563                 _SC_LEVEL1_DCACHE_ASSOC,
564                 _SC_LEVEL1_DCACHE_LINESIZE,
565                 _SC_LEVEL2_CACHE_SIZE,
566                 _SC_LEVEL2_CACHE_ASSOC,
567                 _SC_LEVEL2_CACHE_LINESIZE,
568                 _SC_LEVEL3_CACHE_SIZE,
569                 _SC_LEVEL3_CACHE_ASSOC,
570                 _SC_LEVEL3_CACHE_LINESIZE,
571                 _SC_LEVEL4_CACHE_SIZE,
572                 _SC_LEVEL4_CACHE_ASSOC,
573                 _SC_LEVEL4_CACHE_LINESIZE
574         }
575
576         [Map]
577         [CLSCompliant (false)]
578         public enum ConfstrName : int {
579                 _CS_PATH,                       /* The default search path.  */
580                 _CS_V6_WIDTH_RESTRICTED_ENVS,
581                 _CS_GNU_LIBC_VERSION,
582                 _CS_GNU_LIBPTHREAD_VERSION,
583                 _CS_LFS_CFLAGS = 1000,
584                 _CS_LFS_LDFLAGS,
585                 _CS_LFS_LIBS,
586                 _CS_LFS_LINTFLAGS,
587                 _CS_LFS64_CFLAGS,
588                 _CS_LFS64_LDFLAGS,
589                 _CS_LFS64_LIBS,
590                 _CS_LFS64_LINTFLAGS,
591                 _CS_XBS5_ILP32_OFF32_CFLAGS = 1100,
592                 _CS_XBS5_ILP32_OFF32_LDFLAGS,
593                 _CS_XBS5_ILP32_OFF32_LIBS,
594                 _CS_XBS5_ILP32_OFF32_LINTFLAGS,
595                 _CS_XBS5_ILP32_OFFBIG_CFLAGS,
596                 _CS_XBS5_ILP32_OFFBIG_LDFLAGS,
597                 _CS_XBS5_ILP32_OFFBIG_LIBS,
598                 _CS_XBS5_ILP32_OFFBIG_LINTFLAGS,
599                 _CS_XBS5_LP64_OFF64_CFLAGS,
600                 _CS_XBS5_LP64_OFF64_LDFLAGS,
601                 _CS_XBS5_LP64_OFF64_LIBS,
602                 _CS_XBS5_LP64_OFF64_LINTFLAGS,
603                 _CS_XBS5_LPBIG_OFFBIG_CFLAGS,
604                 _CS_XBS5_LPBIG_OFFBIG_LDFLAGS,
605                 _CS_XBS5_LPBIG_OFFBIG_LIBS,
606                 _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS,
607                 _CS_POSIX_V6_ILP32_OFF32_CFLAGS,
608                 _CS_POSIX_V6_ILP32_OFF32_LDFLAGS,
609                 _CS_POSIX_V6_ILP32_OFF32_LIBS,
610                 _CS_POSIX_V6_ILP32_OFF32_LINTFLAGS,
611                 _CS_POSIX_V6_ILP32_OFFBIG_CFLAGS,
612                 _CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS,
613                 _CS_POSIX_V6_ILP32_OFFBIG_LIBS,
614                 _CS_POSIX_V6_ILP32_OFFBIG_LINTFLAGS,
615                 _CS_POSIX_V6_LP64_OFF64_CFLAGS,
616                 _CS_POSIX_V6_LP64_OFF64_LDFLAGS,
617                 _CS_POSIX_V6_LP64_OFF64_LIBS,
618                 _CS_POSIX_V6_LP64_OFF64_LINTFLAGS,
619                 _CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS,
620                 _CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS,
621                 _CS_POSIX_V6_LPBIG_OFFBIG_LIBS,
622                 _CS_POSIX_V6_LPBIG_OFFBIG_LINTFLAGS
623         }
624
625         [Map]
626         [CLSCompliant (false)]
627         public enum LockfCommand : int {
628                 F_ULOCK = 0, // Unlock a previously locked region.
629                 F_LOCK  = 1, // Lock a region for exclusive use.
630                 F_TLOCK = 2, // Test and lock a region for exclusive use.
631                 F_TEST  = 3, // Test a region for other process locks.
632         }
633
634         [Map][Flags]
635         public enum PollEvents : short {
636                 POLLIN      = 0x0001, // There is data to read
637                 POLLPRI     = 0x0002, // There is urgent data to read
638                 POLLOUT     = 0x0004, // Writing now will not block
639                 POLLERR     = 0x0008, // Error condition
640                 POLLHUP     = 0x0010, // Hung up
641                 POLLNVAL    = 0x0020, // Invalid request; fd not open
642                 // XPG4.2 definitions (via _XOPEN_SOURCE)
643                 POLLRDNORM  = 0x0040, // Normal data may be read
644                 POLLRDBAND  = 0x0080, // Priority data may be read
645                 POLLWRNORM  = 0x0100, // Writing now will not block
646                 POLLWRBAND  = 0x0200, // Priority data may be written
647         }
648
649         [Map][Flags]
650         [CLSCompliant (false)]
651         public enum XattrFlags : int {
652                 XATTR_AUTO = 0,
653                 XATTR_CREATE = 1,
654                 XATTR_REPLACE = 2,
655         }
656
657         [Map][Flags]
658         [CLSCompliant (false)]
659         public enum MountFlags : ulong {
660                 ST_RDONLY      =    1,  // Mount read-only
661                 ST_NOSUID      =    2,  // Ignore suid and sgid bits
662                 ST_NODEV       =    4,  // Disallow access to device special files
663                 ST_NOEXEC      =    8,  // Disallow program execution
664                 ST_SYNCHRONOUS =   16,  // Writes are synced at once
665                 ST_REMOUNT     =   32,  // Alter flags of a mounted FS
666                 ST_MANDLOCK    =   64,  // Allow mandatory locks on an FS
667                 ST_WRITE       =  128,  // Write on file/directory/symlink
668                 ST_APPEND      =  256,  // Append-only file
669                 ST_IMMUTABLE   =  512,  // Immutable file
670                 ST_NOATIME     = 1024,  // Do not update access times
671                 ST_NODIRATIME  = 2048,  // Do not update directory access times
672                 ST_BIND        = 4096,  // Bind directory at different place
673         }
674
675         [Map][Flags]
676         [CLSCompliant (false)]
677         public enum MmapFlags : int {
678                 MAP_SHARED      = 0x01,     // Share changes.
679                 MAP_PRIVATE     = 0x02,     // Changes are private.
680                 MAP_TYPE        = 0x0f,     // Mask for type of mapping.
681                 MAP_FIXED       = 0x10,     // Interpret addr exactly.
682                 MAP_FILE        = 0,
683                 MAP_ANONYMOUS   = 0x20,     // Don't use a file.
684                 MAP_ANON        = MAP_ANONYMOUS,
685
686                 // These are Linux-specific.
687                 MAP_GROWSDOWN   = 0x00100,  // Stack-like segment.
688                 MAP_DENYWRITE   = 0x00800,  // ETXTBSY
689                 MAP_EXECUTABLE  = 0x01000,  // Mark it as an executable.
690                 MAP_LOCKED      = 0x02000,  // Lock the mapping.
691                 MAP_NORESERVE   = 0x04000,  // Don't check for reservations.
692                 MAP_POPULATE    = 0x08000,  // Populate (prefault) pagetables.
693                 MAP_NONBLOCK    = 0x10000,  // Do not block on IO.
694         }
695
696         [Map][Flags]
697         [CLSCompliant (false)]
698         public enum MmapProts : int {
699                 PROT_READ       = 0x1,  // Page can be read.
700                 PROT_WRITE      = 0x2,  // Page can be written.
701                 PROT_EXEC       = 0x4,  // Page can be executed.
702                 PROT_NONE       = 0x0,  // Page can not be accessed.
703                 PROT_GROWSDOWN  = 0x01000000, // Extend change to start of
704                                               //   growsdown vma (mprotect only).
705                 PROT_GROWSUP    = 0x02000000, // Extend change to start of
706                                               //   growsup vma (mprotect only).
707         }
708
709         [Map][Flags]
710         [CLSCompliant (false)]
711         public enum MsyncFlags : int {
712                 MS_ASYNC      = 0x1,  // Sync memory asynchronously.
713                 MS_SYNC       = 0x4,  // Synchronous memory sync.
714                 MS_INVALIDATE = 0x2,  // Invalidate the caches.
715         }
716
717         [Map][Flags]
718         [CLSCompliant (false)]
719         public enum MlockallFlags : int {
720                 MCL_CURRENT     = 0x1,  // Lock all currently mapped pages.
721                 MCL_FUTURE  = 0x2,      // Lock all additions to address
722         }
723
724         [Map][Flags]
725         [CLSCompliant (false)]
726         public enum MremapFlags : ulong {
727                 MREMAP_MAYMOVE = 0x1,
728         }
729
730         [Map]
731         [CLSCompliant (false)]
732         public enum UnixSocketType : int {
733                 SOCK_STREAM    =  1, // Byte-stream socket
734                 SOCK_DGRAM     =  2, // Datagram socket
735                 SOCK_RAW       =  3, // Raw protocol interface (linux specific)
736                 SOCK_RDM       =  4, // Reliably-delivered messages (linux specific)
737                 SOCK_SEQPACKET =  5, // Sequenced-packet socket
738                 SOCK_DCCP      =  6, // Datagram Congestion Control Protocol (linux specific)
739                 SOCK_PACKET    = 10, // Linux specific
740         }
741
742         [Map][Flags]
743         [CLSCompliant (false)]
744         public enum UnixSocketFlags : int {
745                 SOCK_CLOEXEC  = 0x80000, /* Atomically set close-on-exec flag for the new descriptor(s). */
746                 SOCK_NONBLOCK = 0x00800, /* Atomically mark descriptor(s) as non-blocking. */
747         }
748
749         [Map]
750         [CLSCompliant (false)]
751         public enum UnixSocketProtocol : int {
752                 IPPROTO_ICMP    =    1, /* Internet Control Message Protocol */
753                 IPPROTO_IGMP    =    2, /* Internet Group Management Protocol */
754                 IPPROTO_IPIP    =    4, /* IPIP tunnels (older KA9Q tunnels use 94) */
755                 IPPROTO_TCP     =    6, /* Transmission Control Protocol */
756                 IPPROTO_EGP     =    8, /* Exterior Gateway Protocol */
757                 IPPROTO_PUP     =   12, /* PUP protocol */
758                 IPPROTO_UDP     =   17, /* User Datagram Protocol */
759                 IPPROTO_IDP     =   22, /* XNS IDP protocol */
760                 IPPROTO_TP      =   29, /* SO Transport Protocol Class 4 */
761                 IPPROTO_DCCP    =   33, /* Datagram Congestion Control Protocol */
762                 IPPROTO_IPV6    =   41, /* IPv6-in-IPv4 tunnelling */
763                 IPPROTO_RSVP    =   46, /* RSVP Protocol */
764                 IPPROTO_GRE     =   47, /* Cisco GRE tunnels (rfc 1701,1702) */
765                 IPPROTO_ESP     =   50, /* Encapsulation Security Payload protocol */
766                 IPPROTO_AH      =   51, /* Authentication Header protocol */
767                 IPPROTO_MTP     =   92, /* Multicast Transport Protocol */
768                 IPPROTO_BEETPH  =   94, /* IP option pseudo header for BEET */
769                 IPPROTO_ENCAP   =   98, /* Encapsulation Header */
770                 IPPROTO_PIM     =  103, /* Protocol Independent Multicast */
771                 IPPROTO_COMP    =  108, /* Compression Header Protocol */
772                 IPPROTO_SCTP    =  132, /* Stream Control Transport Protocol */
773                 IPPROTO_UDPLITE =  136, /* UDP-Lite (RFC 3828) */
774                 IPPROTO_RAW     =  255, /* Raw IP packets */
775
776                 // Number used by linux (0) has a special meaning for socket()
777                 IPPROTO_IP      = 1024, /* Dummy protocol for TCP */
778                 // Number used by linux (1) clashes with IPPROTO_ICMP
779                 SOL_SOCKET      = 2048, /* For setsockopt() / getsockopt(): Options to be accessed at socket level, not protocol level. */
780         }
781
782         [Map]
783         [CLSCompliant (false)]
784         public enum UnixAddressFamily : int {
785                 AF_UNSPEC     =  0,  /* Unspecified. */
786                 AF_UNIX       =  1,  /* Local to host (pipes and file-domain). */
787                 AF_INET       =  2,  /* IP protocol family. */
788                 AF_AX25       =  3,  /* Amateur Radio AX.25. */
789                 AF_IPX        =  4,  /* Novell Internet Protocol. */
790                 AF_APPLETALK  =  5,  /* Appletalk DDP. */
791                 AF_NETROM     =  6,  /* Amateur radio NetROM. */
792                 AF_BRIDGE     =  7,  /* Multiprotocol bridge. */
793                 AF_ATMPVC     =  8,  /* ATM PVCs. */
794                 AF_X25        =  9,  /* Reserved for X.25 project. */
795                 AF_INET6      = 10,  /* IP version 6. */
796                 AF_ROSE       = 11,  /* Amateur Radio X.25 PLP. */
797                 AF_DECnet     = 12,  /* Reserved for DECnet project. */
798                 AF_NETBEUI    = 13,  /* Reserved for 802.2LLC project. */
799                 AF_SECURITY   = 14,  /* Security callback pseudo AF. */
800                 AF_KEY        = 15,  /* PF_KEY key management API. */
801                 AF_NETLINK    = 16,
802                 AF_PACKET     = 17,  /* Packet family. */
803                 AF_ASH        = 18,  /* Ash. */
804                 AF_ECONET     = 19,  /* Acorn Econet. */
805                 AF_ATMSVC     = 20,  /* ATM SVCs. */
806                 AF_RDS        = 21,  /* RDS sockets. */
807                 AF_SNA        = 22,  /* Linux SNA Project */
808                 AF_IRDA       = 23,  /* IRDA sockets. */
809                 AF_PPPOX      = 24,  /* PPPoX sockets. */
810                 AF_WANPIPE    = 25,  /* Wanpipe API sockets. */
811                 AF_LLC        = 26,  /* Linux LLC. */
812                 AF_CAN        = 29,  /* Controller Area Network. */
813                 AF_TIPC       = 30,  /* TIPC sockets. */
814                 AF_BLUETOOTH  = 31,  /* Bluetooth sockets. */
815                 AF_IUCV       = 32,  /* IUCV sockets. */
816                 AF_RXRPC      = 33,  /* RxRPC sockets. */
817                 AF_ISDN       = 34,  /* mISDN sockets. */
818                 AF_PHONET     = 35,  /* Phonet sockets. */
819                 AF_IEEE802154 = 36,  /* IEEE 802.15.4 sockets. */
820                 AF_CAIF       = 37,  /* CAIF sockets. */
821                 AF_ALG        = 38,  /* Algorithm sockets. */
822                 AF_NFC        = 39,  /* NFC sockets. */
823                 AF_VSOCK      = 40,  /* vSockets. */
824         }
825
826         [Map]
827         [CLSCompliant (false)]
828         public enum UnixSocketOptionName : int {
829                 SO_DEBUG                         =  1,
830                 SO_REUSEADDR                     =  2,
831                 SO_TYPE                          =  3,
832                 SO_ERROR                         =  4,
833                 SO_DONTROUTE                     =  5,
834                 SO_BROADCAST                     =  6,
835                 SO_SNDBUF                        =  7,
836                 SO_RCVBUF                        =  8,
837                 SO_SNDBUFFORCE                   = 32,
838                 SO_RCVBUFFORCE                   = 33,
839                 SO_KEEPALIVE                     =  9,
840                 SO_OOBINLINE                     = 10,
841                 SO_NO_CHECK                      = 11,
842                 SO_PRIORITY                      = 12,
843                 SO_LINGER                        = 13,
844                 SO_BSDCOMPAT                     = 14,
845                 SO_REUSEPORT                     = 15,
846                 SO_PASSCRED                      = 16,
847                 SO_PEERCRED                      = 17,
848                 SO_RCVLOWAT                      = 18,
849                 SO_SNDLOWAT                      = 19,
850                 SO_RCVTIMEO                      = 20,
851                 SO_SNDTIMEO                      = 21,
852                 SO_SECURITY_AUTHENTICATION       = 22,
853                 SO_SECURITY_ENCRYPTION_TRANSPORT = 23,
854                 SO_SECURITY_ENCRYPTION_NETWORK   = 24,
855                 SO_BINDTODEVICE                  = 25,
856                 SO_ATTACH_FILTER                 = 26,
857                 SO_DETACH_FILTER                 = 27,
858                 SO_PEERNAME                      = 28,
859                 SO_TIMESTAMP                     = 29,
860                 SO_ACCEPTCONN                    = 30,
861                 SO_PEERSEC                       = 31,
862                 SO_PASSSEC                       = 34,
863                 SO_TIMESTAMPNS                   = 35,
864                 SO_MARK                          = 36,
865                 SO_TIMESTAMPING                  = 37,
866                 SO_PROTOCOL                      = 38,
867                 SO_DOMAIN                        = 39,
868                 SO_RXQ_OVFL                      = 40,
869                 SO_WIFI_STATUS                   = 41,
870                 SO_PEEK_OFF                      = 42,
871                 SO_NOFCS                         = 43,
872                 SO_LOCK_FILTER                   = 44,
873                 SO_SELECT_ERR_QUEUE              = 45,
874                 SO_BUSY_POLL                     = 46,
875                 SO_MAX_PACING_RATE               = 47,
876         }
877
878         [Flags][Map]
879         [CLSCompliant (false)]
880         public enum MessageFlags : int {
881                 MSG_OOB          =       0x01, /* Process out-of-band data. */
882                 MSG_PEEK         =       0x02, /* Peek at incoming messages. */
883                 MSG_DONTROUTE    =       0x04, /* Don't use local routing. */
884                 MSG_CTRUNC       =       0x08, /* Control data lost before delivery. */
885                 MSG_PROXY        =       0x10, /* Supply or ask second address. */
886                 MSG_TRUNC        =       0x20,
887                 MSG_DONTWAIT     =       0x40, /* Nonblocking IO. */
888                 MSG_EOR          =       0x80, /* End of record. */
889                 MSG_WAITALL      =      0x100, /* Wait for a full request. */
890                 MSG_FIN          =      0x200,
891                 MSG_SYN          =      0x400,
892                 MSG_CONFIRM      =      0x800, /* Confirm path validity. */
893                 MSG_RST          =     0x1000,
894                 MSG_ERRQUEUE     =     0x2000, /* Fetch message from error queue. */
895                 MSG_NOSIGNAL     =     0x4000, /* Do not generate SIGPIPE. */
896                 MSG_MORE         =     0x8000, /* Sender will send more. */
897                 MSG_WAITFORONE   =    0x10000, /* Wait for at least one packet to return.*/
898                 MSG_FASTOPEN     = 0x20000000, /* Send data in TCP SYN. */
899                 MSG_CMSG_CLOEXEC = 0x40000000, /* Set close_on_exit for file descriptor received through SCM_RIGHTS. */
900         }
901
902         [Map]
903         [CLSCompliant (false)]
904         public enum ShutdownOption : int {
905                 SHUT_RD   = 0x01,   /* No more receptions. */
906                 SHUT_WR   = 0x02,   /* No more transmissions. */
907                 SHUT_RDWR = 0x03,   /* No more receptions or transmissions. */
908         }
909
910         #endregion
911
912         #region Structures
913
914         [Map ("struct flock")]
915         public struct Flock
916                 : IEquatable <Flock>
917         {
918                 [CLSCompliant (false)]
919                 public LockType         l_type;    // Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
920                 [CLSCompliant (false)]
921                 public SeekFlags        l_whence;  // How to interpret l_start
922                 [off_t] public long     l_start;   // Starting offset for lock
923                 [off_t] public long     l_len;     // Number of bytes to lock
924                 [pid_t] public int      l_pid;     // PID of process blocking our lock (F_GETLK only)
925
926                 public override int GetHashCode ()
927                 {
928                         return l_type.GetHashCode () ^ l_whence.GetHashCode () ^ 
929                                 l_start.GetHashCode () ^ l_len.GetHashCode () ^
930                                 l_pid.GetHashCode ();
931                 }
932
933                 public override bool Equals (object obj)
934                 {
935                         if ((obj == null) || (obj.GetType () != GetType ()))
936                                 return false;
937                         Flock value = (Flock) obj;
938                         return l_type == value.l_type && l_whence == value.l_whence && 
939                                 l_start == value.l_start && l_len == value.l_len && 
940                                 l_pid == value.l_pid;
941                 }
942
943                 public bool Equals (Flock value)
944                 {
945                         return l_type == value.l_type && l_whence == value.l_whence && 
946                                 l_start == value.l_start && l_len == value.l_len && 
947                                 l_pid == value.l_pid;
948                 }
949
950                 public static bool operator== (Flock lhs, Flock rhs)
951                 {
952                         return lhs.Equals (rhs);
953                 }
954
955                 public static bool operator!= (Flock lhs, Flock rhs)
956                 {
957                         return !lhs.Equals (rhs);
958                 }
959         }
960
961         [Map ("struct pollfd")]
962         public struct Pollfd
963                 : IEquatable <Pollfd>
964         {
965                 public int fd;
966                 [CLSCompliant (false)]
967                 public PollEvents events;
968                 [CLSCompliant (false)]
969                 public PollEvents revents;
970
971                 public override int GetHashCode ()
972                 {
973                         return events.GetHashCode () ^ revents.GetHashCode ();
974                 }
975
976                 public override bool Equals (object obj)
977                 {
978                         if (obj == null || obj.GetType () != GetType ())
979                                 return false;
980                         Pollfd value = (Pollfd) obj;
981                         return value.events == events && value.revents == revents;
982                 }
983
984                 public bool Equals (Pollfd value)
985                 {
986                         return value.events == events && value.revents == revents;
987                 }
988
989                 public static bool operator== (Pollfd lhs, Pollfd rhs)
990                 {
991                         return lhs.Equals (rhs);
992                 }
993
994                 public static bool operator!= (Pollfd lhs, Pollfd rhs)
995                 {
996                         return !lhs.Equals (rhs);
997                 }
998         }
999
1000         // Use manually written To/From methods to handle fields st_atime_nsec etc.
1001         public struct Stat
1002                 : IEquatable <Stat>
1003         {
1004                 [CLSCompliant (false)]
1005                 [dev_t]     public ulong    st_dev;     // device
1006                 [CLSCompliant (false)]
1007                 [ino_t]     public  ulong   st_ino;     // inode
1008                 [CLSCompliant (false)]
1009                 public  FilePermissions     st_mode;    // protection
1010                 [NonSerialized]
1011 #pragma warning disable 169             
1012                 private uint                _padding_;  // padding for structure alignment
1013 #pragma warning restore 169             
1014                 [CLSCompliant (false)]
1015                 [nlink_t]   public  ulong   st_nlink;   // number of hard links
1016                 [CLSCompliant (false)]
1017                 [uid_t]     public  uint    st_uid;     // user ID of owner
1018                 [CLSCompliant (false)]
1019                 [gid_t]     public  uint    st_gid;     // group ID of owner
1020                 [CLSCompliant (false)]
1021                 [dev_t]     public  ulong   st_rdev;    // device type (if inode device)
1022                 [off_t]     public  long    st_size;    // total size, in bytes
1023                 [blksize_t] public  long    st_blksize; // blocksize for filesystem I/O
1024                 [blkcnt_t]  public  long    st_blocks;  // number of blocks allocated
1025                 [time_t]    public  long    st_atime;   // time of last access
1026                 [time_t]    public  long    st_mtime;   // time of last modification
1027                 [time_t]    public  long    st_ctime;   // time of last status change
1028                 public  long             st_atime_nsec; // Timespec.tv_nsec partner to st_atime
1029                 public  long             st_mtime_nsec; // Timespec.tv_nsec partner to st_mtime
1030                 public  long             st_ctime_nsec; // Timespec.tv_nsec partner to st_ctime
1031
1032                 public Timespec st_atim {
1033                         get {
1034                                 return new Timespec { tv_sec = st_atime, tv_nsec = st_atime_nsec };
1035                         }
1036                         set {
1037                                 st_atime = value.tv_sec;
1038                                 st_atime_nsec = value.tv_nsec;
1039                         }
1040                 }
1041
1042                 public Timespec st_mtim {
1043                         get {
1044                                 return new Timespec { tv_sec = st_mtime, tv_nsec = st_mtime_nsec };
1045                         }
1046                         set {
1047                                 st_mtime = value.tv_sec;
1048                                 st_mtime_nsec = value.tv_nsec;
1049                         }
1050                 }
1051
1052                 public Timespec st_ctim {
1053                         get {
1054                                 return new Timespec { tv_sec = st_ctime, tv_nsec = st_ctime_nsec };
1055                         }
1056                         set {
1057                                 st_ctime = value.tv_sec;
1058                                 st_ctime_nsec = value.tv_nsec;
1059                         }
1060                 }
1061
1062                 public override int GetHashCode ()
1063                 {
1064                         return st_dev.GetHashCode () ^
1065                                 st_ino.GetHashCode () ^
1066                                 st_mode.GetHashCode () ^
1067                                 st_nlink.GetHashCode () ^
1068                                 st_uid.GetHashCode () ^
1069                                 st_gid.GetHashCode () ^
1070                                 st_rdev.GetHashCode () ^
1071                                 st_size.GetHashCode () ^
1072                                 st_blksize.GetHashCode () ^
1073                                 st_blocks.GetHashCode () ^
1074                                 st_atime.GetHashCode () ^
1075                                 st_mtime.GetHashCode () ^
1076                                 st_ctime.GetHashCode () ^
1077                                 st_atime_nsec.GetHashCode () ^
1078                                 st_mtime_nsec.GetHashCode () ^
1079                                 st_ctime_nsec.GetHashCode ();
1080                 }
1081
1082                 public override bool Equals (object obj)
1083                 {
1084                         if (obj == null || obj.GetType() != GetType ())
1085                                 return false;
1086                         Stat value = (Stat) obj;
1087                         return value.st_dev == st_dev &&
1088                                 value.st_ino == st_ino &&
1089                                 value.st_mode == st_mode &&
1090                                 value.st_nlink == st_nlink &&
1091                                 value.st_uid == st_uid &&
1092                                 value.st_gid == st_gid &&
1093                                 value.st_rdev == st_rdev &&
1094                                 value.st_size == st_size &&
1095                                 value.st_blksize == st_blksize &&
1096                                 value.st_blocks == st_blocks &&
1097                                 value.st_atime == st_atime &&
1098                                 value.st_mtime == st_mtime &&
1099                                 value.st_ctime == st_ctime &&
1100                                 value.st_atime_nsec == st_atime_nsec &&
1101                                 value.st_mtime_nsec == st_mtime_nsec &&
1102                                 value.st_ctime_nsec == st_ctime_nsec;
1103                 }
1104
1105                 public bool Equals (Stat value)
1106                 {
1107                         return value.st_dev == st_dev &&
1108                                 value.st_ino == st_ino &&
1109                                 value.st_mode == st_mode &&
1110                                 value.st_nlink == st_nlink &&
1111                                 value.st_uid == st_uid &&
1112                                 value.st_gid == st_gid &&
1113                                 value.st_rdev == st_rdev &&
1114                                 value.st_size == st_size &&
1115                                 value.st_blksize == st_blksize &&
1116                                 value.st_blocks == st_blocks &&
1117                                 value.st_atime == st_atime &&
1118                                 value.st_mtime == st_mtime &&
1119                                 value.st_ctime == st_ctime &&
1120                                 value.st_atime_nsec == st_atime_nsec &&
1121                                 value.st_mtime_nsec == st_mtime_nsec &&
1122                                 value.st_ctime_nsec == st_ctime_nsec;
1123                 }
1124
1125                 public static bool operator== (Stat lhs, Stat rhs)
1126                 {
1127                         return lhs.Equals (rhs);
1128                 }
1129
1130                 public static bool operator!= (Stat lhs, Stat rhs)
1131                 {
1132                         return !lhs.Equals (rhs);
1133                 }
1134         }
1135
1136         // `struct statvfs' isn't portable, so don't generate To/From methods.
1137         [Map]
1138         [CLSCompliant (false)]
1139         public struct Statvfs
1140                 : IEquatable <Statvfs>
1141         {
1142                 public                  ulong f_bsize;    // file system block size
1143                 public                  ulong f_frsize;   // fragment size
1144                 [fsblkcnt_t] public     ulong f_blocks;   // size of fs in f_frsize units
1145                 [fsblkcnt_t] public     ulong f_bfree;    // # free blocks
1146                 [fsblkcnt_t] public     ulong f_bavail;   // # free blocks for non-root
1147                 [fsfilcnt_t] public     ulong f_files;    // # inodes
1148                 [fsfilcnt_t] public     ulong f_ffree;    // # free inodes
1149                 [fsfilcnt_t] public     ulong f_favail;   // # free inodes for non-root
1150                 public                  ulong f_fsid;     // file system id
1151                 public MountFlags             f_flag;     // mount flags
1152                 public                  ulong f_namemax;  // maximum filename length
1153
1154                 public override int GetHashCode ()
1155                 {
1156                         return f_bsize.GetHashCode () ^
1157                                 f_frsize.GetHashCode () ^
1158                                 f_blocks.GetHashCode () ^
1159                                 f_bfree.GetHashCode () ^
1160                                 f_bavail.GetHashCode () ^
1161                                 f_files.GetHashCode () ^
1162                                 f_ffree.GetHashCode () ^
1163                                 f_favail.GetHashCode () ^
1164                                 f_fsid.GetHashCode () ^
1165                                 f_flag.GetHashCode () ^
1166                                 f_namemax.GetHashCode ();
1167                 }
1168
1169                 public override bool Equals (object obj)
1170                 {
1171                         if (obj == null || obj.GetType() != GetType ())
1172                                 return false;
1173                         Statvfs value = (Statvfs) obj;
1174                         return value.f_bsize == f_bsize &&
1175                                 value.f_frsize == f_frsize &&
1176                                 value.f_blocks == f_blocks &&
1177                                 value.f_bfree == f_bfree &&
1178                                 value.f_bavail == f_bavail &&
1179                                 value.f_files == f_files &&
1180                                 value.f_ffree == f_ffree &&
1181                                 value.f_favail == f_favail &&
1182                                 value.f_fsid == f_fsid &&
1183                                 value.f_flag == f_flag &&
1184                                 value.f_namemax == f_namemax;
1185                 }
1186
1187                 public bool Equals (Statvfs value)
1188                 {
1189                         return value.f_bsize == f_bsize &&
1190                                 value.f_frsize == f_frsize &&
1191                                 value.f_blocks == f_blocks &&
1192                                 value.f_bfree == f_bfree &&
1193                                 value.f_bavail == f_bavail &&
1194                                 value.f_files == f_files &&
1195                                 value.f_ffree == f_ffree &&
1196                                 value.f_favail == f_favail &&
1197                                 value.f_fsid == f_fsid &&
1198                                 value.f_flag == f_flag &&
1199                                 value.f_namemax == f_namemax;
1200                 }
1201
1202                 public static bool operator== (Statvfs lhs, Statvfs rhs)
1203                 {
1204                         return lhs.Equals (rhs);
1205                 }
1206
1207                 public static bool operator!= (Statvfs lhs, Statvfs rhs)
1208                 {
1209                         return !lhs.Equals (rhs);
1210                 }
1211         }
1212
1213         [Map ("struct timeval")]
1214         public struct Timeval
1215                 : IEquatable <Timeval>
1216         {
1217                 [time_t]      public long tv_sec;   // seconds
1218                 [suseconds_t] public long tv_usec;  // microseconds
1219
1220                 public override int GetHashCode ()
1221                 {
1222                         return tv_sec.GetHashCode () ^ tv_usec.GetHashCode ();
1223                 }
1224
1225                 public override bool Equals (object obj)
1226                 {
1227                         if (obj == null || obj.GetType () != GetType ())
1228                                 return false;
1229                         Timeval value = (Timeval) obj;
1230                         return value.tv_sec == tv_sec && value.tv_usec == tv_usec;
1231                 }
1232
1233                 public bool Equals (Timeval value)
1234                 {
1235                         return value.tv_sec == tv_sec && value.tv_usec == tv_usec;
1236                 }
1237
1238                 public static bool operator== (Timeval lhs, Timeval rhs)
1239                 {
1240                         return lhs.Equals (rhs);
1241                 }
1242
1243                 public static bool operator!= (Timeval lhs, Timeval rhs)
1244                 {
1245                         return !lhs.Equals (rhs);
1246                 }
1247         }
1248
1249         [Map ("struct timezone")]
1250         public struct Timezone
1251                 : IEquatable <Timezone>
1252         {
1253                 public  int tz_minuteswest; // minutes W of Greenwich
1254 #pragma warning disable 169             
1255                 private int tz_dsttime;     // type of dst correction (OBSOLETE)
1256 #pragma warning restore 169             
1257
1258                 public override int GetHashCode ()
1259                 {
1260                         return tz_minuteswest.GetHashCode ();
1261                 }
1262
1263                 public override bool Equals (object obj)
1264                 {
1265                         if (obj == null || obj.GetType () != GetType ())
1266                                 return false;
1267                         Timezone value = (Timezone) obj;
1268                         return value.tz_minuteswest == tz_minuteswest;
1269                 }
1270
1271                 public bool Equals (Timezone value)
1272                 {
1273                         return value.tz_minuteswest == tz_minuteswest;
1274                 }
1275
1276                 public static bool operator== (Timezone lhs, Timezone rhs)
1277                 {
1278                         return lhs.Equals (rhs);
1279                 }
1280
1281                 public static bool operator!= (Timezone lhs, Timezone rhs)
1282                 {
1283                         return !lhs.Equals (rhs);
1284                 }
1285         }
1286
1287         [Map ("struct utimbuf")]
1288         public struct Utimbuf
1289                 : IEquatable <Utimbuf>
1290         {
1291                 [time_t] public long    actime;   // access time
1292                 [time_t] public long    modtime;  // modification time
1293
1294                 public override int GetHashCode ()
1295                 {
1296                         return actime.GetHashCode () ^ modtime.GetHashCode ();
1297                 }
1298
1299                 public override bool Equals (object obj)
1300                 {
1301                         if (obj == null || obj.GetType () != GetType ())
1302                                 return false;
1303                         Utimbuf value = (Utimbuf) obj;
1304                         return value.actime == actime && value.modtime == modtime;
1305                 }
1306
1307                 public bool Equals (Utimbuf value)
1308                 {
1309                         return value.actime == actime && value.modtime == modtime;
1310                 }
1311
1312                 public static bool operator== (Utimbuf lhs, Utimbuf rhs)
1313                 {
1314                         return lhs.Equals (rhs);
1315                 }
1316
1317                 public static bool operator!= (Utimbuf lhs, Utimbuf rhs)
1318                 {
1319                         return !lhs.Equals (rhs);
1320                 }
1321         }
1322
1323         [Map ("struct timespec")]
1324         public struct Timespec
1325                 : IEquatable <Timespec>
1326         {
1327                 [time_t] public long    tv_sec;   // Seconds.
1328                 public          long    tv_nsec;  // Nanoseconds.
1329
1330                 public override int GetHashCode ()
1331                 {
1332                         return tv_sec.GetHashCode () ^ tv_nsec.GetHashCode ();
1333                 }
1334
1335                 public override bool Equals (object obj)
1336                 {
1337                         if (obj == null || obj.GetType () != GetType ())
1338                                 return false;
1339                         Timespec value = (Timespec) obj;
1340                         return value.tv_sec == tv_sec && value.tv_nsec == tv_nsec;
1341                 }
1342
1343                 public bool Equals (Timespec value)
1344                 {
1345                         return value.tv_sec == tv_sec && value.tv_nsec == tv_nsec;
1346                 }
1347
1348                 public static bool operator== (Timespec lhs, Timespec rhs)
1349                 {
1350                         return lhs.Equals (rhs);
1351                 }
1352
1353                 public static bool operator!= (Timespec lhs, Timespec rhs)
1354                 {
1355                         return !lhs.Equals (rhs);
1356                 }
1357         }
1358
1359         [Map ("struct iovec")]
1360         public struct Iovec
1361         {
1362                 public IntPtr   iov_base; // Starting address
1363                 [CLSCompliant (false)]
1364                 public ulong    iov_len;  // Number of bytes to transfer
1365         }
1366
1367         [Flags][Map]
1368         public enum EpollFlags {
1369                 EPOLL_CLOEXEC = 02000000,
1370                 EPOLL_NONBLOCK = 04000,
1371         }
1372
1373         [Flags][Map]
1374         [CLSCompliant (false)]
1375         public enum EpollEvents : uint {
1376                 EPOLLIN = 0x001,
1377                 EPOLLPRI = 0x002,
1378                 EPOLLOUT = 0x004,
1379                 EPOLLRDNORM = 0x040,
1380                 EPOLLRDBAND = 0x080,
1381                 EPOLLWRNORM = 0x100,
1382                 EPOLLWRBAND = 0x200,
1383                 EPOLLMSG = 0x400,
1384                 EPOLLERR = 0x008,
1385                 EPOLLHUP = 0x010,
1386                 EPOLLRDHUP = 0x2000,
1387                 EPOLLONESHOT = 1 << 30,
1388                 EPOLLET = unchecked ((uint) (1 << 31))
1389         }
1390
1391         public enum EpollOp {
1392                 EPOLL_CTL_ADD = 1,
1393                 EPOLL_CTL_DEL = 2,
1394                 EPOLL_CTL_MOD = 3,
1395         }
1396
1397         [StructLayout (LayoutKind.Explicit, Size=12, Pack=1)]
1398         [CLSCompliant (false)]
1399         public struct EpollEvent {
1400                 [FieldOffset (0)]
1401                 public EpollEvents events;
1402                 [FieldOffset (4)]
1403                 public int fd;
1404                 [FieldOffset (4)]
1405                 public IntPtr ptr;
1406                 [FieldOffset (4)]
1407                 public uint u32;
1408                 [FieldOffset (4)]
1409                 public ulong u64;
1410         }
1411
1412         [Map ("struct linger")]
1413         [CLSCompliant (false)]
1414         public struct Linger {
1415                 public int l_onoff;
1416                 public int l_linger;
1417         }
1418
1419         #endregion
1420
1421         #region Classes
1422
1423         public sealed class Dirent
1424                 : IEquatable <Dirent>
1425         {
1426                 [CLSCompliant (false)]
1427                 public /* ino_t */ ulong  d_ino;
1428                 public /* off_t */ long   d_off;
1429                 [CLSCompliant (false)]
1430                 public ushort             d_reclen;
1431                 public byte               d_type;
1432                 public string             d_name;
1433
1434                 public override int GetHashCode ()
1435                 {
1436                         return d_ino.GetHashCode () ^ d_off.GetHashCode () ^ 
1437                                 d_reclen.GetHashCode () ^ d_type.GetHashCode () ^
1438                                 d_name.GetHashCode ();
1439                 }
1440
1441                 public override bool Equals (object obj)
1442                 {
1443                         if (obj == null || GetType() != obj.GetType())
1444                                 return false;
1445                         Dirent d = (Dirent) obj;
1446                         return Equals (d);
1447                 }
1448
1449                 public bool Equals (Dirent value)
1450                 {
1451                         if (value == null)
1452                                 return false;
1453                         return value.d_ino == d_ino && value.d_off == d_off &&
1454                                 value.d_reclen == d_reclen && value.d_type == d_type &&
1455                                 value.d_name == d_name;
1456                 }
1457
1458                 public override string ToString ()
1459                 {
1460                         return d_name;
1461                 }
1462
1463                 public static bool operator== (Dirent lhs, Dirent rhs)
1464                 {
1465                         return Object.Equals (lhs, rhs);
1466                 }
1467
1468                 public static bool operator!= (Dirent lhs, Dirent rhs)
1469                 {
1470                         return !Object.Equals (lhs, rhs);
1471                 }
1472         }
1473
1474         public sealed class Fstab
1475                 : IEquatable <Fstab>
1476         {
1477                 public string fs_spec;
1478                 public string fs_file;
1479                 public string fs_vfstype;
1480                 public string fs_mntops;
1481                 public string fs_type;
1482                 public int    fs_freq;
1483                 public int    fs_passno;
1484
1485                 public override int GetHashCode ()
1486                 {
1487                         return fs_spec.GetHashCode () ^ fs_file.GetHashCode () ^
1488                                 fs_vfstype.GetHashCode () ^ fs_mntops.GetHashCode () ^
1489                                 fs_type.GetHashCode () ^ fs_freq ^ fs_passno;
1490                 }
1491
1492                 public override bool Equals (object obj)
1493                 {
1494                         if (obj == null || GetType() != obj.GetType())
1495                                 return false;
1496                         Fstab f = (Fstab) obj;
1497                         return Equals (f);
1498                 }
1499
1500                 public bool Equals (Fstab value)
1501                 {
1502                         if (value == null)
1503                                 return false;
1504                         return value.fs_spec == fs_spec && value.fs_file == fs_file &&
1505                                 value.fs_vfstype == fs_vfstype && value.fs_mntops == fs_mntops &&
1506                                 value.fs_type == fs_type && value.fs_freq == fs_freq && 
1507                                 value.fs_passno == fs_passno;
1508                 }
1509
1510                 public override string ToString ()
1511                 {
1512                         return fs_spec;
1513                 }
1514
1515                 public static bool operator== (Fstab lhs, Fstab rhs)
1516                 {
1517                         return Object.Equals (lhs, rhs);
1518                 }
1519
1520                 public static bool operator!= (Fstab lhs, Fstab rhs)
1521                 {
1522                         return !Object.Equals (lhs, rhs);
1523                 }
1524         }
1525
1526         public sealed class Group
1527                 : IEquatable <Group>
1528         {
1529                 public string           gr_name;
1530                 public string           gr_passwd;
1531                 [CLSCompliant (false)]
1532                 public /* gid_t */ uint gr_gid;
1533                 public string[]         gr_mem;
1534
1535                 public override int GetHashCode ()
1536                 {
1537                         int memhc = 0;
1538                         for (int i = 0; i < gr_mem.Length; ++i)
1539                                 memhc ^= gr_mem[i].GetHashCode ();
1540
1541                         return gr_name.GetHashCode () ^ gr_passwd.GetHashCode () ^ 
1542                                 gr_gid.GetHashCode () ^ memhc;
1543                 }
1544
1545                 public override bool Equals (object obj)
1546                 {
1547                         if (obj == null || GetType() != obj.GetType())
1548                                 return false;
1549                         Group g = (Group) obj;
1550                         return Equals (g);
1551                 }
1552
1553                 public bool Equals (Group value)
1554                 {
1555                         if (value == null)
1556                                 return false;
1557                         if (value.gr_gid != gr_gid)
1558                                 return false;
1559                         if (value.gr_gid == gr_gid && value.gr_name == gr_name &&
1560                                 value.gr_passwd == gr_passwd) {
1561                                 if (value.gr_mem == gr_mem)
1562                                         return true;
1563                                 if (value.gr_mem == null || gr_mem == null)
1564                                         return false;
1565                                 if (value.gr_mem.Length != gr_mem.Length)
1566                                         return false;
1567                                 for (int i = 0; i < gr_mem.Length; ++i)
1568                                         if (gr_mem[i] != value.gr_mem[i])
1569                                                 return false;
1570                                 return true;
1571                         }
1572                         return false;
1573                 }
1574
1575                 // Generate string in /etc/group format
1576                 public override string ToString ()
1577                 {
1578                         StringBuilder sb = new StringBuilder ();
1579                         sb.Append (gr_name).Append (":").Append (gr_passwd).Append (":");
1580                         sb.Append (gr_gid).Append (":");
1581                         GetMembers (sb, gr_mem);
1582                         return sb.ToString ();
1583                 }
1584
1585                 private static void GetMembers (StringBuilder sb, string[] members)
1586                 {
1587                         if (members.Length > 0)
1588                                 sb.Append (members[0]);
1589                         for (int i = 1; i < members.Length; ++i) {
1590                                 sb.Append (",");
1591                                 sb.Append (members[i]);
1592                         }
1593                 }
1594
1595                 public static bool operator== (Group lhs, Group rhs)
1596                 {
1597                         return Object.Equals (lhs, rhs);
1598                 }
1599
1600                 public static bool operator!= (Group lhs, Group rhs)
1601                 {
1602                         return !Object.Equals (lhs, rhs);
1603                 }
1604         }
1605
1606         public sealed class Passwd
1607                 : IEquatable <Passwd>
1608         {
1609                 public string           pw_name;
1610                 public string           pw_passwd;
1611                 [CLSCompliant (false)]
1612                 public /* uid_t */ uint pw_uid;
1613                 [CLSCompliant (false)]
1614                 public /* gid_t */ uint pw_gid;
1615                 public string           pw_gecos;
1616                 public string           pw_dir;
1617                 public string           pw_shell;
1618
1619                 public override int GetHashCode ()
1620                 {
1621                         return pw_name.GetHashCode () ^ pw_passwd.GetHashCode () ^ 
1622                                 pw_uid.GetHashCode () ^ pw_gid.GetHashCode () ^
1623                                 pw_gecos.GetHashCode () ^ pw_dir.GetHashCode () ^
1624                                 pw_dir.GetHashCode () ^ pw_shell.GetHashCode ();
1625                 }
1626
1627                 public override bool Equals (object obj)
1628                 {
1629                         if (obj == null || GetType() != obj.GetType())
1630                                 return false;
1631                         Passwd p = (Passwd) obj;
1632                         return Equals (p);
1633                 }
1634
1635                 public bool Equals (Passwd value)
1636                 {
1637                         if (value == null)
1638                                 return false;
1639                         return value.pw_uid == pw_uid && value.pw_gid == pw_gid && 
1640                                 value.pw_name == pw_name && value.pw_passwd == pw_passwd && 
1641                                 value.pw_gecos == pw_gecos && value.pw_dir == pw_dir && 
1642                                 value.pw_shell == pw_shell;
1643                 }
1644
1645                 // Generate string in /etc/passwd format
1646                 public override string ToString ()
1647                 {
1648                         return string.Format ("{0}:{1}:{2}:{3}:{4}:{5}:{6}",
1649                                 pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell);
1650                 }
1651
1652                 public static bool operator== (Passwd lhs, Passwd rhs)
1653                 {
1654                         return Object.Equals (lhs, rhs);
1655                 }
1656
1657                 public static bool operator!= (Passwd lhs, Passwd rhs)
1658                 {
1659                         return !Object.Equals (lhs, rhs);
1660                 }
1661         }
1662
1663         public sealed class Utsname
1664                 : IEquatable <Utsname>
1665         {
1666                 public string sysname;
1667                 public string nodename;
1668                 public string release;
1669                 public string version;
1670                 public string machine;
1671                 public string domainname;
1672
1673                 public override int GetHashCode ()
1674                 {
1675                         return sysname.GetHashCode () ^ nodename.GetHashCode () ^ 
1676                                 release.GetHashCode () ^ version.GetHashCode () ^
1677                                 machine.GetHashCode () ^ domainname.GetHashCode ();
1678                 }
1679
1680                 public override bool Equals (object obj)
1681                 {
1682                         if (obj == null || GetType() != obj.GetType())
1683                                 return false;
1684                         Utsname u = (Utsname) obj;
1685                         return Equals (u);
1686                 }
1687
1688                 public bool Equals (Utsname value)
1689                 {
1690                         return value.sysname == sysname && value.nodename == nodename && 
1691                                 value.release == release && value.version == version && 
1692                                 value.machine == machine && value.domainname == domainname;
1693                 }
1694
1695                 // Generate string in /etc/passwd format
1696                 public override string ToString ()
1697                 {
1698                         return string.Format ("{0} {1} {2} {3} {4}",
1699                                 sysname, nodename, release, version, machine);
1700                 }
1701
1702                 public static bool operator== (Utsname lhs, Utsname rhs)
1703                 {
1704                         return Object.Equals (lhs, rhs);
1705                 }
1706
1707                 public static bool operator!= (Utsname lhs, Utsname rhs)
1708                 {
1709                         return !Object.Equals (lhs, rhs);
1710                 }
1711         }
1712
1713         //
1714         // Convention: Functions *not* part of the standard C library AND part of
1715         // a POSIX and/or Unix standard (X/Open, SUS, XPG, etc.) go here.
1716         //
1717         // For example, the man page should be similar to:
1718         //
1719         //    CONFORMING TO (or CONFORMS TO)
1720         //           XPG2, SUSv2, POSIX, etc.
1721         //
1722         // BSD- and GNU-specific exports can also be placed here.
1723         //
1724         // Non-POSIX/XPG/etc. functions can also be placed here if:
1725         //  (a) They'd be likely to be covered in a Steven's-like book
1726         //  (b) The functions would be present in libc.so (or equivalent).
1727         //
1728         // If a function has its own library, that's a STRONG indicator that the
1729         // function should get a different binding, probably in its own assembly, 
1730         // so that package management can work sanely.  (That is, we'd like to avoid
1731         // scenarios where FooLib.dll is installed, but it requires libFooLib.so to
1732         // run, and libFooLib.so doesn't exist.  That would be confusing.)
1733         //
1734         // The only methods in here should be:
1735         //  (1) low-level functions
1736         //  (2) "Trivial" function overloads.  For example, if the parameters to a
1737         //      function are related (e.g. getgroups(2))
1738         //  (3) The return type SHOULD NOT be changed.  If you want to provide a
1739         //      convenience function with a nicer return type, place it into one of
1740         //      the Mono.Unix.Unix* wrapper classes, and give it a .NET-styled name.
1741         //      - EXCEPTION: No public functions should have a `void' return type.
1742         //        `void' return types should be replaced with `int'.
1743         //        Rationality: `void'-return functions typically require a
1744         //        complicated call sequence, such as clear errno, then call, then
1745         //        check errno to see if any errors occurred.  This sequence can't 
1746         //        be done safely in managed code, as errno may change as part of 
1747         //        the P/Invoke mechanism.
1748         //        Instead, add a MonoPosixHelper export which does:
1749         //          errno = 0;
1750         //          INVOKE SYSCALL;
1751         //          return errno == 0 ? 0 : -1;
1752         //        This lets managed code check the return value in the usual manner.
1753         //  (4) Exceptions SHOULD NOT be thrown.  EXCEPTIONS: 
1754         //      - If you're wrapping *broken* methods which make assumptions about 
1755         //        input data, such as that an argument refers to N bytes of data.  
1756         //        This is currently limited to cuserid(3) and encrypt(3).
1757         //      - If you call functions which themselves generate exceptions.  
1758         //        This is the case for using NativeConvert, which will throw an
1759         //        exception if an invalid/unsupported value is used.
1760         //
1761         // Naming Conventions:
1762         //  - Syscall method names should have the same name as the function being
1763         //    wrapped (e.g. Syscall.read ==> read(2)).  This allows people to
1764         //    consult the appropriate man page if necessary.
1765         //  - Methods need not have the same arguments IF this simplifies or
1766         //    permits correct usage.  The current example is syslog, in which
1767         //    syslog(3)'s single `priority' argument is split into SyslogFacility
1768         //    and SyslogLevel arguments.
1769         //  - Type names (structures, classes, enumerations) are always PascalCased.
1770         //  - Enumerations are named as <MethodName><ArgumentName>, and are located
1771         //    in the Mono.Unix.Native namespace.  For readability, if ArgumentName 
1772         //    is "cmd", use Command instead.  For example, fcntl(2) takes a
1773         //    FcntlCommand argument.  This naming convention is to provide an
1774         //    assocation between an enumeration and where it should be used, and
1775         //    allows a single method to accept multiple different enumerations 
1776         //    (see mmap(2), which takes MmapProts and MmapFlags).
1777         //    - EXCEPTION: if an enumeration is shared between multiple different
1778         //      methods, AND/OR the "obvious" enumeration name conflicts with an
1779         //      existing .NET type, a more appropriate name should be used.
1780         //      Example: FilePermissions
1781         //    - EXCEPTION: [Flags] enumerations should get plural names to follow
1782         //      .NET name guidelines.  Usually this doesn't result in a change
1783         //      (OpenFlags is the `flags' parameter for open(2)), but it can
1784         //      (mmap(2) prot ==> MmapProts, access(2) mode ==> AccessModes).
1785         //  - Enumerations should have the [Map] and (optional) [Flags] attributes.
1786         //    [Map] is required for make-map to find the type and generate the
1787         //    appropriate NativeConvert conversion functions.
1788         //  - Enumeration contents should match the original Unix names.  This helps
1789         //    with documentation (the existing man pages are still useful), and is
1790         //    required for use with the make-map generation program.
1791         //  - Structure names should be the PascalCased version of the actual
1792         //    structure name (struct flock ==> Flock).  Structure members should
1793         //    have the same names, or a (reasonably) portable subset (Dirent being
1794         //    the poster child for questionable members).
1795         //    - Whether the managed type should be a reference type (class) or a 
1796         //      value type (struct) should be determined on a case-by-case basis: 
1797         //      if you ever need to be able to use NULL for it (such as with Dirent, 
1798         //      Group, Passwd, as these are method return types and `null' is used 
1799         //      to signify the end), it should be a reference type; otherwise, use 
1800         //      your discretion, and keep any expected usage patterns in mind.
1801         //  - Syscall should be a Single Point Of Truth (SPOT).  There should be
1802         //    only ONE way to do anything.  By convention, the Linux function names
1803         //    are used, but that need not always be the case (use your discretion).
1804         //    It SHOULD NOT be required that developers know what platform they're
1805         //    on, and choose among a set of similar functions.  In short, anything
1806         //    that requires a platform check is BAD -- Mono.Unix is a wrapper, and
1807         //    we can afford to clean things up whenever possible.
1808         //    - Examples: 
1809         //      - Syscall.statfs: Solaris/Mac OS X provide statfs(2), Linux provides
1810         //        statvfs(2).  MonoPosixHelper will "thunk" between the two,
1811         //        exporting a statvfs that works across platforms.
1812         //      - Syscall.getfsent: Glibc export which Solaris lacks, while Solaris
1813         //        instead provides getvfsent(3).  MonoPosixHelper provides wrappers
1814         //        to convert getvfsent(3) into Fstab data.
1815         //    - Exception: If it isn't possible to cleanly wrap platforms, then the
1816         //      method shouldn't be exported.  The user will be expected to do their
1817         //      own platform check and their own DllImports.
1818         //      Examples: mount(2), umount(2), etc.
1819         //    - Note: if a platform doesn't support a function AT ALL, the
1820         //      MonoPosixHelper wrapper won't be compiled, resulting in a
1821         //      EntryPointNotFoundException.  This is also consistent with a missing 
1822         //      P/Invoke into libc.so.
1823         //
1824         [CLSCompliant (false)]
1825         public sealed class Syscall : Stdlib
1826         {
1827                 new internal const string LIBC  = "libc";
1828
1829                 private Syscall () {}
1830
1831                 //
1832                 // <aio.h>
1833                 //
1834
1835                 // TODO: aio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), 
1836                 // aio_return(3), aio_suspend(3), aio_write(3)
1837                 //
1838                 // Then update UnixStream.BeginRead to use the aio* functions.
1839
1840
1841                 #region <attr/xattr.h> Declarations
1842                 //
1843                 // <attr/xattr.h> -- COMPLETE
1844                 //
1845
1846                 // setxattr(2)
1847                 //    int setxattr (const char *path, const char *name,
1848                 //        const void *value, size_t size, int flags);
1849                 [DllImport (MPH, SetLastError=true,
1850                                 EntryPoint="Mono_Posix_Syscall_setxattr")]
1851                 public static extern int setxattr (
1852                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1853                                 string path, 
1854                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1855                                 string name, byte[] value, ulong size, XattrFlags flags);
1856
1857                 public static int setxattr (string path, string name, byte [] value, ulong size)
1858                 {
1859                         return setxattr (path, name, value, size, XattrFlags.XATTR_AUTO);
1860                 }
1861
1862                 public static int setxattr (string path, string name, byte [] value, XattrFlags flags)
1863                 {
1864                         return setxattr (path, name, value, (ulong) value.Length, flags);
1865                 }
1866
1867                 public static int setxattr (string path, string name, byte [] value)
1868                 {
1869                         return setxattr (path, name, value, (ulong) value.Length);
1870                 }
1871
1872                 // lsetxattr(2)
1873                 //        int lsetxattr (const char *path, const char *name,
1874                 //                   const void *value, size_t size, int flags);
1875                 [DllImport (MPH, SetLastError=true,
1876                                 EntryPoint="Mono_Posix_Syscall_lsetxattr")]
1877                 public static extern int lsetxattr (
1878                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1879                                 string path, 
1880                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1881                                 string name, byte[] value, ulong size, XattrFlags flags);
1882
1883                 public static int lsetxattr (string path, string name, byte [] value, ulong size)
1884                 {
1885                         return lsetxattr (path, name, value, size, XattrFlags.XATTR_AUTO);
1886                 }
1887
1888                 public static int lsetxattr (string path, string name, byte [] value, XattrFlags flags)
1889                 {
1890                         return lsetxattr (path, name, value, (ulong) value.Length, flags);
1891                 }
1892
1893                 public static int lsetxattr (string path, string name, byte [] value)
1894                 {
1895                         return lsetxattr (path, name, value, (ulong) value.Length);
1896                 }
1897
1898                 // fsetxattr(2)
1899                 //        int fsetxattr (int fd, const char *name,
1900                 //                   const void *value, size_t size, int flags);
1901                 [DllImport (MPH, SetLastError=true,
1902                                 EntryPoint="Mono_Posix_Syscall_fsetxattr")]
1903                 public static extern int fsetxattr (int fd, 
1904                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1905                                 string name, byte[] value, ulong size, XattrFlags flags);
1906
1907                 public static int fsetxattr (int fd, string name, byte [] value, ulong size)
1908                 {
1909                         return fsetxattr (fd, name, value, size, XattrFlags.XATTR_AUTO);
1910                 }
1911
1912                 public static int fsetxattr (int fd, string name, byte [] value, XattrFlags flags)
1913                 {
1914                         return fsetxattr (fd, name, value, (ulong) value.Length, flags);
1915                 }
1916
1917                 public static int fsetxattr (int fd, string name, byte [] value)
1918                 {
1919                         return fsetxattr (fd, name, value, (ulong) value.Length);
1920                 }
1921
1922                 // getxattr(2)
1923                 //        ssize_t getxattr (const char *path, const char *name,
1924                 //                      void *value, size_t size);
1925                 [DllImport (MPH, SetLastError=true,
1926                                 EntryPoint="Mono_Posix_Syscall_getxattr")]
1927                 public static extern long getxattr (
1928                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1929                                 string path, 
1930                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1931                                 string name, byte[] value, ulong size);
1932
1933                 public static long getxattr (string path, string name, byte [] value)
1934                 {
1935                         return getxattr (path, name, value, (ulong) value.Length);
1936                 }
1937
1938                 public static long getxattr (string path, string name, out byte [] value)
1939                 {
1940                         value = null;
1941                         long size = getxattr (path, name, value, 0);
1942                         if (size <= 0)
1943                                 return size;
1944
1945                         value = new byte [size];
1946                         return getxattr (path, name, value, (ulong) size);
1947                 }
1948
1949                 // lgetxattr(2)
1950                 //        ssize_t lgetxattr (const char *path, const char *name,
1951                 //                       void *value, size_t size);
1952                 [DllImport (MPH, SetLastError=true,
1953                                 EntryPoint="Mono_Posix_Syscall_lgetxattr")]
1954                 public static extern long lgetxattr (
1955                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1956                                 string path, 
1957                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1958                                 string name, byte[] value, ulong size);
1959
1960                 public static long lgetxattr (string path, string name, byte [] value)
1961                 {
1962                         return lgetxattr (path, name, value, (ulong) value.Length);
1963                 }
1964
1965                 public static long lgetxattr (string path, string name, out byte [] value)
1966                 {
1967                         value = null;
1968                         long size = lgetxattr (path, name, value, 0);
1969                         if (size <= 0)
1970                                 return size;
1971
1972                         value = new byte [size];
1973                         return lgetxattr (path, name, value, (ulong) size);
1974                 }
1975
1976                 // fgetxattr(2)
1977                 //        ssize_t fgetxattr (int fd, const char *name, void *value, size_t size);
1978                 [DllImport (MPH, SetLastError=true,
1979                                 EntryPoint="Mono_Posix_Syscall_fgetxattr")]
1980                 public static extern long fgetxattr (int fd, 
1981                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
1982                                 string name, byte[] value, ulong size);
1983
1984                 public static long fgetxattr (int fd, string name, byte [] value)
1985                 {
1986                         return fgetxattr (fd, name, value, (ulong) value.Length);
1987                 }
1988
1989                 public static long fgetxattr (int fd, string name, out byte [] value)
1990                 {
1991                         value = null;
1992                         long size = fgetxattr (fd, name, value, 0);
1993                         if (size <= 0)
1994                                 return size;
1995
1996                         value = new byte [size];
1997                         return fgetxattr (fd, name, value, (ulong) size);
1998                 }
1999
2000                 // listxattr(2)
2001                 //        ssize_t listxattr (const char *path, char *list, size_t size);
2002                 [DllImport (MPH, SetLastError=true,
2003                                 EntryPoint="Mono_Posix_Syscall_listxattr")]
2004                 public static extern long listxattr (
2005                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2006                                 string path, byte[] list, ulong size);
2007
2008                 // Slight modification: returns 0 on success, negative on error
2009                 public static long listxattr (string path, Encoding encoding, out string [] values)
2010                 {
2011                         values = null;
2012                         long size = listxattr (path, null, 0);
2013                         if (size == 0)
2014                                 values = new string [0];
2015                         if (size <= 0)
2016                                 return (int) size;
2017
2018                         byte[] list = new byte [size];
2019                         long ret = listxattr (path, list, (ulong) size);
2020                         if (ret < 0)
2021                                 return (int) ret;
2022
2023                         GetValues (list, encoding, out values);
2024                         return 0;
2025                 }
2026
2027                 public static long listxattr (string path, out string[] values)
2028                 {
2029                         return listxattr (path, UnixEncoding.Instance, out values);
2030                 }
2031
2032                 private static void GetValues (byte[] list, Encoding encoding, out string[] values)
2033                 {
2034                         int num_values = 0;
2035                         for (int i = 0; i < list.Length; ++i)
2036                                 if (list [i] == 0)
2037                                         ++num_values;
2038
2039                         values = new string [num_values];
2040                         num_values = 0;
2041                         int str_start = 0;
2042                         for (int i = 0; i < list.Length; ++i) {
2043                                 if (list [i] == 0) {
2044                                         values [num_values++] = encoding.GetString (list, str_start, i - str_start);
2045                                         str_start = i+1;
2046                                 }
2047                         }
2048                 }
2049
2050                 // llistxattr(2)
2051                 //        ssize_t llistxattr (const char *path, char *list, size_t size);
2052                 [DllImport (MPH, SetLastError=true,
2053                                 EntryPoint="Mono_Posix_Syscall_llistxattr")]
2054                 public static extern long llistxattr (
2055                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2056                                 string path, byte[] list, ulong size);
2057
2058                 // Slight modification: returns 0 on success, negative on error
2059                 public static long llistxattr (string path, Encoding encoding, out string [] values)
2060                 {
2061                         values = null;
2062                         long size = llistxattr (path, null, 0);
2063                         if (size == 0)
2064                                 values = new string [0];
2065                         if (size <= 0)
2066                                 return (int) size;
2067
2068                         byte[] list = new byte [size];
2069                         long ret = llistxattr (path, list, (ulong) size);
2070                         if (ret < 0)
2071                                 return (int) ret;
2072
2073                         GetValues (list, encoding, out values);
2074                         return 0;
2075                 }
2076
2077                 public static long llistxattr (string path, out string[] values)
2078                 {
2079                         return llistxattr (path, UnixEncoding.Instance, out values);
2080                 }
2081
2082                 // flistxattr(2)
2083                 //        ssize_t flistxattr (int fd, char *list, size_t size);
2084                 [DllImport (MPH, SetLastError=true,
2085                                 EntryPoint="Mono_Posix_Syscall_flistxattr")]
2086                 public static extern long flistxattr (int fd, byte[] list, ulong size);
2087
2088                 // Slight modification: returns 0 on success, negative on error
2089                 public static long flistxattr (int fd, Encoding encoding, out string [] values)
2090                 {
2091                         values = null;
2092                         long size = flistxattr (fd, null, 0);
2093                         if (size == 0)
2094                                 values = new string [0];
2095                         if (size <= 0)
2096                                 return (int) size;
2097
2098                         byte[] list = new byte [size];
2099                         long ret = flistxattr (fd, list, (ulong) size);
2100                         if (ret < 0)
2101                                 return (int) ret;
2102
2103                         GetValues (list, encoding, out values);
2104                         return 0;
2105                 }
2106
2107                 public static long flistxattr (int fd, out string[] values)
2108                 {
2109                         return flistxattr (fd, UnixEncoding.Instance, out values);
2110                 }
2111
2112                 [DllImport (MPH, SetLastError=true,
2113                                 EntryPoint="Mono_Posix_Syscall_removexattr")]
2114                 public static extern int removexattr (
2115                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2116                                 string path, 
2117                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2118                                 string name);
2119
2120                 [DllImport (MPH, SetLastError=true,
2121                                 EntryPoint="Mono_Posix_Syscall_lremovexattr")]
2122                 public static extern int lremovexattr (
2123                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2124                                 string path, 
2125                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2126                                 string name);
2127
2128                 [DllImport (MPH, SetLastError=true,
2129                                 EntryPoint="Mono_Posix_Syscall_fremovexattr")]
2130                 public static extern int fremovexattr (int fd, 
2131                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2132                                 string name);
2133                 #endregion
2134
2135                 #region <dirent.h> Declarations
2136                 //
2137                 // <dirent.h>
2138                 //
2139                 // TODO: scandir(3), alphasort(3), versionsort(3), getdirentries(3)
2140
2141                 [DllImport (LIBC, SetLastError=true)]
2142                 public static extern IntPtr opendir (
2143                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2144                                 string name);
2145
2146                 [DllImport (LIBC, SetLastError=true)]
2147                 public static extern int closedir (IntPtr dir);
2148
2149                 // seekdir(3):
2150                 //    void seekdir (DIR *dir, off_t offset);
2151                 //    Slight modification.  Returns -1 on error, 0 on success.
2152                 [DllImport (MPH, SetLastError=true,
2153                                 EntryPoint="Mono_Posix_Syscall_seekdir")]
2154                 public static extern int seekdir (IntPtr dir, long offset);
2155
2156                 // telldir(3)
2157                 //    off_t telldir(DIR *dir);
2158                 [DllImport (MPH, SetLastError=true,
2159                                 EntryPoint="Mono_Posix_Syscall_telldir")]
2160                 public static extern long telldir (IntPtr dir);
2161
2162                 [DllImport (MPH, SetLastError=true,
2163                                 EntryPoint="Mono_Posix_Syscall_rewinddir")]
2164                 public static extern int rewinddir (IntPtr dir);
2165
2166                 private struct _Dirent {
2167                         [ino_t] public ulong      d_ino;
2168                         [off_t] public long       d_off;
2169                         public ushort             d_reclen;
2170                         public byte               d_type;
2171                         public IntPtr             d_name;
2172                 }
2173
2174                 private static void CopyDirent (Dirent to, ref _Dirent from)
2175                 {
2176                         try {
2177                                 to.d_ino    = from.d_ino;
2178                                 to.d_off    = from.d_off;
2179                                 to.d_reclen = from.d_reclen;
2180                                 to.d_type   = from.d_type;
2181                                 to.d_name   = UnixMarshal.PtrToString (from.d_name);
2182                         }
2183                         finally {
2184                                 Stdlib.free (from.d_name);
2185                                 from.d_name = IntPtr.Zero;
2186                         }
2187                 }
2188
2189                 internal static object readdir_lock = new object ();
2190
2191                 [DllImport (MPH, SetLastError=true,
2192                                 EntryPoint="Mono_Posix_Syscall_readdir")]
2193                 private static extern int sys_readdir (IntPtr dir, out _Dirent dentry);
2194
2195                 public static Dirent readdir (IntPtr dir)
2196                 {
2197                         _Dirent dentry;
2198                         int r;
2199                         lock (readdir_lock) {
2200                                 r = sys_readdir (dir, out dentry);
2201                         }
2202                         if (r != 0)
2203                                 return null;
2204                         Dirent d = new Dirent ();
2205                         CopyDirent (d, ref dentry);
2206                         return d;
2207                 }
2208
2209                 [DllImport (MPH, SetLastError=true,
2210                                 EntryPoint="Mono_Posix_Syscall_readdir_r")]
2211                 private static extern int sys_readdir_r (IntPtr dirp, out _Dirent entry, out IntPtr result);
2212
2213                 public static int readdir_r (IntPtr dirp, Dirent entry, out IntPtr result)
2214                 {
2215                         entry.d_ino    = 0;
2216                         entry.d_off    = 0;
2217                         entry.d_reclen = 0;
2218                         entry.d_type   = 0;
2219                         entry.d_name   = null;
2220
2221                         _Dirent _d;
2222                         int r = sys_readdir_r (dirp, out _d, out result);
2223
2224                         if (r == 0 && result != IntPtr.Zero) {
2225                                 CopyDirent (entry, ref _d);
2226                         }
2227
2228                         return r;
2229                 }
2230
2231                 [DllImport (LIBC, SetLastError=true)]
2232                 public static extern int dirfd (IntPtr dir);
2233
2234                 [DllImport (LIBC, SetLastError=true)]
2235                 public static extern IntPtr fdopendir (int fd);
2236                 #endregion
2237
2238                 #region <fcntl.h> Declarations
2239                 //
2240                 // <fcntl.h> -- COMPLETE
2241                 //
2242
2243                 [DllImport (MPH, SetLastError=true, 
2244                                 EntryPoint="Mono_Posix_Syscall_fcntl")]
2245                 public static extern int fcntl (int fd, FcntlCommand cmd);
2246
2247                 [DllImport (MPH, SetLastError=true, 
2248                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg")]
2249                 public static extern int fcntl (int fd, FcntlCommand cmd, long arg);
2250
2251                 [DllImport (MPH, SetLastError=true, 
2252                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg_int")]
2253                 public static extern int fcntl (int fd, FcntlCommand cmd, int arg);
2254
2255                 [DllImport (MPH, SetLastError=true, 
2256                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg_ptr")]
2257                 public static extern int fcntl (int fd, FcntlCommand cmd, IntPtr ptr);
2258
2259                 public static int fcntl (int fd, FcntlCommand cmd, DirectoryNotifyFlags arg)
2260                 {
2261                         if (cmd != FcntlCommand.F_NOTIFY) {
2262                                 SetLastError (Errno.EINVAL);
2263                                 return -1;
2264                         }
2265                         long _arg = NativeConvert.FromDirectoryNotifyFlags (arg);
2266                         return fcntl (fd, FcntlCommand.F_NOTIFY, _arg);
2267                 }
2268
2269                 [DllImport (MPH, SetLastError=true, 
2270                                 EntryPoint="Mono_Posix_Syscall_fcntl_lock")]
2271                 public static extern int fcntl (int fd, FcntlCommand cmd, ref Flock @lock);
2272
2273                 [DllImport (MPH, SetLastError=true, 
2274                                 EntryPoint="Mono_Posix_Syscall_open")]
2275                 public static extern int open (
2276                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2277                                 string pathname, OpenFlags flags);
2278
2279                 // open(2)
2280                 //    int open(const char *pathname, int flags, mode_t mode);
2281                 [DllImport (MPH, SetLastError=true, 
2282                                 EntryPoint="Mono_Posix_Syscall_open_mode")]
2283                 public static extern int open (
2284                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2285                                 string pathname, OpenFlags flags, FilePermissions mode);
2286
2287                 // creat(2)
2288                 //    int creat(const char *pathname, mode_t mode);
2289                 [DllImport (MPH, SetLastError=true, 
2290                                 EntryPoint="Mono_Posix_Syscall_creat")]
2291                 public static extern int creat (
2292                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2293                                 string pathname, FilePermissions mode);
2294
2295                 // posix_fadvise(2)
2296                 //    int posix_fadvise(int fd, off_t offset, off_t len, int advice);
2297                 [DllImport (MPH, SetLastError=true, 
2298                                 EntryPoint="Mono_Posix_Syscall_posix_fadvise")]
2299                 public static extern int posix_fadvise (int fd, long offset, 
2300                         long len, PosixFadviseAdvice advice);
2301
2302                 // posix_fallocate(P)
2303                 //    int posix_fallocate(int fd, off_t offset, size_t len);
2304                 [DllImport (MPH, SetLastError=true, 
2305                                 EntryPoint="Mono_Posix_Syscall_posix_fallocate")]
2306                 public static extern int posix_fallocate (int fd, long offset, ulong len);
2307
2308                 [DllImport (LIBC, SetLastError=true, 
2309                                 EntryPoint="openat")]
2310                 private static extern int sys_openat (int dirfd,
2311                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2312                                 string pathname, int flags);
2313
2314                 // openat(2)
2315                 //    int openat(int dirfd, const char *pathname, int flags, mode_t mode);
2316                 [DllImport (LIBC, SetLastError=true, 
2317                                 EntryPoint="openat")]
2318                 private static extern int sys_openat (int dirfd,
2319                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2320                                 string pathname, int flags, uint mode);
2321
2322                 public static int openat (int dirfd, string pathname, OpenFlags flags)
2323                 {
2324                         int _flags = NativeConvert.FromOpenFlags (flags);
2325                         return sys_openat (dirfd, pathname, _flags);
2326                 }
2327
2328                 public static int openat (int dirfd, string pathname, OpenFlags flags, FilePermissions mode)
2329                 {
2330                         int _flags = NativeConvert.FromOpenFlags (flags);
2331                         uint _mode = NativeConvert.FromFilePermissions (mode);
2332                         return sys_openat (dirfd, pathname, _flags, _mode);
2333                 }
2334
2335                 [DllImport (MPH, SetLastError=true, 
2336                                 EntryPoint="Mono_Posix_Syscall_get_at_fdcwd")]
2337                 private static extern int get_at_fdcwd ();
2338
2339                 public static readonly int AT_FDCWD = get_at_fdcwd ();
2340
2341                 #endregion
2342
2343                 #region <fstab.h> Declarations
2344                 //
2345                 // <fstab.h>  -- COMPLETE
2346                 //
2347                 [Map]
2348                 private struct _Fstab {
2349                         public IntPtr fs_spec;
2350                         public IntPtr fs_file;
2351                         public IntPtr fs_vfstype;
2352                         public IntPtr fs_mntops;
2353                         public IntPtr fs_type;
2354                         public int    fs_freq;
2355                         public int    fs_passno;
2356                         public IntPtr _fs_buf_;
2357                 }
2358
2359                 private static void CopyFstab (Fstab to, ref _Fstab from)
2360                 {
2361                         try {
2362                                 to.fs_spec     = UnixMarshal.PtrToString (from.fs_spec);
2363                                 to.fs_file     = UnixMarshal.PtrToString (from.fs_file);
2364                                 to.fs_vfstype  = UnixMarshal.PtrToString (from.fs_vfstype);
2365                                 to.fs_mntops   = UnixMarshal.PtrToString (from.fs_mntops);
2366                                 to.fs_type     = UnixMarshal.PtrToString (from.fs_type);
2367                                 to.fs_freq     = from.fs_freq;
2368                                 to.fs_passno   = from.fs_passno;
2369                         }
2370                         finally {
2371                                 Stdlib.free (from._fs_buf_);
2372                                 from._fs_buf_ = IntPtr.Zero;
2373                         }
2374                 }
2375
2376                 internal static object fstab_lock = new object ();
2377
2378                 [DllImport (MPH, SetLastError=true,
2379                                 EntryPoint="Mono_Posix_Syscall_endfsent")]
2380                 private static extern int sys_endfsent ();
2381
2382                 public static int endfsent ()
2383                 {
2384                         lock (fstab_lock) {
2385                                 return sys_endfsent ();
2386                         }
2387                 }
2388
2389                 [DllImport (MPH, SetLastError=true,
2390                                 EntryPoint="Mono_Posix_Syscall_getfsent")]
2391                 private static extern int sys_getfsent (out _Fstab fs);
2392
2393                 public static Fstab getfsent ()
2394                 {
2395                         _Fstab fsbuf;
2396                         int r;
2397                         lock (fstab_lock) {
2398                                 r = sys_getfsent (out fsbuf);
2399                         }
2400                         if (r != 0)
2401                                 return null;
2402                         Fstab fs = new Fstab ();
2403                         CopyFstab (fs, ref fsbuf);
2404                         return fs;
2405                 }
2406
2407                 [DllImport (MPH, SetLastError=true,
2408                                 EntryPoint="Mono_Posix_Syscall_getfsfile")]
2409                 private static extern int sys_getfsfile (
2410                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2411                                 string mount_point, out _Fstab fs);
2412
2413                 public static Fstab getfsfile (string mount_point)
2414                 {
2415                         _Fstab fsbuf;
2416                         int r;
2417                         lock (fstab_lock) {
2418                                 r = sys_getfsfile (mount_point, out fsbuf);
2419                         }
2420                         if (r != 0)
2421                                 return null;
2422                         Fstab fs = new Fstab ();
2423                         CopyFstab (fs, ref fsbuf);
2424                         return fs;
2425                 }
2426
2427                 [DllImport (MPH, SetLastError=true,
2428                                 EntryPoint="Mono_Posix_Syscall_getfsspec")]
2429                 private static extern int sys_getfsspec (
2430                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2431                                 string special_file, out _Fstab fs);
2432
2433                 public static Fstab getfsspec (string special_file)
2434                 {
2435                         _Fstab fsbuf;
2436                         int r;
2437                         lock (fstab_lock) {
2438                                 r = sys_getfsspec (special_file, out fsbuf);
2439                         }
2440                         if (r != 0)
2441                                 return null;
2442                         Fstab fs = new Fstab ();
2443                         CopyFstab (fs, ref fsbuf);
2444                         return fs;
2445                 }
2446
2447                 [DllImport (MPH, SetLastError=true,
2448                                 EntryPoint="Mono_Posix_Syscall_setfsent")]
2449                 private static extern int sys_setfsent ();
2450
2451                 public static int setfsent ()
2452                 {
2453                         lock (fstab_lock) {
2454                                 return sys_setfsent ();
2455                         }
2456                 }
2457
2458                 #endregion
2459
2460                 #region <grp.h> Declarations
2461                 //
2462                 // <grp.h>
2463                 //
2464                 // TODO: putgrent(3), fgetgrent_r(), initgroups(3)
2465
2466                 // getgrouplist(2)
2467                 [DllImport (LIBC, SetLastError=true, EntryPoint="getgrouplist")]
2468                 private static extern int sys_getgrouplist (string user, uint grp, uint [] groups,ref int ngroups);
2469
2470                 public static Group [] getgrouplist (string username)
2471                 {
2472                         if (username == null)
2473                                 throw new ArgumentNullException ("username");
2474                         if (username.Trim () == "")
2475                                 throw new ArgumentException ("Username cannot be empty", "username");
2476                         // Syscall to getpwnam to retrieve user uid
2477                         Passwd pw = Syscall.getpwnam (username);
2478                         if (pw == null)
2479                                 throw new ArgumentException (string.Format ("User {0} does not exist", username), "username");
2480                         return getgrouplist (pw);
2481                 }
2482
2483                 public static Group [] getgrouplist (Passwd user)
2484                 {
2485                         if (user == null)
2486                                 throw new ArgumentNullException ("user");
2487                         // initializing ngroups by 16 to get the group count
2488                         int ngroups = 8;
2489                         int res = -1;
2490                         // allocating buffer to store group uid's
2491                         uint [] groups=null;
2492                         do {
2493                                 Array.Resize (ref groups, ngroups*=2);
2494                                 res = sys_getgrouplist (user.pw_name, user.pw_gid, groups, ref ngroups);
2495                         }
2496                         while (res == -1);
2497                         List<Group> result = new List<Group> ();
2498                         Group gr = null;
2499                         for (int i = 0; i < res; i++) {
2500                                 gr = Syscall.getgrgid (groups [i]);
2501                                 if (gr != null)
2502                                         result.Add (gr);
2503                         }
2504                         return result.ToArray ();
2505                 }
2506
2507                 // setgroups(2)
2508                 //    int setgroups (size_t size, const gid_t *list);
2509                 [DllImport (MPH, SetLastError=true,
2510                                 EntryPoint="Mono_Posix_Syscall_setgroups")]
2511                 public static extern int setgroups (ulong size, uint[] list);
2512
2513                 public static int setgroups (uint [] list)
2514                 {
2515                         return setgroups ((ulong) list.Length, list);
2516                 }
2517
2518                 [Map]
2519                 private struct _Group
2520                 {
2521                         public IntPtr           gr_name;
2522                         public IntPtr           gr_passwd;
2523                         [gid_t] public uint     gr_gid;
2524                         public int              _gr_nmem_;
2525                         public IntPtr           gr_mem;
2526                         public IntPtr           _gr_buf_;
2527                 }
2528
2529                 private static void CopyGroup (Group to, ref _Group from)
2530                 {
2531                         try {
2532                                 to.gr_gid    = from.gr_gid;
2533                                 to.gr_name   = UnixMarshal.PtrToString (from.gr_name);
2534                                 to.gr_passwd = UnixMarshal.PtrToString (from.gr_passwd);
2535                                 to.gr_mem    = UnixMarshal.PtrToStringArray (from._gr_nmem_, from.gr_mem);
2536                         }
2537                         finally {
2538                                 Stdlib.free (from.gr_mem);
2539                                 Stdlib.free (from._gr_buf_);
2540                                 from.gr_mem   = IntPtr.Zero;
2541                                 from._gr_buf_ = IntPtr.Zero;
2542                         }
2543                 }
2544
2545                 internal static object grp_lock = new object ();
2546
2547                 [DllImport (MPH, SetLastError=true,
2548                                 EntryPoint="Mono_Posix_Syscall_getgrnam")]
2549                 private static extern int sys_getgrnam (string name, out _Group group);
2550
2551                 public static Group getgrnam (string name)
2552                 {
2553                         _Group group;
2554                         int r;
2555                         lock (grp_lock) {
2556                                 r = sys_getgrnam (name, out group);
2557                         }
2558                         if (r != 0)
2559                                 return null;
2560                         Group gr = new Group ();
2561                         CopyGroup (gr, ref group);
2562                         return gr;
2563                 }
2564
2565                 // getgrgid(3)
2566                 //    struct group *getgrgid(gid_t gid);
2567                 [DllImport (MPH, SetLastError=true,
2568                                 EntryPoint="Mono_Posix_Syscall_getgrgid")]
2569                 private static extern int sys_getgrgid (uint uid, out _Group group);
2570
2571                 public static Group getgrgid (uint uid)
2572                 {
2573                         _Group group;
2574                         int r;
2575                         lock (grp_lock) {
2576                                 r = sys_getgrgid (uid, out group);
2577                         }
2578                         if (r != 0)
2579                                 return null;
2580                         Group gr = new Group ();
2581                         CopyGroup (gr, ref group);
2582                         return gr;
2583                 }
2584
2585                 [DllImport (MPH, SetLastError=true,
2586                                 EntryPoint="Mono_Posix_Syscall_getgrnam_r")]
2587                 private static extern int sys_getgrnam_r (
2588                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2589                                 string name, out _Group grbuf, out IntPtr grbufp);
2590
2591                 public static int getgrnam_r (string name, Group grbuf, out Group grbufp)
2592                 {
2593                         grbufp = null;
2594                         _Group group;
2595                         IntPtr _grbufp;
2596                         int r = sys_getgrnam_r (name, out group, out _grbufp);
2597                         if (r == 0 && _grbufp != IntPtr.Zero) {
2598                                 CopyGroup (grbuf, ref group);
2599                                 grbufp = grbuf;
2600                         }
2601                         return r;
2602                 }
2603
2604                 // getgrgid_r(3)
2605                 //    int getgrgid_r(gid_t gid, struct group *gbuf, char *buf,
2606                 //        size_t buflen, struct group **gbufp);
2607                 [DllImport (MPH, SetLastError=true,
2608                                 EntryPoint="Mono_Posix_Syscall_getgrgid_r")]
2609                 private static extern int sys_getgrgid_r (uint uid, out _Group grbuf, out IntPtr grbufp);
2610
2611                 public static int getgrgid_r (uint uid, Group grbuf, out Group grbufp)
2612                 {
2613                         grbufp = null;
2614                         _Group group;
2615                         IntPtr _grbufp;
2616                         int r = sys_getgrgid_r (uid, out group, out _grbufp);
2617                         if (r == 0 && _grbufp != IntPtr.Zero) {
2618                                 CopyGroup (grbuf, ref group);
2619                                 grbufp = grbuf;
2620                         }
2621                         return r;
2622                 }
2623
2624                 [DllImport (MPH, SetLastError=true,
2625                                 EntryPoint="Mono_Posix_Syscall_getgrent")]
2626                 private static extern int sys_getgrent (out _Group grbuf);
2627
2628                 public static Group getgrent ()
2629                 {
2630                         _Group group;
2631                         int r;
2632                         lock (grp_lock) {
2633                                 r = sys_getgrent (out group);
2634                         }
2635                         if (r != 0)
2636                                 return null;
2637                         Group gr = new Group();
2638                         CopyGroup (gr, ref group);
2639                         return gr;
2640                 }
2641
2642                 [DllImport (MPH, SetLastError=true, 
2643                                 EntryPoint="Mono_Posix_Syscall_setgrent")]
2644                 private static extern int sys_setgrent ();
2645
2646                 public static int setgrent ()
2647                 {
2648                         lock (grp_lock) {
2649                                 return sys_setgrent ();
2650                         }
2651                 }
2652
2653                 [DllImport (MPH, SetLastError=true, 
2654                                 EntryPoint="Mono_Posix_Syscall_endgrent")]
2655                 private static extern int sys_endgrent ();
2656
2657                 public static int endgrent ()
2658                 {
2659                         lock (grp_lock) {
2660                                 return sys_endgrent ();
2661                         }
2662                 }
2663
2664                 [DllImport (MPH, SetLastError=true,
2665                                 EntryPoint="Mono_Posix_Syscall_fgetgrent")]
2666                 private static extern int sys_fgetgrent (IntPtr stream, out _Group grbuf);
2667
2668                 public static Group fgetgrent (IntPtr stream)
2669                 {
2670                         _Group group;
2671                         int r;
2672                         lock (grp_lock) {
2673                                 r = sys_fgetgrent (stream, out group);
2674                         }
2675                         if (r != 0)
2676                                 return null;
2677                         Group gr = new Group ();
2678                         CopyGroup (gr, ref group);
2679                         return gr;
2680                 }
2681                 #endregion
2682
2683                 #region <pwd.h> Declarations
2684                 //
2685                 // <pwd.h>
2686                 //
2687                 // TODO: putpwent(3), fgetpwent_r()
2688                 //
2689                 // SKIPPING: getpw(3): it's dangerous.  Use getpwuid(3) instead.
2690
2691                 [Map]
2692                 private struct _Passwd
2693                 {
2694                         public IntPtr           pw_name;
2695                         public IntPtr           pw_passwd;
2696                         [uid_t] public uint     pw_uid;
2697                         [gid_t] public uint     pw_gid;
2698                         public IntPtr           pw_gecos;
2699                         public IntPtr           pw_dir;
2700                         public IntPtr           pw_shell;
2701                         public IntPtr           _pw_buf_;
2702                 }
2703
2704                 private static void CopyPasswd (Passwd to, ref _Passwd from)
2705                 {
2706                         try {
2707                                 to.pw_name   = UnixMarshal.PtrToString (from.pw_name);
2708                                 to.pw_passwd = UnixMarshal.PtrToString (from.pw_passwd);
2709                                 to.pw_uid    = from.pw_uid;
2710                                 to.pw_gid    = from.pw_gid;
2711                                 to.pw_gecos  = UnixMarshal.PtrToString (from.pw_gecos);
2712                                 to.pw_dir    = UnixMarshal.PtrToString (from.pw_dir);
2713                                 to.pw_shell  = UnixMarshal.PtrToString (from.pw_shell);
2714                         }
2715                         finally {
2716                                 Stdlib.free (from._pw_buf_);
2717                                 from._pw_buf_ = IntPtr.Zero;
2718                         }
2719                 }
2720
2721                 internal static object pwd_lock = new object ();
2722
2723                 [DllImport (MPH, SetLastError=true,
2724                                 EntryPoint="Mono_Posix_Syscall_getpwnam")]
2725                 private static extern int sys_getpwnam (string name, out _Passwd passwd);
2726
2727                 public static Passwd getpwnam (string name)
2728                 {
2729                         _Passwd passwd;
2730                         int r;
2731                         lock (pwd_lock) {
2732                                 r = sys_getpwnam (name, out passwd);
2733                         }
2734                         if (r != 0)
2735                                 return null;
2736                         Passwd pw = new Passwd ();
2737                         CopyPasswd (pw, ref passwd);
2738                         return pw;
2739                 }
2740
2741                 // getpwuid(3)
2742                 //    struct passwd *getpwnuid(uid_t uid);
2743                 [DllImport (MPH, SetLastError=true,
2744                                 EntryPoint="Mono_Posix_Syscall_getpwuid")]
2745                 private static extern int sys_getpwuid (uint uid, out _Passwd passwd);
2746
2747                 public static Passwd getpwuid (uint uid)
2748                 {
2749                         _Passwd passwd;
2750                         int r;
2751                         lock (pwd_lock) {
2752                                 r = sys_getpwuid (uid, out passwd);
2753                         }
2754                         if (r != 0)
2755                                 return null;
2756                         Passwd pw = new Passwd ();
2757                         CopyPasswd (pw, ref passwd);
2758                         return pw;
2759                 }
2760
2761                 [DllImport (MPH, SetLastError=true,
2762                                 EntryPoint="Mono_Posix_Syscall_getpwnam_r")]
2763                 private static extern int sys_getpwnam_r (
2764                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2765                                 string name, out _Passwd pwbuf, out IntPtr pwbufp);
2766
2767                 public static int getpwnam_r (string name, Passwd pwbuf, out Passwd pwbufp)
2768                 {
2769                         pwbufp = null;
2770                         _Passwd passwd;
2771                         IntPtr _pwbufp;
2772                         int r = sys_getpwnam_r (name, out passwd, out _pwbufp);
2773                         if (r == 0 && _pwbufp != IntPtr.Zero) {
2774                                 CopyPasswd (pwbuf, ref passwd);
2775                                 pwbufp = pwbuf;
2776                         }
2777                         return r;
2778                 }
2779
2780                 // getpwuid_r(3)
2781                 //    int getpwuid_r(uid_t uid, struct passwd *pwbuf, char *buf, size_t
2782                 //        buflen, struct passwd **pwbufp);
2783                 [DllImport (MPH, SetLastError=true,
2784                                 EntryPoint="Mono_Posix_Syscall_getpwuid_r")]
2785                 private static extern int sys_getpwuid_r (uint uid, out _Passwd pwbuf, out IntPtr pwbufp);
2786
2787                 public static int getpwuid_r (uint uid, Passwd pwbuf, out Passwd pwbufp)
2788                 {
2789                         pwbufp = null;
2790                         _Passwd passwd;
2791                         IntPtr _pwbufp;
2792                         int r = sys_getpwuid_r (uid, out passwd, out _pwbufp);
2793                         if (r == 0 && _pwbufp != IntPtr.Zero) {
2794                                 CopyPasswd (pwbuf, ref passwd);
2795                                 pwbufp = pwbuf;
2796                         }
2797                         return r;
2798                 }
2799
2800                 [DllImport (MPH, SetLastError=true,
2801                                 EntryPoint="Mono_Posix_Syscall_getpwent")]
2802                 private static extern int sys_getpwent (out _Passwd pwbuf);
2803
2804                 public static Passwd getpwent ()
2805                 {
2806                         _Passwd passwd;
2807                         int r;
2808                         lock (pwd_lock) {
2809                                 r = sys_getpwent (out passwd);
2810                         }
2811                         if (r != 0)
2812                                 return null;
2813                         Passwd pw = new Passwd ();
2814                         CopyPasswd (pw, ref passwd);
2815                         return pw;
2816                 }
2817
2818                 [DllImport (MPH, SetLastError=true, 
2819                                 EntryPoint="Mono_Posix_Syscall_setpwent")]
2820                 private static extern int sys_setpwent ();
2821
2822                 public static int setpwent ()
2823                 {
2824                         lock (pwd_lock) {
2825                                 return sys_setpwent ();
2826                         }
2827                 }
2828
2829                 [DllImport (MPH, SetLastError=true, 
2830                                 EntryPoint="Mono_Posix_Syscall_endpwent")]
2831                 private static extern int sys_endpwent ();
2832
2833                 public static int endpwent ()
2834                 {
2835                         lock (pwd_lock) {
2836                                 return sys_endpwent ();
2837                         }
2838                 }
2839
2840                 [DllImport (MPH, SetLastError=true,
2841                                 EntryPoint="Mono_Posix_Syscall_fgetpwent")]
2842                 private static extern int sys_fgetpwent (IntPtr stream, out _Passwd pwbuf);
2843
2844                 public static Passwd fgetpwent (IntPtr stream)
2845                 {
2846                         _Passwd passwd;
2847                         int r;
2848                         lock (pwd_lock) {
2849                                 r = sys_fgetpwent (stream, out passwd);
2850                         }
2851                         if (r != 0)
2852                                 return null;
2853                         Passwd pw = new Passwd ();
2854                         CopyPasswd (pw, ref passwd);
2855                         return pw;
2856                 }
2857                 #endregion
2858
2859                 #region <signal.h> Declarations
2860                 //
2861                 // <signal.h>
2862                 //
2863                 [DllImport (MPH, SetLastError=true,
2864                                 EntryPoint="Mono_Posix_Syscall_psignal")]
2865                 private static extern int psignal (int sig, string s);
2866
2867                 public static int psignal (Signum sig, string s)
2868                 {
2869                         int signum = NativeConvert.FromSignum (sig);
2870                         return psignal (signum, s);
2871                 }
2872
2873                 // kill(2)
2874                 //    int kill(pid_t pid, int sig);
2875                 [DllImport (LIBC, SetLastError=true, EntryPoint="kill")]
2876                 private static extern int sys_kill (int pid, int sig);
2877
2878                 public static int kill (int pid, Signum sig)
2879                 {
2880                         int _sig = NativeConvert.FromSignum (sig);
2881                         return sys_kill (pid, _sig);
2882                 }
2883
2884                 private static object signal_lock = new object ();
2885
2886                 [DllImport (LIBC, SetLastError=true, EntryPoint="strsignal")]
2887                 private static extern IntPtr sys_strsignal (int sig);
2888
2889                 public static string strsignal (Signum sig)
2890                 {
2891                         int s = NativeConvert.FromSignum (sig);
2892                         lock (signal_lock) {
2893                                 IntPtr r = sys_strsignal (s);
2894                                 return UnixMarshal.PtrToString (r);
2895                         }
2896                 }
2897
2898                 // TODO: sigaction(2)
2899                 // TODO: sigsuspend(2)
2900                 // TODO: sigpending(2)
2901
2902                 #endregion
2903
2904                 #region <stdio.h> Declarations
2905                 //
2906                 // <stdio.h>
2907                 //
2908                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_L_ctermid")]
2909                 private static extern int _L_ctermid ();
2910
2911                 public static readonly int L_ctermid = _L_ctermid ();
2912
2913                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_L_cuserid")]
2914                 private static extern int _L_cuserid ();
2915
2916                 public static readonly int L_cuserid = _L_cuserid ();
2917
2918                 internal static object getlogin_lock = new object ();
2919
2920                 [DllImport (LIBC, SetLastError=true, EntryPoint="cuserid")]
2921                 private static extern IntPtr sys_cuserid ([Out] StringBuilder @string);
2922
2923                 [Obsolete ("\"Nobody knows precisely what cuserid() does... " + 
2924                                 "DO NOT USE cuserid().\n" +
2925                                 "`string' must hold L_cuserid characters.  Use getlogin_r instead.")]
2926                 public static string cuserid (StringBuilder @string)
2927                 {
2928                         if (@string.Capacity < L_cuserid) {
2929                                 throw new ArgumentOutOfRangeException ("string", "string.Capacity < L_cuserid");
2930                         }
2931                         lock (getlogin_lock) {
2932                                 IntPtr r = sys_cuserid (@string);
2933                                 return UnixMarshal.PtrToString (r);
2934                         }
2935                 }
2936
2937                 [DllImport (LIBC, SetLastError=true)]
2938                 public static extern int renameat (int olddirfd,
2939                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2940                                 string oldpath, int newdirfd,
2941                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2942                                 string newpath);
2943                 #endregion
2944
2945                 #region <stdlib.h> Declarations
2946                 //
2947                 // <stdlib.h>
2948                 //
2949                 [DllImport (LIBC, SetLastError=true)]
2950                 public static extern int mkstemp (StringBuilder template);
2951
2952                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdtemp")]
2953                 private static extern IntPtr sys_mkdtemp (StringBuilder template);
2954
2955                 public static StringBuilder mkdtemp (StringBuilder template)
2956                 {
2957                         if (sys_mkdtemp (template) == IntPtr.Zero)
2958                                 return null;
2959                         return template;
2960                 }
2961
2962                 [DllImport (LIBC, SetLastError=true)]
2963                 public static extern int ttyslot ();
2964
2965                 [Obsolete ("This is insecure and should not be used", true)]
2966                 public static int setkey (string key)
2967                 {
2968                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
2969                 }
2970
2971                 #endregion
2972
2973                 #region <string.h> Declarations
2974                 //
2975                 // <string.h>
2976                 //
2977
2978                 // strerror_r(3)
2979                 //    int strerror_r(int errnum, char *buf, size_t n);
2980                 [DllImport (MPH, SetLastError=true, 
2981                                 EntryPoint="Mono_Posix_Syscall_strerror_r")]
2982                 private static extern int sys_strerror_r (int errnum, 
2983                                 [Out] StringBuilder buf, ulong n);
2984
2985                 public static int strerror_r (Errno errnum, StringBuilder buf, ulong n)
2986                 {
2987                         int e = NativeConvert.FromErrno (errnum);
2988                         return sys_strerror_r (e, buf, n);
2989                 }
2990
2991                 public static int strerror_r (Errno errnum, StringBuilder buf)
2992                 {
2993                         return strerror_r (errnum, buf, (ulong) buf.Capacity);
2994                 }
2995
2996                 #endregion
2997
2998                 #region <sys/epoll.h> Declarations
2999
3000                 public static int epoll_create (int size)
3001                 {
3002                         return sys_epoll_create (size);
3003                 }
3004
3005                 public static int epoll_create (EpollFlags flags)
3006                 {
3007                         return sys_epoll_create1 (flags);
3008                 }
3009
3010                 public static int epoll_ctl (int epfd, EpollOp op, int fd, EpollEvents events)
3011                 {
3012                         EpollEvent ee = new EpollEvent ();
3013                         ee.events = events;
3014                         ee.fd = fd;
3015
3016                         return epoll_ctl (epfd, op, fd, ref ee);
3017                 }
3018
3019                 public static int epoll_wait (int epfd, EpollEvent [] events, int max_events, int timeout)
3020                 {
3021                         if (events.Length < max_events)
3022                                 throw new ArgumentOutOfRangeException ("events", "Must refer to at least 'max_events' elements.");
3023
3024                         return sys_epoll_wait (epfd, events, max_events, timeout);
3025                 }
3026
3027                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_create")]
3028                 private static extern int sys_epoll_create (int size);
3029
3030                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_create1")]
3031                 private static extern int sys_epoll_create1 (EpollFlags flags);
3032
3033                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_ctl")]
3034                 public static extern int epoll_ctl (int epfd, EpollOp op, int fd, ref EpollEvent ee);
3035
3036                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_wait")]
3037                 private static extern int sys_epoll_wait (int epfd, EpollEvent [] ee, int maxevents, int timeout);
3038                 #endregion
3039                 
3040                 #region <sys/mman.h> Declarations
3041                 //
3042                 // <sys/mman.h>
3043                 //
3044
3045                 // posix_madvise(P)
3046                 //    int posix_madvise(void *addr, size_t len, int advice);
3047                 [DllImport (MPH, SetLastError=true, 
3048                                 EntryPoint="Mono_Posix_Syscall_posix_madvise")]
3049                 public static extern int posix_madvise (IntPtr addr, ulong len, 
3050                         PosixMadviseAdvice advice);
3051
3052                 public static readonly IntPtr MAP_FAILED = unchecked((IntPtr)(-1));
3053
3054                 [DllImport (MPH, SetLastError=true, 
3055                                 EntryPoint="Mono_Posix_Syscall_mmap")]
3056                 public static extern IntPtr mmap (IntPtr start, ulong length, 
3057                                 MmapProts prot, MmapFlags flags, int fd, long offset);
3058
3059                 [DllImport (MPH, SetLastError=true, 
3060                                 EntryPoint="Mono_Posix_Syscall_munmap")]
3061                 public static extern int munmap (IntPtr start, ulong length);
3062
3063                 [DllImport (MPH, SetLastError=true, 
3064                                 EntryPoint="Mono_Posix_Syscall_mprotect")]
3065                 public static extern int mprotect (IntPtr start, ulong len, MmapProts prot);
3066
3067                 [DllImport (MPH, SetLastError=true, 
3068                                 EntryPoint="Mono_Posix_Syscall_msync")]
3069                 public static extern int msync (IntPtr start, ulong len, MsyncFlags flags);
3070
3071                 [DllImport (MPH, SetLastError=true, 
3072                                 EntryPoint="Mono_Posix_Syscall_mlock")]
3073                 public static extern int mlock (IntPtr start, ulong len);
3074
3075                 [DllImport (MPH, SetLastError=true, 
3076                                 EntryPoint="Mono_Posix_Syscall_munlock")]
3077                 public static extern int munlock (IntPtr start, ulong len);
3078
3079                 [DllImport (LIBC, SetLastError=true, EntryPoint="mlockall")]
3080                 private static extern int sys_mlockall (int flags);
3081
3082                 public static int mlockall (MlockallFlags flags)
3083                 {
3084                         int _flags = NativeConvert.FromMlockallFlags (flags);
3085                         return sys_mlockall (_flags);
3086                 }
3087
3088                 [DllImport (LIBC, SetLastError=true)]
3089                 public static extern int munlockall ();
3090
3091                 [DllImport (MPH, SetLastError=true, 
3092                                 EntryPoint="Mono_Posix_Syscall_mremap")]
3093                 public static extern IntPtr mremap (IntPtr old_address, ulong old_size, 
3094                                 ulong new_size, MremapFlags flags);
3095
3096                 [DllImport (MPH, SetLastError=true, 
3097                                 EntryPoint="Mono_Posix_Syscall_mincore")]
3098                 public static extern int mincore (IntPtr start, ulong length, byte[] vec);
3099
3100                 [DllImport (MPH, SetLastError=true, 
3101                                 EntryPoint="Mono_Posix_Syscall_remap_file_pages")]
3102                 public static extern int remap_file_pages (IntPtr start, ulong size,
3103                                 MmapProts prot, long pgoff, MmapFlags flags);
3104
3105                 #endregion
3106
3107                 #region <sys/poll.h> Declarations
3108                 //
3109                 // <sys/poll.h> -- COMPLETE
3110                 //
3111
3112                 private struct _pollfd {
3113                         public int fd;
3114                         public short events;
3115                         public short revents;
3116                 }
3117
3118                 [DllImport (LIBC, SetLastError=true, EntryPoint="poll")]
3119                 private static extern int sys_poll (_pollfd[] ufds, uint nfds, int timeout);
3120
3121                 public static int poll (Pollfd [] fds, uint nfds, int timeout)
3122                 {
3123                         if (fds.Length < nfds)
3124                                 throw new ArgumentOutOfRangeException ("fds", "Must refer to at least `nfds' elements");
3125
3126                         _pollfd[] send = new _pollfd[nfds];
3127
3128                         for (int i = 0; i < send.Length; i++) {
3129                                 send [i].fd     = fds [i].fd;
3130                                 send [i].events = NativeConvert.FromPollEvents (fds [i].events);
3131                         }
3132
3133                         int r = sys_poll (send, nfds, timeout);
3134
3135                         for (int i = 0; i < send.Length; i++) {
3136                                 fds [i].revents = NativeConvert.ToPollEvents (send [i].revents);
3137                         }
3138
3139                         return r;
3140                 }
3141
3142                 public static int poll (Pollfd [] fds, int timeout)
3143                 {
3144                         return poll (fds, (uint) fds.Length, timeout);
3145                 }
3146
3147                 //
3148                 // <sys/ptrace.h>
3149                 //
3150
3151                 // TODO: ptrace(2)
3152
3153                 //
3154                 // <sys/resource.h>
3155                 //
3156
3157                 // TODO: setrlimit(2)
3158                 // TODO: getrlimit(2)
3159                 // TODO: getrusage(2)
3160
3161                 #endregion
3162
3163                 #region <sys/sendfile.h> Declarations
3164                 //
3165                 // <sys/sendfile.h> -- COMPLETE
3166                 //
3167
3168                 [DllImport (MPH, SetLastError=true,
3169                                 EntryPoint="Mono_Posix_Syscall_sendfile")]
3170                 public static extern long sendfile (int out_fd, int in_fd, 
3171                                 ref long offset, ulong count);
3172
3173                 #endregion
3174
3175                 #region <sys/stat.h> Declarations
3176                 //
3177                 // <sys/stat.h>  -- COMPLETE
3178                 //
3179                 [DllImport (MPH, SetLastError=true, 
3180                                 EntryPoint="Mono_Posix_Syscall_stat")]
3181                 public static extern int stat (
3182                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3183                                 string file_name, out Stat buf);
3184
3185                 [DllImport (MPH, SetLastError=true, 
3186                                 EntryPoint="Mono_Posix_Syscall_fstat")]
3187                 public static extern int fstat (int filedes, out Stat buf);
3188
3189                 [DllImport (MPH, SetLastError=true, 
3190                                 EntryPoint="Mono_Posix_Syscall_lstat")]
3191                 public static extern int lstat (
3192                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3193                                 string file_name, out Stat buf);
3194
3195                 // TODO:
3196                 // S_ISDIR, S_ISCHR, S_ISBLK, S_ISREG, S_ISFIFO, S_ISLNK, S_ISSOCK
3197                 // All take FilePermissions
3198
3199                 // chmod(2)
3200                 //    int chmod(const char *path, mode_t mode);
3201                 [DllImport (LIBC, SetLastError=true, EntryPoint="chmod")]
3202                 private static extern int sys_chmod (
3203                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3204                                 string path, uint mode);
3205
3206                 public static int chmod (string path, FilePermissions mode)
3207                 {
3208                         uint _mode = NativeConvert.FromFilePermissions (mode);
3209                         return sys_chmod (path, _mode);
3210                 }
3211
3212                 // fchmod(2)
3213                 //    int chmod(int filedes, mode_t mode);
3214                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchmod")]
3215                 private static extern int sys_fchmod (int filedes, uint mode);
3216
3217                 public static int fchmod (int filedes, FilePermissions mode)
3218                 {
3219                         uint _mode = NativeConvert.FromFilePermissions (mode);
3220                         return sys_fchmod (filedes, _mode);
3221                 }
3222
3223                 // umask(2)
3224                 //    mode_t umask(mode_t mask);
3225                 [DllImport (LIBC, SetLastError=true, EntryPoint="umask")]
3226                 private static extern uint sys_umask (uint mask);
3227
3228                 public static FilePermissions umask (FilePermissions mask)
3229                 {
3230                         uint _mask = NativeConvert.FromFilePermissions (mask);
3231                         uint r = sys_umask (_mask);
3232                         return NativeConvert.ToFilePermissions (r);
3233                 }
3234
3235                 // mkdir(2)
3236                 //    int mkdir(const char *pathname, mode_t mode);
3237                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdir")]
3238                 private static extern int sys_mkdir (
3239                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3240                                 string oldpath, uint mode);
3241
3242                 public static int mkdir (string oldpath, FilePermissions mode)
3243                 {
3244                         uint _mode = NativeConvert.FromFilePermissions (mode);
3245                         return sys_mkdir (oldpath, _mode);
3246                 }
3247
3248                 // mknod(2)
3249                 //    int mknod (const char *pathname, mode_t mode, dev_t dev);
3250                 [DllImport (MPH, SetLastError=true,
3251                                 EntryPoint="Mono_Posix_Syscall_mknod")]
3252                 public static extern int mknod (
3253                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3254                                 string pathname, FilePermissions mode, ulong dev);
3255
3256                 // mkfifo(3)
3257                 //    int mkfifo(const char *pathname, mode_t mode);
3258                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkfifo")]
3259                 private static extern int sys_mkfifo (
3260                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3261                                 string pathname, uint mode);
3262
3263                 public static int mkfifo (string pathname, FilePermissions mode)
3264                 {
3265                         uint _mode = NativeConvert.FromFilePermissions (mode);
3266                         return sys_mkfifo (pathname, _mode);
3267                 }
3268
3269                 // fchmodat(2)
3270                 //    int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
3271                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchmodat")]
3272                 private static extern int sys_fchmodat (int dirfd,
3273                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3274                                 string pathname, uint mode, int flags);
3275
3276                 public static int fchmodat (int dirfd, string pathname, FilePermissions mode, AtFlags flags)
3277                 {
3278                         uint _mode = NativeConvert.FromFilePermissions (mode);
3279                         int _flags = NativeConvert.FromAtFlags (flags);
3280                         return sys_fchmodat (dirfd, pathname, _mode, _flags);
3281                 }
3282
3283                 [DllImport (MPH, SetLastError=true, 
3284                                 EntryPoint="Mono_Posix_Syscall_fstatat")]
3285                 public static extern int fstatat (int dirfd,
3286                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3287                                 string file_name, out Stat buf, AtFlags flags);
3288
3289                 [DllImport (MPH, SetLastError=true, 
3290                                 EntryPoint="Mono_Posix_Syscall_get_utime_now")]
3291                 private static extern long get_utime_now ();
3292
3293                 [DllImport (MPH, SetLastError=true, 
3294                                 EntryPoint="Mono_Posix_Syscall_get_utime_omit")]
3295                 private static extern long get_utime_omit ();
3296
3297                 public static readonly long UTIME_NOW = get_utime_now ();
3298
3299                 public static readonly long UTIME_OMIT = get_utime_omit ();
3300
3301                 [DllImport (MPH, SetLastError=true, 
3302                                 EntryPoint="Mono_Posix_Syscall_futimens")]
3303                 private static extern int sys_futimens (int fd, Timespec[] times);
3304
3305                 public static int futimens (int fd, Timespec[] times)
3306                 {
3307                         if (times != null && times.Length != 2) {
3308                                 SetLastError (Errno.EINVAL);
3309                                 return -1;
3310                         }
3311                         return sys_futimens (fd, times);
3312                 }
3313
3314                 [DllImport (MPH, SetLastError=true, 
3315                                 EntryPoint="Mono_Posix_Syscall_utimensat")]
3316                 private static extern int sys_utimensat (int dirfd,
3317                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3318                                 string pathname, Timespec[] times, int flags);
3319
3320                 public static int utimensat (int dirfd, string pathname, Timespec[] times, AtFlags flags)
3321                 {
3322                         if (times != null && times.Length != 2) {
3323                                 SetLastError (Errno.EINVAL);
3324                                 return -1;
3325                         }
3326                         int _flags = NativeConvert.FromAtFlags (flags);
3327                         return sys_utimensat (dirfd, pathname, times, _flags);
3328                 }
3329
3330                 // mkdirat(2)
3331                 //    int mkdirat(int dirfd, const char *pathname, mode_t mode);
3332                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdirat")]
3333                 private static extern int sys_mkdirat (int dirfd,
3334                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3335                                 string oldpath, uint mode);
3336
3337                 public static int mkdirat (int dirfd, string oldpath, FilePermissions mode)
3338                 {
3339                         uint _mode = NativeConvert.FromFilePermissions (mode);
3340                         return sys_mkdirat (dirfd, oldpath, _mode);
3341                 }
3342
3343                 // mknodat(2)
3344                 //    int mknodat (int dirfd, const char *pathname, mode_t mode, dev_t dev);
3345                 [DllImport (MPH, SetLastError=true,
3346                                 EntryPoint="Mono_Posix_Syscall_mknodat")]
3347                 public static extern int mknodat (int dirfd,
3348                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3349                                 string pathname, FilePermissions mode, ulong dev);
3350
3351                 // mkfifoat(3)
3352                 //    int mkfifoat(int dirfd, const char *pathname, mode_t mode);
3353                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkfifoat")]
3354                 private static extern int sys_mkfifoat (int dirfd,
3355                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3356                                 string pathname, uint mode);
3357
3358                 public static int mkfifoat (int dirfd, string pathname, FilePermissions mode)
3359                 {
3360                         uint _mode = NativeConvert.FromFilePermissions (mode);
3361                         return sys_mkfifoat (dirfd, pathname, _mode);
3362                 }
3363                 #endregion
3364
3365                 #region <sys/stat.h> Declarations
3366                 //
3367                 // <sys/statvfs.h>
3368                 //
3369
3370                 [DllImport (MPH, SetLastError=true,
3371                                 EntryPoint="Mono_Posix_Syscall_statvfs")]
3372                 public static extern int statvfs (
3373                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3374                                 string path, out Statvfs buf);
3375
3376                 [DllImport (MPH, SetLastError=true,
3377                                 EntryPoint="Mono_Posix_Syscall_fstatvfs")]
3378                 public static extern int fstatvfs (int fd, out Statvfs buf);
3379
3380                 #endregion
3381
3382                 #region <sys/time.h> Declarations
3383                 //
3384                 // <sys/time.h>
3385                 //
3386                 // TODO: adjtime(), getitimer(2), setitimer(2)
3387
3388                 [DllImport (MPH, SetLastError=true, 
3389                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
3390                 public static extern int gettimeofday (out Timeval tv, out Timezone tz);
3391
3392                 [DllImport (MPH, SetLastError=true,
3393                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
3394                 private static extern int gettimeofday (out Timeval tv, IntPtr ignore);
3395
3396                 public static int gettimeofday (out Timeval tv)
3397                 {
3398                         return gettimeofday (out tv, IntPtr.Zero);
3399                 }
3400
3401                 [DllImport (MPH, SetLastError=true,
3402                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
3403                 private static extern int gettimeofday (IntPtr ignore, out Timezone tz);
3404
3405                 public static int gettimeofday (out Timezone tz)
3406                 {
3407                         return gettimeofday (IntPtr.Zero, out tz);
3408                 }
3409
3410                 [DllImport (MPH, SetLastError=true,
3411                                 EntryPoint="Mono_Posix_Syscall_settimeofday")]
3412                 public static extern int settimeofday (ref Timeval tv, ref Timezone tz);
3413
3414                 [DllImport (MPH, SetLastError=true,
3415                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
3416                 private static extern int settimeofday (ref Timeval tv, IntPtr ignore);
3417
3418                 public static int settimeofday (ref Timeval tv)
3419                 {
3420                         return settimeofday (ref tv, IntPtr.Zero);
3421                 }
3422
3423                 [DllImport (MPH, SetLastError=true, 
3424                                 EntryPoint="Mono_Posix_Syscall_utimes")]
3425                 private static extern int sys_utimes (
3426                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3427                                 string filename, Timeval[] tvp);
3428
3429                 public static int utimes (string filename, Timeval[] tvp)
3430                 {
3431                         if (tvp != null && tvp.Length != 2) {
3432                                 SetLastError (Errno.EINVAL);
3433                                 return -1;
3434                         }
3435                         return sys_utimes (filename, tvp);
3436                 }
3437
3438                 [DllImport (MPH, SetLastError=true, 
3439                                 EntryPoint="Mono_Posix_Syscall_lutimes")]
3440                 private static extern int sys_lutimes (
3441                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3442                                 string filename, Timeval[] tvp);
3443
3444                 public static int lutimes (string filename, Timeval[] tvp)
3445                 {
3446                         if (tvp != null && tvp.Length != 2) {
3447                                 SetLastError (Errno.EINVAL);
3448                                 return -1;
3449                         }
3450                         return sys_lutimes (filename, tvp);
3451                 }
3452
3453                 [DllImport (MPH, SetLastError=true, 
3454                                 EntryPoint="Mono_Posix_Syscall_futimes")]
3455                 private static extern int sys_futimes (int fd, Timeval[] tvp);
3456
3457                 public static int futimes (int fd, Timeval[] tvp)
3458                 {
3459                         if (tvp != null && tvp.Length != 2) {
3460                                 SetLastError (Errno.EINVAL);
3461                                 return -1;
3462                         }
3463                         return sys_futimes (fd, tvp);
3464                 }
3465
3466                 #endregion
3467
3468                 //
3469                 // <sys/timeb.h>
3470                 //
3471
3472                 // TODO: ftime(3)
3473
3474                 //
3475                 // <sys/times.h>
3476                 //
3477
3478                 // TODO: times(2)
3479
3480                 //
3481                 // <sys/utsname.h>
3482                 //
3483
3484                 [Map]
3485                 private struct _Utsname
3486                 {
3487                         public IntPtr sysname;
3488                         public IntPtr nodename;
3489                         public IntPtr release;
3490                         public IntPtr version;
3491                         public IntPtr machine;
3492                         public IntPtr domainname;
3493                         public IntPtr _buf_;
3494                 }
3495
3496                 private static void CopyUtsname (ref Utsname to, ref _Utsname from)
3497                 {
3498                         try {
3499                                 to = new Utsname ();
3500                                 to.sysname     = UnixMarshal.PtrToString (from.sysname);
3501                                 to.nodename    = UnixMarshal.PtrToString (from.nodename);
3502                                 to.release     = UnixMarshal.PtrToString (from.release);
3503                                 to.version     = UnixMarshal.PtrToString (from.version);
3504                                 to.machine     = UnixMarshal.PtrToString (from.machine);
3505                                 to.domainname  = UnixMarshal.PtrToString (from.domainname);
3506                         }
3507                         finally {
3508                                 Stdlib.free (from._buf_);
3509                                 from._buf_ = IntPtr.Zero;
3510                         }
3511                 }
3512
3513                 [DllImport (MPH, SetLastError=true, 
3514                                 EntryPoint="Mono_Posix_Syscall_uname")]
3515                 private static extern int sys_uname (out _Utsname buf);
3516
3517                 public static int uname (out Utsname buf)
3518                 {
3519                         _Utsname _buf;
3520                         int r = sys_uname (out _buf);
3521                         buf = new Utsname ();
3522                         if (r == 0) {
3523                                 CopyUtsname (ref buf, ref _buf);
3524                         }
3525                         return r;
3526                 }
3527
3528                 #region <sys/wait.h> Declarations
3529                 //
3530                 // <sys/wait.h>
3531                 //
3532
3533                 // wait(2)
3534                 //    pid_t wait(int *status);
3535                 [DllImport (LIBC, SetLastError=true)]
3536                 public static extern int wait (out int status);
3537
3538                 // waitpid(2)
3539                 //    pid_t waitpid(pid_t pid, int *status, int options);
3540                 [DllImport (LIBC, SetLastError=true)]
3541                 private static extern int waitpid (int pid, out int status, int options);
3542
3543                 public static int waitpid (int pid, out int status, WaitOptions options)
3544                 {
3545                         int _options = NativeConvert.FromWaitOptions (options);
3546                         return waitpid (pid, out status, _options);
3547                 }
3548
3549                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFEXITED")]
3550                 private static extern int _WIFEXITED (int status);
3551
3552                 public static bool WIFEXITED (int status)
3553                 {
3554                         return _WIFEXITED (status) != 0;
3555                 }
3556
3557                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WEXITSTATUS")]
3558                 public static extern int WEXITSTATUS (int status);
3559
3560                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFSIGNALED")]
3561                 private static extern int _WIFSIGNALED (int status);
3562
3563                 public static bool WIFSIGNALED (int status)
3564                 {
3565                         return _WIFSIGNALED (status) != 0;
3566                 }
3567
3568                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WTERMSIG")]
3569                 private static extern int _WTERMSIG (int status);
3570
3571                 public static Signum WTERMSIG (int status)
3572                 {
3573                         int r = _WTERMSIG (status);
3574                         return NativeConvert.ToSignum (r);
3575                 }
3576
3577                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFSTOPPED")]
3578                 private static extern int _WIFSTOPPED (int status);
3579
3580                 public static bool WIFSTOPPED (int status)
3581                 {
3582                         return _WIFSTOPPED (status) != 0;
3583                 }
3584
3585                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WSTOPSIG")]
3586                 private static extern int _WSTOPSIG (int status);
3587
3588                 public static Signum WSTOPSIG (int status)
3589                 {
3590                         int r = _WSTOPSIG (status);
3591                         return NativeConvert.ToSignum (r);
3592                 }
3593
3594                 //
3595                 // <termios.h>
3596                 //
3597
3598                 #endregion
3599
3600                 #region <syslog.h> Declarations
3601                 //
3602                 // <syslog.h>
3603                 //
3604
3605                 [DllImport (MPH, SetLastError=true,
3606                                 EntryPoint="Mono_Posix_Syscall_openlog")]
3607                 private static extern int sys_openlog (IntPtr ident, int option, int facility);
3608
3609                 public static int openlog (IntPtr ident, SyslogOptions option, 
3610                                 SyslogFacility defaultFacility)
3611                 {
3612                         int _option   = NativeConvert.FromSyslogOptions (option);
3613                         int _facility = NativeConvert.FromSyslogFacility (defaultFacility);
3614
3615                         return sys_openlog (ident, _option, _facility);
3616                 }
3617
3618                 [DllImport (MPH, SetLastError=true,
3619                                 EntryPoint="Mono_Posix_Syscall_syslog")]
3620                 private static extern int sys_syslog (int priority, string message);
3621
3622                 public static int syslog (SyslogFacility facility, SyslogLevel level, string message)
3623                 {
3624                         int _facility = NativeConvert.FromSyslogFacility (facility);
3625                         int _level = NativeConvert.FromSyslogLevel (level);
3626                         return sys_syslog (_facility | _level, GetSyslogMessage (message));
3627                 }
3628
3629                 public static int syslog (SyslogLevel level, string message)
3630                 {
3631                         int _level = NativeConvert.FromSyslogLevel (level);
3632                         return sys_syslog (_level, GetSyslogMessage (message));
3633                 }
3634
3635                 private static string GetSyslogMessage (string message)
3636                 {
3637                         return UnixMarshal.EscapeFormatString (message, new char[]{'m'});
3638                 }
3639
3640                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
3641                                 "Use syslog(SyslogFacility, SyslogLevel, string) instead.")]
3642                 public static int syslog (SyslogFacility facility, SyslogLevel level, 
3643                                 string format, params object[] parameters)
3644                 {
3645                         int _facility = NativeConvert.FromSyslogFacility (facility);
3646                         int _level = NativeConvert.FromSyslogLevel (level);
3647
3648                         object[] _parameters = new object[checked(parameters.Length+2)];
3649                         _parameters [0] = _facility | _level;
3650                         _parameters [1] = format;
3651                         Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
3652                         return (int) XPrintfFunctions.syslog (_parameters);
3653                 }
3654
3655                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
3656                                 "Use syslog(SyslogLevel, string) instead.")]
3657                 public static int syslog (SyslogLevel level, string format, 
3658                                 params object[] parameters)
3659                 {
3660                         int _level = NativeConvert.FromSyslogLevel (level);
3661
3662                         object[] _parameters = new object[checked(parameters.Length+2)];
3663                         _parameters [0] = _level;
3664                         _parameters [1] = format;
3665                         Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
3666                         return (int) XPrintfFunctions.syslog (_parameters);
3667                 }
3668
3669                 [DllImport (MPH, SetLastError=true,
3670                                 EntryPoint="Mono_Posix_Syscall_closelog")]
3671                 public static extern int closelog ();
3672
3673                 [DllImport (LIBC, SetLastError=true, EntryPoint="setlogmask")]
3674                 private static extern int sys_setlogmask (int mask);
3675
3676                 public static int setlogmask (SyslogLevel mask)
3677                 {
3678                         int _mask = NativeConvert.FromSyslogLevel (mask);
3679                         return sys_setlogmask (_mask);
3680                 }
3681
3682                 #endregion
3683
3684                 #region <time.h> Declarations
3685
3686                 //
3687                 // <time.h>
3688                 //
3689
3690                 // nanosleep(2)
3691                 //    int nanosleep(const struct timespec *req, struct timespec *rem);
3692                 [DllImport (MPH, SetLastError=true,
3693                                 EntryPoint="Mono_Posix_Syscall_nanosleep")]
3694                 public static extern int nanosleep (ref Timespec req, ref Timespec rem);
3695
3696                 // stime(2)
3697                 //    int stime(time_t *t);
3698                 [DllImport (MPH, SetLastError=true,
3699                                 EntryPoint="Mono_Posix_Syscall_stime")]
3700                 public static extern int stime (ref long t);
3701
3702                 // time(2)
3703                 //    time_t time(time_t *t);
3704                 [DllImport (MPH, SetLastError=true,
3705                                 EntryPoint="Mono_Posix_Syscall_time")]
3706                 public static extern long time (out long t);
3707
3708                 //
3709                 // <ulimit.h>
3710                 //
3711
3712                 // TODO: ulimit(3)
3713
3714                 #endregion
3715
3716                 #region <unistd.h> Declarations
3717                 //
3718                 // <unistd.h>
3719                 //
3720                 // TODO: euidaccess(), usleep(3), get_current_dir_name(), group_member(),
3721                 //       other TODOs listed below.
3722
3723                 [DllImport (LIBC, SetLastError=true, EntryPoint="access")]
3724                 private static extern int sys_access (
3725                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3726                                 string pathname, int mode);
3727
3728                 public static int access (string pathname, AccessModes mode)
3729                 {
3730                         int _mode = NativeConvert.FromAccessModes (mode);
3731                         return sys_access (pathname, _mode);
3732                 }
3733
3734                 // lseek(2)
3735                 //    off_t lseek(int filedes, off_t offset, int whence);
3736                 [DllImport (MPH, SetLastError=true, 
3737                                 EntryPoint="Mono_Posix_Syscall_lseek")]
3738                 private static extern long sys_lseek (int fd, long offset, int whence);
3739
3740                 public static long lseek (int fd, long offset, SeekFlags whence)
3741                 {
3742                         short _whence = NativeConvert.FromSeekFlags (whence);
3743                         return sys_lseek (fd, offset, _whence);
3744                 }
3745
3746     [DllImport (LIBC, SetLastError=true)]
3747                 public static extern int close (int fd);
3748
3749                 // read(2)
3750                 //    ssize_t read(int fd, void *buf, size_t count);
3751                 [DllImport (MPH, SetLastError=true, 
3752                                 EntryPoint="Mono_Posix_Syscall_read")]
3753                 public static extern long read (int fd, IntPtr buf, ulong count);
3754
3755                 public static unsafe long read (int fd, void *buf, ulong count)
3756                 {
3757                         return read (fd, (IntPtr) buf, count);
3758                 }
3759
3760                 // write(2)
3761                 //    ssize_t write(int fd, const void *buf, size_t count);
3762                 [DllImport (MPH, SetLastError=true, 
3763                                 EntryPoint="Mono_Posix_Syscall_write")]
3764                 public static extern long write (int fd, IntPtr buf, ulong count);
3765
3766                 public static unsafe long write (int fd, void *buf, ulong count)
3767                 {
3768                         return write (fd, (IntPtr) buf, count);
3769                 }
3770
3771                 // pread(2)
3772                 //    ssize_t pread(int fd, void *buf, size_t count, off_t offset);
3773                 [DllImport (MPH, SetLastError=true, 
3774                                 EntryPoint="Mono_Posix_Syscall_pread")]
3775                 public static extern long pread (int fd, IntPtr buf, ulong count, long offset);
3776
3777                 public static unsafe long pread (int fd, void *buf, ulong count, long offset)
3778                 {
3779                         return pread (fd, (IntPtr) buf, count, offset);
3780                 }
3781
3782                 // pwrite(2)
3783                 //    ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
3784                 [DllImport (MPH, SetLastError=true, 
3785                                 EntryPoint="Mono_Posix_Syscall_pwrite")]
3786                 public static extern long pwrite (int fd, IntPtr buf, ulong count, long offset);
3787
3788                 public static unsafe long pwrite (int fd, void *buf, ulong count, long offset)
3789                 {
3790                         return pwrite (fd, (IntPtr) buf, count, offset);
3791                 }
3792
3793                 [DllImport (MPH, SetLastError=true, 
3794                                 EntryPoint="Mono_Posix_Syscall_pipe")]
3795                 public static extern int pipe (out int reading, out int writing);
3796
3797                 public static int pipe (int[] filedes)
3798                 {
3799                         if (filedes == null || filedes.Length != 2) {
3800                                 // TODO: set errno
3801                                 return -1;
3802                         }
3803                         int reading, writing;
3804                         int r = pipe (out reading, out writing);
3805                         filedes[0] = reading;
3806                         filedes[1] = writing;
3807                         return r;
3808                 }
3809
3810                 [DllImport (LIBC, SetLastError=true)]
3811                 public static extern uint alarm (uint seconds);
3812
3813                 [DllImport (LIBC, SetLastError=true)]
3814                 public static extern uint sleep (uint seconds);
3815
3816                 [DllImport (LIBC, SetLastError=true)]
3817                 public static extern uint ualarm (uint usecs, uint interval);
3818
3819                 [DllImport (LIBC, SetLastError=true)]
3820                 public static extern int pause ();
3821
3822                 // chown(2)
3823                 //    int chown(const char *path, uid_t owner, gid_t group);
3824                 [DllImport (LIBC, SetLastError=true)]
3825                 public static extern int chown (
3826                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3827                                 string path, uint owner, uint group);
3828
3829                 // fchown(2)
3830                 //    int fchown(int fd, uid_t owner, gid_t group);
3831                 [DllImport (LIBC, SetLastError=true)]
3832                 public static extern int fchown (int fd, uint owner, uint group);
3833
3834                 // lchown(2)
3835                 //    int lchown(const char *path, uid_t owner, gid_t group);
3836                 [DllImport (LIBC, SetLastError=true)]
3837                 public static extern int lchown (
3838                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3839                                 string path, uint owner, uint group);
3840
3841                 [DllImport (LIBC, SetLastError=true)]
3842                 public static extern int chdir (
3843                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3844                                 string path);
3845
3846                 [DllImport (LIBC, SetLastError=true)]
3847                 public static extern int fchdir (int fd);
3848
3849                 // getcwd(3)
3850                 //    char *getcwd(char *buf, size_t size);
3851                 [DllImport (MPH, SetLastError=true,
3852                                 EntryPoint="Mono_Posix_Syscall_getcwd")]
3853                 public static extern IntPtr getcwd ([Out] StringBuilder buf, ulong size);
3854
3855                 public static StringBuilder getcwd (StringBuilder buf)
3856                 {
3857                         getcwd (buf, (ulong) buf.Capacity);
3858                         return buf;
3859                 }
3860
3861                 // getwd(2) is deprecated; don't expose it.
3862
3863                 [DllImport (LIBC, SetLastError=true)]
3864                 public static extern int dup (int fd);
3865
3866                 [DllImport (LIBC, SetLastError=true)]
3867                 public static extern int dup2 (int fd, int fd2);
3868
3869                 // TODO: does Mono marshal arrays properly?
3870                 [DllImport (LIBC, SetLastError=true)]
3871                 public static extern int execve (
3872                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3873                                 string path, string[] argv, string[] envp);
3874
3875                 [DllImport (LIBC, SetLastError=true)]
3876                 public static extern int fexecve (int fd, string[] argv, string[] envp);
3877
3878                 [DllImport (LIBC, SetLastError=true)]
3879                 public static extern int execv (
3880                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3881                                 string path, string[] argv);
3882
3883                 // TODO: execle, execl, execlp
3884                 [DllImport (LIBC, SetLastError=true)]
3885                 public static extern int execvp (
3886                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3887                                 string path, string[] argv);
3888
3889                 [DllImport (LIBC, SetLastError=true)]
3890                 public static extern int nice (int inc);
3891
3892                 [DllImport (LIBC, SetLastError=true)]
3893                 [CLSCompliant (false)]
3894                 public static extern int _exit (int status);
3895
3896                 [DllImport (MPH, SetLastError=true,
3897                                 EntryPoint="Mono_Posix_Syscall_fpathconf")]
3898                 public static extern long fpathconf (int filedes, PathconfName name, Errno defaultError);
3899
3900                 public static long fpathconf (int filedes, PathconfName name)
3901                 {
3902                         return fpathconf (filedes, name, (Errno) 0);
3903                 }
3904
3905                 [DllImport (MPH, SetLastError=true,
3906                                 EntryPoint="Mono_Posix_Syscall_pathconf")]
3907                 public static extern long pathconf (
3908                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3909                                 string path, PathconfName name, Errno defaultError);
3910
3911                 public static long pathconf (string path, PathconfName name)
3912                 {
3913                         return pathconf (path, name, (Errno) 0);
3914                 }
3915
3916                 [DllImport (MPH, SetLastError=true,
3917                                 EntryPoint="Mono_Posix_Syscall_sysconf")]
3918                 public static extern long sysconf (SysconfName name, Errno defaultError);
3919
3920                 public static long sysconf (SysconfName name)
3921                 {
3922                         return sysconf (name, (Errno) 0);
3923                 }
3924
3925                 // confstr(3)
3926                 //    size_t confstr(int name, char *buf, size_t len);
3927                 [DllImport (MPH, SetLastError=true,
3928                                 EntryPoint="Mono_Posix_Syscall_confstr")]
3929                 public static extern ulong confstr (ConfstrName name, [Out] StringBuilder buf, ulong len);
3930
3931                 // getpid(2)
3932                 //    pid_t getpid(void);
3933                 [DllImport (LIBC, SetLastError=true)]
3934                 public static extern int getpid ();
3935
3936                 // getppid(2)
3937                 //    pid_t getppid(void);
3938                 [DllImport (LIBC, SetLastError=true)]
3939                 public static extern int getppid ();
3940
3941                 // setpgid(2)
3942                 //    int setpgid(pid_t pid, pid_t pgid);
3943                 [DllImport (LIBC, SetLastError=true)]
3944                 public static extern int setpgid (int pid, int pgid);
3945
3946                 // getpgid(2)
3947                 //    pid_t getpgid(pid_t pid);
3948                 [DllImport (LIBC, SetLastError=true)]
3949                 public static extern int getpgid (int pid);
3950
3951                 [DllImport (LIBC, SetLastError=true)]
3952                 public static extern int setpgrp ();
3953
3954                 // getpgrp(2)
3955                 //    pid_t getpgrp(void);
3956                 [DllImport (LIBC, SetLastError=true)]
3957                 public static extern int getpgrp ();
3958
3959                 // setsid(2)
3960                 //    pid_t setsid(void);
3961                 [DllImport (LIBC, SetLastError=true)]
3962                 public static extern int setsid ();
3963
3964                 // getsid(2)
3965                 //    pid_t getsid(pid_t pid);
3966                 [DllImport (LIBC, SetLastError=true)]
3967                 public static extern int getsid (int pid);
3968
3969                 // getuid(2)
3970                 //    uid_t getuid(void);
3971                 [DllImport (LIBC, SetLastError=true)]
3972                 public static extern uint getuid ();
3973
3974                 // geteuid(2)
3975                 //    uid_t geteuid(void);
3976                 [DllImport (LIBC, SetLastError=true)]
3977                 public static extern uint geteuid ();
3978
3979                 // getgid(2)
3980                 //    gid_t getgid(void);
3981                 [DllImport (LIBC, SetLastError=true)]
3982                 public static extern uint getgid ();
3983
3984                 // getegid(2)
3985                 //    gid_t getgid(void);
3986                 [DllImport (LIBC, SetLastError=true)]
3987                 public static extern uint getegid ();
3988
3989                 // getgroups(2)
3990                 //    int getgroups(int size, gid_t list[]);
3991                 [DllImport (LIBC, SetLastError=true)]
3992                 public static extern int getgroups (int size, uint[] list);
3993
3994                 public static int getgroups (uint[] list)
3995                 {
3996                         return getgroups (list.Length, list);
3997                 }
3998
3999                 // setuid(2)
4000                 //    int setuid(uid_t uid);
4001                 [DllImport (LIBC, SetLastError=true)]
4002                 public static extern int setuid (uint uid);
4003
4004                 // setreuid(2)
4005                 //    int setreuid(uid_t ruid, uid_t euid);
4006                 [DllImport (LIBC, SetLastError=true)]
4007                 public static extern int setreuid (uint ruid, uint euid);
4008
4009                 // setregid(2)
4010                 //    int setregid(gid_t ruid, gid_t euid);
4011                 [DllImport (LIBC, SetLastError=true)]
4012                 public static extern int setregid (uint rgid, uint egid);
4013
4014                 // seteuid(2)
4015                 //    int seteuid(uid_t euid);
4016                 [DllImport (LIBC, SetLastError=true)]
4017                 public static extern int seteuid (uint euid);
4018
4019                 // setegid(2)
4020                 //    int setegid(gid_t euid);
4021                 [DllImport (LIBC, SetLastError=true)]
4022                 public static extern int setegid (uint uid);
4023
4024                 // setgid(2)
4025                 //    int setgid(gid_t gid);
4026                 [DllImport (LIBC, SetLastError=true)]
4027                 public static extern int setgid (uint gid);
4028
4029                 // getresuid(2)
4030                 //    int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
4031                 [DllImport (LIBC, SetLastError=true)]
4032                 public static extern int getresuid (out uint ruid, out uint euid, out uint suid);
4033
4034                 // getresgid(2)
4035                 //    int getresgid(gid_t *ruid, gid_t *euid, gid_t *suid);
4036                 [DllImport (LIBC, SetLastError=true)]
4037                 public static extern int getresgid (out uint rgid, out uint egid, out uint sgid);
4038
4039                 // setresuid(2)
4040                 //    int setresuid(uid_t ruid, uid_t euid, uid_t suid);
4041                 [DllImport (LIBC, SetLastError=true)]
4042                 public static extern int setresuid (uint ruid, uint euid, uint suid);
4043
4044                 // setresgid(2)
4045                 //    int setresgid(gid_t ruid, gid_t euid, gid_t suid);
4046                 [DllImport (LIBC, SetLastError=true)]
4047                 public static extern int setresgid (uint rgid, uint egid, uint sgid);
4048
4049 #if false
4050                 // fork(2)
4051                 //    pid_t fork(void);
4052                 [DllImport (LIBC, SetLastError=true)]
4053                 [Obsolete ("DO NOT directly call fork(2); it bypasses essential " + 
4054                                 "shutdown code.\nUse System.Diagnostics.Process instead")]
4055                 private static extern int fork ();
4056
4057                 // vfork(2)
4058                 //    pid_t vfork(void);
4059                 [DllImport (LIBC, SetLastError=true)]
4060                 [Obsolete ("DO NOT directly call vfork(2); it bypasses essential " + 
4061                                 "shutdown code.\nUse System.Diagnostics.Process instead")]
4062                 private static extern int vfork ();
4063 #endif
4064
4065                 private static object tty_lock = new object ();
4066
4067                 [DllImport (LIBC, SetLastError=true, EntryPoint="ttyname")]
4068                 private static extern IntPtr sys_ttyname (int fd);
4069
4070                 public static string ttyname (int fd)
4071                 {
4072                         lock (tty_lock) {
4073                                 IntPtr r = sys_ttyname (fd);
4074                                 return UnixMarshal.PtrToString (r);
4075                         }
4076                 }
4077
4078                 // ttyname_r(3)
4079                 //    int ttyname_r(int fd, char *buf, size_t buflen);
4080                 [DllImport (MPH, SetLastError=true,
4081                                 EntryPoint="Mono_Posix_Syscall_ttyname_r")]
4082                 public static extern int ttyname_r (int fd, [Out] StringBuilder buf, ulong buflen);
4083
4084                 public static int ttyname_r (int fd, StringBuilder buf)
4085                 {
4086                         return ttyname_r (fd, buf, (ulong) buf.Capacity);
4087                 }
4088
4089                 [DllImport (LIBC, EntryPoint="isatty")]
4090                 private static extern int sys_isatty (int fd);
4091
4092                 public static bool isatty (int fd)
4093                 {
4094                         return sys_isatty (fd) == 1;
4095                 }
4096
4097                 [DllImport (LIBC, SetLastError=true)]
4098                 public static extern int link (
4099                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4100                                 string oldpath, 
4101                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4102                                 string newpath);
4103
4104                 [DllImport (LIBC, SetLastError=true)]
4105                 public static extern int symlink (
4106                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4107                                 string oldpath, 
4108                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4109                                 string newpath);
4110
4111                 delegate long DoReadlinkFun (byte[] target);
4112
4113                 // Helper function for readlink(string, StringBuilder) and readlinkat (int, string, StringBuilder)
4114                 static int ReadlinkIntoStringBuilder (DoReadlinkFun doReadlink, [Out] StringBuilder buf, ulong bufsiz)
4115                 {
4116                         // bufsiz > int.MaxValue can't work because StringBuilder can store only int.MaxValue chars
4117                         int bufsizInt = checked ((int) bufsiz);
4118                         var target = new byte [bufsizInt];
4119
4120                         var r = doReadlink (target);
4121                         if (r < 0)
4122                                 return checked ((int) r);
4123
4124                         buf.Length = 0;
4125                         var chars = UnixEncoding.Instance.GetChars (target, 0, checked ((int) r));
4126                         // Make sure that at more bufsiz chars are written
4127                         buf.Append (chars, 0, System.Math.Min (bufsizInt, chars.Length));
4128                         if (r == bufsizInt) {
4129                                 // may not have read full contents; fill 'buf' so that caller can properly check
4130                                 buf.Append (new string ('\x00', bufsizInt - buf.Length));
4131                         }
4132                         return buf.Length;
4133                 }
4134
4135                 // readlink(2)
4136                 //    ssize_t readlink(const char *path, char *buf, size_t bufsize);
4137                 public static int readlink (string path, [Out] StringBuilder buf, ulong bufsiz)
4138                 {
4139                         return ReadlinkIntoStringBuilder (target => readlink (path, target), buf, bufsiz);
4140                 }
4141
4142                 public static int readlink (string path, [Out] StringBuilder buf)
4143                 {
4144                         return readlink (path, buf, (ulong) buf.Capacity);
4145                 }
4146
4147                 [DllImport (MPH, SetLastError=true,
4148                                 EntryPoint="Mono_Posix_Syscall_readlink")]
4149                 private static extern long readlink (
4150                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4151                                 string path, byte[] buf, ulong bufsiz);
4152
4153                 public static long readlink (string path, byte[] buf)
4154                 {
4155                         return readlink (path, buf, (ulong) buf.LongLength);
4156                 }
4157
4158                 [DllImport (LIBC, SetLastError=true)]
4159                 public static extern int unlink (
4160                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4161                                 string pathname);
4162
4163                 [DllImport (LIBC, SetLastError=true)]
4164                 public static extern int rmdir (
4165                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4166                                 string pathname);
4167
4168                 // tcgetpgrp(3)
4169                 //    pid_t tcgetpgrp(int fd);
4170                 [DllImport (LIBC, SetLastError=true)]
4171                 public static extern int tcgetpgrp (int fd);
4172
4173                 // tcsetpgrp(3)
4174                 //    int tcsetpgrp(int fd, pid_t pgrp);
4175                 [DllImport (LIBC, SetLastError=true)]
4176                 public static extern int tcsetpgrp (int fd, int pgrp);
4177
4178                 [DllImport (LIBC, SetLastError=true, EntryPoint="getlogin")]
4179                 private static extern IntPtr sys_getlogin ();
4180
4181                 public static string getlogin ()
4182                 {
4183                         lock (getlogin_lock) {
4184                                 IntPtr r = sys_getlogin ();
4185                                 return UnixMarshal.PtrToString (r);
4186                         }
4187                 }
4188
4189                 // getlogin_r(3)
4190                 //    int getlogin_r(char *buf, size_t bufsize);
4191                 [DllImport (MPH, SetLastError=true,
4192                                 EntryPoint="Mono_Posix_Syscall_getlogin_r")]
4193                 public static extern int getlogin_r ([Out] StringBuilder name, ulong bufsize);
4194
4195                 public static int getlogin_r (StringBuilder name)
4196                 {
4197                         return getlogin_r (name, (ulong) name.Capacity);
4198                 }
4199
4200                 [DllImport (LIBC, SetLastError=true)]
4201                 public static extern int setlogin (string name);
4202
4203                 // gethostname(2)
4204                 //    int gethostname(char *name, size_t len);
4205                 [DllImport (MPH, SetLastError=true,
4206                                 EntryPoint="Mono_Posix_Syscall_gethostname")]
4207                 public static extern int gethostname ([Out] StringBuilder name, ulong len);
4208
4209                 public static int gethostname (StringBuilder name)
4210                 {
4211                         return gethostname (name, (ulong) name.Capacity);
4212                 }
4213
4214                 // sethostname(2)
4215                 //    int gethostname(const char *name, size_t len);
4216                 [DllImport (MPH, SetLastError=true,
4217                                 EntryPoint="Mono_Posix_Syscall_sethostname")]
4218                 public static extern int sethostname (string name, ulong len);
4219
4220                 public static int sethostname (string name)
4221                 {
4222                         return sethostname (name, (ulong) name.Length);
4223                 }
4224
4225                 [DllImport (MPH, SetLastError=true,
4226                                 EntryPoint="Mono_Posix_Syscall_gethostid")]
4227                 public static extern long gethostid ();
4228
4229                 [DllImport (MPH, SetLastError=true,
4230                                 EntryPoint="Mono_Posix_Syscall_sethostid")]
4231                 public static extern int sethostid (long hostid);
4232
4233                 // getdomainname(2)
4234                 //    int getdomainname(char *name, size_t len);
4235                 [DllImport (MPH, SetLastError=true,
4236                                 EntryPoint="Mono_Posix_Syscall_getdomainname")]
4237                 public static extern int getdomainname ([Out] StringBuilder name, ulong len);
4238
4239                 public static int getdomainname (StringBuilder name)
4240                 {
4241                         return getdomainname (name, (ulong) name.Capacity);
4242                 }
4243
4244                 // setdomainname(2)
4245                 //    int setdomainname(const char *name, size_t len);
4246                 [DllImport (MPH, SetLastError=true,
4247                                 EntryPoint="Mono_Posix_Syscall_setdomainname")]
4248                 public static extern int setdomainname (string name, ulong len);
4249
4250                 public static int setdomainname (string name)
4251                 {
4252                         return setdomainname (name, (ulong) name.Length);
4253                 }
4254
4255                 [DllImport (LIBC, SetLastError=true)]
4256                 public static extern int vhangup ();
4257
4258                 // Revoke doesn't appear to be POSIX.  Include it?
4259                 [DllImport (LIBC, SetLastError=true)]
4260                 public static extern int revoke (
4261                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4262                                 string file);
4263
4264                 // TODO: profil?  It's not POSIX.
4265
4266                 [DllImport (LIBC, SetLastError=true)]
4267                 public static extern int acct (
4268                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4269                                 string filename);
4270
4271                 [DllImport (LIBC, SetLastError=true, EntryPoint="getusershell")]
4272                 private static extern IntPtr sys_getusershell ();
4273
4274                 internal static object usershell_lock = new object ();
4275
4276                 public static string getusershell ()
4277                 {
4278                         lock (usershell_lock) {
4279                                 IntPtr r = sys_getusershell ();
4280                                 return UnixMarshal.PtrToString (r);
4281                         }
4282                 }
4283
4284                 [DllImport (MPH, SetLastError=true, 
4285                                 EntryPoint="Mono_Posix_Syscall_setusershell")]
4286                 private static extern int sys_setusershell ();
4287
4288                 public static int setusershell ()
4289                 {
4290                         lock (usershell_lock) {
4291                                 return sys_setusershell ();
4292                         }
4293                 }
4294
4295                 [DllImport (MPH, SetLastError=true, 
4296                                 EntryPoint="Mono_Posix_Syscall_endusershell")]
4297                 private static extern int sys_endusershell ();
4298
4299                 public static int endusershell ()
4300                 {
4301                         lock (usershell_lock) {
4302                                 return sys_endusershell ();
4303                         }
4304                 }
4305
4306 #if false
4307                 [DllImport (LIBC, SetLastError=true)]
4308                 private static extern int daemon (int nochdir, int noclose);
4309
4310                 // this implicitly forks, and thus isn't safe.
4311                 private static int daemon (bool nochdir, bool noclose)
4312                 {
4313                         return daemon (nochdir ? 1 : 0, noclose ? 1 : 0);
4314                 }
4315 #endif
4316
4317                 [DllImport (LIBC, SetLastError=true)]
4318                 public static extern int chroot (
4319                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4320                                 string path);
4321
4322                 // skipping getpass(3) as the man page states:
4323                 //   This function is obsolete.  Do not use it.
4324
4325                 [DllImport (LIBC, SetLastError=true)]
4326                 public static extern int fsync (int fd);
4327
4328                 [DllImport (LIBC, SetLastError=true)]
4329                 public static extern int fdatasync (int fd);
4330
4331                 [DllImport (MPH, SetLastError=true,
4332                                 EntryPoint="Mono_Posix_Syscall_sync")]
4333                 public static extern int sync ();
4334
4335                 [DllImport (LIBC, SetLastError=true)]
4336                 [Obsolete ("Dropped in POSIX 1003.1-2001.  " +
4337                                 "Use Syscall.sysconf (SysconfName._SC_PAGESIZE).")]
4338                 public static extern int getpagesize ();
4339
4340                 // truncate(2)
4341                 //    int truncate(const char *path, off_t length);
4342                 [DllImport (MPH, SetLastError=true, 
4343                                 EntryPoint="Mono_Posix_Syscall_truncate")]
4344                 public static extern int truncate (
4345                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4346                                 string path, long length);
4347
4348                 // ftruncate(2)
4349                 //    int ftruncate(int fd, off_t length);
4350                 [DllImport (MPH, SetLastError=true, 
4351                                 EntryPoint="Mono_Posix_Syscall_ftruncate")]
4352                 public static extern int ftruncate (int fd, long length);
4353
4354                 [DllImport (LIBC, SetLastError=true)]
4355                 public static extern int getdtablesize ();
4356
4357                 [DllImport (LIBC, SetLastError=true)]
4358                 public static extern int brk (IntPtr end_data_segment);
4359
4360                 [DllImport (LIBC, SetLastError=true)]
4361                 public static extern IntPtr sbrk (IntPtr increment);
4362
4363                 // TODO: syscall(2)?
4364                 // Probably safer to skip entirely.
4365
4366                 // lockf(3)
4367                 //    int lockf(int fd, int cmd, off_t len);
4368                 [DllImport (MPH, SetLastError=true, 
4369                                 EntryPoint="Mono_Posix_Syscall_lockf")]
4370                 public static extern int lockf (int fd, LockfCommand cmd, long len);
4371
4372                 [Obsolete ("This is insecure and should not be used", true)]
4373                 public static string crypt (string key, string salt)
4374                 {
4375                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
4376                 }
4377
4378                 [Obsolete ("This is insecure and should not be used", true)]
4379                 public static int encrypt (byte[] block, bool decode)
4380                 {
4381                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
4382                 }
4383
4384                 // swab(3)
4385                 //    void swab(const void *from, void *to, ssize_t n);
4386                 [DllImport (MPH, SetLastError=true, 
4387                                 EntryPoint="Mono_Posix_Syscall_swab")]
4388                 public static extern int swab (IntPtr from, IntPtr to, long n);
4389
4390                 public static unsafe void swab (void* from, void* to, long n)
4391                 {
4392                         swab ((IntPtr) from, (IntPtr) to, n);
4393                 }
4394
4395                 [DllImport (LIBC, SetLastError=true, EntryPoint="faccessat")]
4396                 private static extern int sys_faccessat (int dirfd,
4397                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4398                                 string pathname, int mode, int flags);
4399
4400                 public static int faccessat (int dirfd, string pathname, AccessModes mode, AtFlags flags)
4401                 {
4402                         int _mode = NativeConvert.FromAccessModes (mode);
4403                         int _flags = NativeConvert.FromAtFlags (flags);
4404                         return sys_faccessat (dirfd, pathname, _mode, _flags);
4405                 }
4406
4407                 // fchownat(2)
4408                 //    int fchownat(int dirfd, const char *path, uid_t owner, gid_t group, int flags);
4409                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchownat")]
4410                 private static extern int sys_fchownat (int dirfd,
4411                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4412                                 string pathname, uint owner, uint group, int flags);
4413
4414                 public static int fchownat (int dirfd, string pathname, uint owner, uint group, AtFlags flags)
4415                 {
4416                         int _flags = NativeConvert.FromAtFlags (flags);
4417                         return sys_fchownat (dirfd, pathname, owner, group, _flags);
4418                 }
4419
4420                 [DllImport (LIBC, SetLastError=true, EntryPoint="linkat")]
4421                 private static extern int sys_linkat (int olddirfd,
4422                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4423                                 string oldpath, int newdirfd,
4424                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4425                                 string newpath, int flags);
4426
4427                 public static int linkat (int olddirfd, string oldpath, int newdirfd, string newpath, AtFlags flags)
4428                 {
4429                         int _flags = NativeConvert.FromAtFlags (flags);
4430                         return sys_linkat (olddirfd, oldpath, newdirfd, newpath, _flags);
4431                 }
4432
4433                 // readlinkat(2)
4434                 //    ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsize);
4435                 public static int readlinkat (int dirfd, string pathname, [Out] StringBuilder buf, ulong bufsiz)
4436                 {
4437                         return ReadlinkIntoStringBuilder (target => readlinkat (dirfd, pathname, target), buf, bufsiz);
4438                 }
4439
4440                 public static int readlinkat (int dirfd, string pathname, [Out] StringBuilder buf)
4441                 {
4442                         return readlinkat (dirfd, pathname, buf, (ulong) buf.Capacity);
4443                 }
4444
4445                 [DllImport (MPH, SetLastError=true,
4446                                 EntryPoint="Mono_Posix_Syscall_readlinkat")]
4447                 private static extern long readlinkat (int dirfd,
4448                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4449                                 string pathname, byte[] buf, ulong bufsiz);
4450
4451                 public static long readlinkat (int dirfd, string pathname, byte[] buf)
4452                 {
4453                         return readlinkat (dirfd, pathname, buf, (ulong) buf.LongLength);
4454                 }
4455
4456                 [DllImport (LIBC, SetLastError=true)]
4457                 public static extern int symlinkat (
4458                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4459                                 string oldpath, int dirfd,
4460                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4461                                 string newpath);
4462
4463                 [DllImport (LIBC, SetLastError=true, EntryPoint="unlinkat")]
4464                 private static extern int sys_unlinkat (int dirfd,
4465                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4466                                 string pathname, int flags);
4467
4468                 public static int unlinkat (int dirfd, string pathname, AtFlags flags)
4469                 {
4470                         int _flags = NativeConvert.FromAtFlags (flags);
4471                         return sys_unlinkat (dirfd, pathname, _flags);
4472                 }
4473                 #endregion
4474
4475                 #region <utime.h> Declarations
4476                 //
4477                 // <utime.h>  -- COMPLETE
4478                 //
4479
4480                 [DllImport (MPH, SetLastError=true, 
4481                                 EntryPoint="Mono_Posix_Syscall_utime")]
4482                 private static extern int sys_utime (
4483                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4484                                 string filename, ref Utimbuf buf, int use_buf);
4485
4486                 public static int utime (string filename, ref Utimbuf buf)
4487                 {
4488                         return sys_utime (filename, ref buf, 1);
4489                 }
4490
4491                 public static int utime (string filename)
4492                 {
4493                         Utimbuf buf = new Utimbuf ();
4494                         return sys_utime (filename, ref buf, 0);
4495                 }
4496                 #endregion
4497
4498                 #region <sys/uio.h> Declarations
4499                 //
4500                 // <sys/uio.h> -- COMPLETE
4501                 //
4502
4503                 // readv(2)
4504                 //    ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
4505                 [DllImport (MPH, SetLastError=true,
4506                                 EntryPoint="Mono_Posix_Syscall_readv")]
4507                 private static extern long sys_readv (int fd, Iovec[] iov, int iovcnt);
4508
4509                 public static long readv (int fd, Iovec[] iov)
4510                 {
4511                         return sys_readv (fd, iov, iov.Length);
4512                 }
4513
4514                 // writev(2)
4515                 //    ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
4516                 [DllImport (MPH, SetLastError=true,
4517                                 EntryPoint="Mono_Posix_Syscall_writev")]
4518                 private static extern long sys_writev (int fd, Iovec[] iov, int iovcnt);
4519
4520                 public static long writev (int fd, Iovec[] iov)
4521                 {
4522                         return sys_writev (fd, iov, iov.Length);
4523                 }
4524
4525                 // preadv(2)
4526                 //    ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset);
4527                 [DllImport (MPH, SetLastError=true,
4528                                 EntryPoint="Mono_Posix_Syscall_preadv")]
4529                 private static extern long sys_preadv (int fd, Iovec[] iov, int iovcnt, long offset);
4530
4531                 public static long preadv (int fd, Iovec[] iov, long offset)
4532                 {
4533                         return sys_preadv (fd, iov, iov.Length, offset);
4534                 }
4535
4536                 // pwritev(2)
4537                 //    ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset);
4538                 [DllImport (MPH, SetLastError=true,
4539                                 EntryPoint="Mono_Posix_Syscall_pwritev")]
4540                 private static extern long sys_pwritev (int fd, Iovec[] iov, int iovcnt, long offset);
4541
4542                 public static long pwritev (int fd, Iovec[] iov, long offset)
4543                 {
4544                         return sys_pwritev (fd, iov, iov.Length, offset);
4545                 }
4546                 #endregion
4547
4548                 #region <socket.h> Declarations
4549                 //
4550                 // <socket.h>
4551                 //
4552
4553                 // socket(2)
4554                 //    int socket(int domain, int type, int protocol);
4555                 [DllImport (LIBC, SetLastError=true, 
4556                                 EntryPoint="socket")]
4557                 static extern int sys_socket (int domain, int type, int protocol);
4558
4559                 public static int socket (UnixAddressFamily domain, UnixSocketType type, UnixSocketFlags flags, UnixSocketProtocol protocol)
4560                 {
4561                         var _domain = NativeConvert.FromUnixAddressFamily (domain);
4562                         var _type = NativeConvert.FromUnixSocketType (type);
4563                         var _flags = NativeConvert.FromUnixSocketFlags (flags);
4564                         // protocol == 0 is a special case (uses default protocol)
4565                         var _protocol = protocol == 0 ? 0 : NativeConvert.FromUnixSocketProtocol (protocol);
4566
4567                         return sys_socket (_domain, _type | _flags, _protocol);
4568                 }
4569
4570                 public static int socket (UnixAddressFamily domain, UnixSocketType type, UnixSocketProtocol protocol)
4571                 {
4572                         return socket (domain, type, 0, protocol);
4573                 }
4574
4575                 // socketpair(2)
4576                 //    int socketpair(int domain, int type, int protocol, int sv[2]);
4577                 [DllImport (MPH, SetLastError=true, 
4578                                 EntryPoint="Mono_Posix_Syscall_socketpair")]
4579                 static extern int sys_socketpair (int domain, int type, int protocol, out int socket1, out int socket2);
4580
4581                 public static int socketpair (UnixAddressFamily domain, UnixSocketType type, UnixSocketFlags flags, UnixSocketProtocol protocol, out int socket1, out int socket2)
4582                 {
4583                         var _domain = NativeConvert.FromUnixAddressFamily (domain);
4584                         var _type = NativeConvert.FromUnixSocketType (type);
4585                         var _flags = NativeConvert.FromUnixSocketFlags (flags);
4586                         // protocol == 0 is a special case (uses default protocol)
4587                         var _protocol = protocol == 0 ? 0 : NativeConvert.FromUnixSocketProtocol (protocol);
4588
4589                         return sys_socketpair (_domain, _type | _flags, _protocol, out socket1, out socket2);
4590                 }
4591
4592                 public static int socketpair (UnixAddressFamily domain, UnixSocketType type, UnixSocketProtocol protocol, out int socket1, out int socket2)
4593                 {
4594                         return socketpair (domain, type, 0, protocol, out socket1, out socket2);
4595                 }
4596
4597                 // sockatmark(2)
4598                 //    int sockatmark(int sockfd);
4599                 [DllImport (LIBC, SetLastError=true)]
4600                 public static extern int sockatmark (int socket);
4601
4602                 // listen(2)
4603                 //    int listen(int sockfd, int backlog);
4604                 [DllImport (LIBC, SetLastError=true)]
4605                 public static extern int listen (int socket, int backlog);
4606
4607                 // getsockopt(2)
4608                 //    int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
4609                 [DllImport (MPH, SetLastError=true, 
4610                                 EntryPoint="Mono_Posix_Syscall_getsockopt")]
4611                 static extern unsafe int sys_getsockopt (int socket, int level, int option_name, void *option_value, ref long option_len);
4612
4613                 [DllImport (MPH, SetLastError=true, 
4614                                 EntryPoint="Mono_Posix_Syscall_getsockopt_timeval")]
4615                 static extern unsafe int sys_getsockopt_timeval (int socket, int level, int option_name, out Timeval option_value);
4616
4617                 [DllImport (MPH, SetLastError=true, 
4618                                 EntryPoint="Mono_Posix_Syscall_getsockopt_linger")]
4619                 static extern unsafe int sys_getsockopt_linger (int socket, int level, int option_name, out Linger option_value);
4620
4621                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, void *option_value, ref long option_len)
4622                 {
4623                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4624                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4625                         return sys_getsockopt (socket, _level, _option_name, option_value, ref option_len);
4626                 }
4627
4628                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, IntPtr option_value, ref long option_len)
4629                 {
4630                         return getsockopt (socket, level, option_name, (void*) option_value, ref option_len);
4631                 }
4632
4633                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out int option_value)
4634                 {
4635                         int value;
4636                         long size = sizeof (int);
4637                         int ret = getsockopt (socket, level, option_name, &value, ref size);
4638                         if (ret != -1 && size != sizeof (int)) {
4639                                 SetLastError (Errno.EINVAL);
4640                                 ret = -1;
4641                         }
4642                         option_value = value;
4643                         return ret;
4644                 }
4645
4646                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, byte[] option_value, ref long option_len)
4647                 {
4648                         if (option_len > (option_value == null ? 0 : option_value.Length))
4649                                 throw new ArgumentOutOfRangeException ("option_len", "option_len > (option_value == null ? 0 : option_value.Length)");
4650                         fixed (byte* ptr = option_value)
4651                                 return getsockopt (socket, level, option_name, ptr, ref option_len);
4652                 }
4653
4654                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out Timeval option_value)
4655                 {
4656                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4657                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4658                         return sys_getsockopt_timeval (socket, _level, _option_name, out option_value);
4659                 }
4660
4661                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out Linger option_value)
4662                 {
4663                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4664                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4665                         return sys_getsockopt_linger (socket, _level, _option_name, out option_value);
4666                 }
4667
4668                 // setsockopt(2)
4669                 //    int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
4670                 [DllImport (MPH, SetLastError=true, 
4671                                 EntryPoint="Mono_Posix_Syscall_setsockopt")]
4672                 static extern unsafe int sys_setsockopt (int socket, int level, int option_name, void *option_value, long option_len);
4673
4674                 [DllImport (MPH, SetLastError=true, 
4675                                 EntryPoint="Mono_Posix_Syscall_setsockopt_timeval")]
4676                 static extern unsafe int sys_setsockopt_timeval (int socket, int level, int option_name, ref Timeval option_value);
4677
4678                 [DllImport (MPH, SetLastError=true, 
4679                                 EntryPoint="Mono_Posix_Syscall_setsockopt_linger")]
4680                 static extern unsafe int sys_setsockopt_linger (int socket, int level, int option_name, ref Linger option_value);
4681
4682                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, void *option_value, long option_len)
4683                 {
4684                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4685                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4686                         return sys_setsockopt (socket, _level, _option_name, option_value, option_len);
4687                 }
4688
4689                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, IntPtr option_value, long option_len)
4690                 {
4691                         return setsockopt (socket, level, option_name, (void*) option_value, option_len);
4692                 }
4693
4694                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, int option_value)
4695                 {
4696                         return setsockopt (socket, level, option_name, &option_value, sizeof (int));
4697                 }
4698
4699                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, byte[] option_value, long option_len)
4700                 {
4701                         if (option_len > (option_value == null ? 0 : option_value.Length))
4702                                 throw new ArgumentOutOfRangeException ("option_len", "option_len > (option_value == null ? 0 : option_value.Length)");
4703                         fixed (byte* ptr = option_value)
4704                                 return setsockopt (socket, level, option_name, ptr, option_len);
4705                 }
4706
4707                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, Timeval option_value)
4708                 {
4709                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4710                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4711                         return sys_setsockopt_timeval (socket, _level, _option_name, ref option_value);
4712                 }
4713
4714                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, Linger option_value)
4715                 {
4716                         var _level = NativeConvert.FromUnixSocketProtocol (level);
4717                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
4718                         return sys_setsockopt_linger (socket, _level, _option_name, ref option_value);
4719                 }
4720
4721                 // shutdown(2)
4722                 //    int shutdown(int sockfd, int how);
4723                 [DllImport (LIBC, SetLastError=true, 
4724                                 EntryPoint="shutdown")]
4725                 static extern int sys_shutdown (int socket, int how);
4726
4727                 public static int shutdown (int socket, ShutdownOption how)
4728                 {
4729                         var _how = NativeConvert.FromShutdownOption (how);
4730                         return sys_shutdown (socket, _how);
4731                 }
4732
4733                 // recv(2)
4734                 //    ssize_t recv(int sockfd, void *buf, size_t len, int flags);
4735                 [DllImport (MPH, SetLastError=true, 
4736                                 EntryPoint="Mono_Posix_Syscall_recv")]
4737                 static extern unsafe long sys_recv (int socket, void *buffer, ulong length, int flags);
4738
4739                 public static unsafe long recv (int socket, void *buffer, ulong length, MessageFlags flags)
4740                 {
4741                         int _flags = NativeConvert.FromMessageFlags (flags);
4742                         return sys_recv (socket, buffer, length, _flags);
4743                 }
4744
4745                 public static unsafe long recv (int socket, IntPtr buffer, ulong length, MessageFlags flags)
4746                 {
4747                         return recv (socket, (void*) buffer, length, flags);
4748                 }
4749
4750                 public static unsafe long recv (int socket, byte[] buffer, ulong length, MessageFlags flags)
4751                 {
4752                         if (length > (ulong) (buffer == null ? 0 : buffer.LongLength))
4753                                 throw new ArgumentOutOfRangeException ("length", "length > (buffer == null ? 0 : buffer.LongLength)");
4754                         fixed (byte* ptr = buffer)
4755                                 return recv (socket, ptr, length, flags);
4756                 }
4757
4758                 // send(2)
4759                 //    ssize_t send(int sockfd, const void *buf, size_t len, int flags);
4760                 [DllImport (MPH, SetLastError=true, 
4761                                 EntryPoint="Mono_Posix_Syscall_send")]
4762                 static extern unsafe long sys_send (int socket, void *message, ulong length, int flags);
4763
4764                 public static unsafe long send (int socket, void *message, ulong length, MessageFlags flags)
4765                 {
4766                         int _flags = NativeConvert.FromMessageFlags (flags);
4767                         return sys_send (socket, message, length, _flags);
4768                 }
4769
4770                 public static unsafe long send (int socket, IntPtr message, ulong length, MessageFlags flags)
4771                 {
4772                         return send (socket, (void*) message, length, flags);
4773                 }
4774
4775                 public static unsafe long send (int socket, byte[] message, ulong length, MessageFlags flags)
4776                 {
4777                         if (length > (ulong) (message == null ? 0 : message.LongLength))
4778                                 throw new ArgumentOutOfRangeException ("length", "length > (message == null ? 0 : message.LongLength)");
4779                         fixed (byte* ptr = message)
4780                                 return send (socket, ptr, length, flags);
4781                 }
4782
4783                 #endregion
4784         }
4785
4786         #endregion
4787 }
4788
4789 // vim: noexpandtab