[Mono.Posix] Add wrappers for struct sockaddr_*
[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                 // Value used when a syscall returns an unknown address family value
826                 Unknown       = 65536,
827         }
828
829         [Map]
830         [CLSCompliant (false)]
831         public enum UnixSocketOptionName : int {
832                 SO_DEBUG                         =  1,
833                 SO_REUSEADDR                     =  2,
834                 SO_TYPE                          =  3,
835                 SO_ERROR                         =  4,
836                 SO_DONTROUTE                     =  5,
837                 SO_BROADCAST                     =  6,
838                 SO_SNDBUF                        =  7,
839                 SO_RCVBUF                        =  8,
840                 SO_SNDBUFFORCE                   = 32,
841                 SO_RCVBUFFORCE                   = 33,
842                 SO_KEEPALIVE                     =  9,
843                 SO_OOBINLINE                     = 10,
844                 SO_NO_CHECK                      = 11,
845                 SO_PRIORITY                      = 12,
846                 SO_LINGER                        = 13,
847                 SO_BSDCOMPAT                     = 14,
848                 SO_REUSEPORT                     = 15,
849                 SO_PASSCRED                      = 16,
850                 SO_PEERCRED                      = 17,
851                 SO_RCVLOWAT                      = 18,
852                 SO_SNDLOWAT                      = 19,
853                 SO_RCVTIMEO                      = 20,
854                 SO_SNDTIMEO                      = 21,
855                 SO_SECURITY_AUTHENTICATION       = 22,
856                 SO_SECURITY_ENCRYPTION_TRANSPORT = 23,
857                 SO_SECURITY_ENCRYPTION_NETWORK   = 24,
858                 SO_BINDTODEVICE                  = 25,
859                 SO_ATTACH_FILTER                 = 26,
860                 SO_DETACH_FILTER                 = 27,
861                 SO_PEERNAME                      = 28,
862                 SO_TIMESTAMP                     = 29,
863                 SO_ACCEPTCONN                    = 30,
864                 SO_PEERSEC                       = 31,
865                 SO_PASSSEC                       = 34,
866                 SO_TIMESTAMPNS                   = 35,
867                 SO_MARK                          = 36,
868                 SO_TIMESTAMPING                  = 37,
869                 SO_PROTOCOL                      = 38,
870                 SO_DOMAIN                        = 39,
871                 SO_RXQ_OVFL                      = 40,
872                 SO_WIFI_STATUS                   = 41,
873                 SO_PEEK_OFF                      = 42,
874                 SO_NOFCS                         = 43,
875                 SO_LOCK_FILTER                   = 44,
876                 SO_SELECT_ERR_QUEUE              = 45,
877                 SO_BUSY_POLL                     = 46,
878                 SO_MAX_PACING_RATE               = 47,
879         }
880
881         [Flags][Map]
882         [CLSCompliant (false)]
883         public enum MessageFlags : int {
884                 MSG_OOB          =       0x01, /* Process out-of-band data. */
885                 MSG_PEEK         =       0x02, /* Peek at incoming messages. */
886                 MSG_DONTROUTE    =       0x04, /* Don't use local routing. */
887                 MSG_CTRUNC       =       0x08, /* Control data lost before delivery. */
888                 MSG_PROXY        =       0x10, /* Supply or ask second address. */
889                 MSG_TRUNC        =       0x20,
890                 MSG_DONTWAIT     =       0x40, /* Nonblocking IO. */
891                 MSG_EOR          =       0x80, /* End of record. */
892                 MSG_WAITALL      =      0x100, /* Wait for a full request. */
893                 MSG_FIN          =      0x200,
894                 MSG_SYN          =      0x400,
895                 MSG_CONFIRM      =      0x800, /* Confirm path validity. */
896                 MSG_RST          =     0x1000,
897                 MSG_ERRQUEUE     =     0x2000, /* Fetch message from error queue. */
898                 MSG_NOSIGNAL     =     0x4000, /* Do not generate SIGPIPE. */
899                 MSG_MORE         =     0x8000, /* Sender will send more. */
900                 MSG_WAITFORONE   =    0x10000, /* Wait for at least one packet to return.*/
901                 MSG_FASTOPEN     = 0x20000000, /* Send data in TCP SYN. */
902                 MSG_CMSG_CLOEXEC = 0x40000000, /* Set close_on_exit for file descriptor received through SCM_RIGHTS. */
903         }
904
905         [Map]
906         [CLSCompliant (false)]
907         public enum ShutdownOption : int {
908                 SHUT_RD   = 0x01,   /* No more receptions. */
909                 SHUT_WR   = 0x02,   /* No more transmissions. */
910                 SHUT_RDWR = 0x03,   /* No more receptions or transmissions. */
911         }
912
913         // Used by libMonoPosixHelper to distinguish between different sockaddr types
914         [Map]
915         enum SockaddrType : int {
916                 Invalid,
917                 SockaddrStorage,
918                 SockaddrUn,
919                 Sockaddr,
920                 SockaddrIn,
921                 SockaddrIn6,
922
923                 // Flag to indicate that this Sockaddr must be wrapped with a _SockaddrDynamic wrapper
924                 MustBeWrapped = 0x8000,
925         }
926
927         #endregion
928
929         #region Structures
930
931         [Map ("struct flock")]
932         public struct Flock
933                 : IEquatable <Flock>
934         {
935                 [CLSCompliant (false)]
936                 public LockType         l_type;    // Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
937                 [CLSCompliant (false)]
938                 public SeekFlags        l_whence;  // How to interpret l_start
939                 [off_t] public long     l_start;   // Starting offset for lock
940                 [off_t] public long     l_len;     // Number of bytes to lock
941                 [pid_t] public int      l_pid;     // PID of process blocking our lock (F_GETLK only)
942
943                 public override int GetHashCode ()
944                 {
945                         return l_type.GetHashCode () ^ l_whence.GetHashCode () ^ 
946                                 l_start.GetHashCode () ^ l_len.GetHashCode () ^
947                                 l_pid.GetHashCode ();
948                 }
949
950                 public override bool Equals (object obj)
951                 {
952                         if ((obj == null) || (obj.GetType () != GetType ()))
953                                 return false;
954                         Flock value = (Flock) obj;
955                         return l_type == value.l_type && l_whence == value.l_whence && 
956                                 l_start == value.l_start && l_len == value.l_len && 
957                                 l_pid == value.l_pid;
958                 }
959
960                 public bool Equals (Flock value)
961                 {
962                         return l_type == value.l_type && l_whence == value.l_whence && 
963                                 l_start == value.l_start && l_len == value.l_len && 
964                                 l_pid == value.l_pid;
965                 }
966
967                 public static bool operator== (Flock lhs, Flock rhs)
968                 {
969                         return lhs.Equals (rhs);
970                 }
971
972                 public static bool operator!= (Flock lhs, Flock rhs)
973                 {
974                         return !lhs.Equals (rhs);
975                 }
976         }
977
978         [Map ("struct pollfd")]
979         public struct Pollfd
980                 : IEquatable <Pollfd>
981         {
982                 public int fd;
983                 [CLSCompliant (false)]
984                 public PollEvents events;
985                 [CLSCompliant (false)]
986                 public PollEvents revents;
987
988                 public override int GetHashCode ()
989                 {
990                         return events.GetHashCode () ^ revents.GetHashCode ();
991                 }
992
993                 public override bool Equals (object obj)
994                 {
995                         if (obj == null || obj.GetType () != GetType ())
996                                 return false;
997                         Pollfd value = (Pollfd) obj;
998                         return value.events == events && value.revents == revents;
999                 }
1000
1001                 public bool Equals (Pollfd value)
1002                 {
1003                         return value.events == events && value.revents == revents;
1004                 }
1005
1006                 public static bool operator== (Pollfd lhs, Pollfd rhs)
1007                 {
1008                         return lhs.Equals (rhs);
1009                 }
1010
1011                 public static bool operator!= (Pollfd lhs, Pollfd rhs)
1012                 {
1013                         return !lhs.Equals (rhs);
1014                 }
1015         }
1016
1017         // Use manually written To/From methods to handle fields st_atime_nsec etc.
1018         public struct Stat
1019                 : IEquatable <Stat>
1020         {
1021                 [CLSCompliant (false)]
1022                 [dev_t]     public ulong    st_dev;     // device
1023                 [CLSCompliant (false)]
1024                 [ino_t]     public  ulong   st_ino;     // inode
1025                 [CLSCompliant (false)]
1026                 public  FilePermissions     st_mode;    // protection
1027                 [NonSerialized]
1028 #pragma warning disable 169             
1029                 private uint                _padding_;  // padding for structure alignment
1030 #pragma warning restore 169             
1031                 [CLSCompliant (false)]
1032                 [nlink_t]   public  ulong   st_nlink;   // number of hard links
1033                 [CLSCompliant (false)]
1034                 [uid_t]     public  uint    st_uid;     // user ID of owner
1035                 [CLSCompliant (false)]
1036                 [gid_t]     public  uint    st_gid;     // group ID of owner
1037                 [CLSCompliant (false)]
1038                 [dev_t]     public  ulong   st_rdev;    // device type (if inode device)
1039                 [off_t]     public  long    st_size;    // total size, in bytes
1040                 [blksize_t] public  long    st_blksize; // blocksize for filesystem I/O
1041                 [blkcnt_t]  public  long    st_blocks;  // number of blocks allocated
1042                 [time_t]    public  long    st_atime;   // time of last access
1043                 [time_t]    public  long    st_mtime;   // time of last modification
1044                 [time_t]    public  long    st_ctime;   // time of last status change
1045                 public  long             st_atime_nsec; // Timespec.tv_nsec partner to st_atime
1046                 public  long             st_mtime_nsec; // Timespec.tv_nsec partner to st_mtime
1047                 public  long             st_ctime_nsec; // Timespec.tv_nsec partner to st_ctime
1048
1049                 public Timespec st_atim {
1050                         get {
1051                                 return new Timespec { tv_sec = st_atime, tv_nsec = st_atime_nsec };
1052                         }
1053                         set {
1054                                 st_atime = value.tv_sec;
1055                                 st_atime_nsec = value.tv_nsec;
1056                         }
1057                 }
1058
1059                 public Timespec st_mtim {
1060                         get {
1061                                 return new Timespec { tv_sec = st_mtime, tv_nsec = st_mtime_nsec };
1062                         }
1063                         set {
1064                                 st_mtime = value.tv_sec;
1065                                 st_mtime_nsec = value.tv_nsec;
1066                         }
1067                 }
1068
1069                 public Timespec st_ctim {
1070                         get {
1071                                 return new Timespec { tv_sec = st_ctime, tv_nsec = st_ctime_nsec };
1072                         }
1073                         set {
1074                                 st_ctime = value.tv_sec;
1075                                 st_ctime_nsec = value.tv_nsec;
1076                         }
1077                 }
1078
1079                 public override int GetHashCode ()
1080                 {
1081                         return st_dev.GetHashCode () ^
1082                                 st_ino.GetHashCode () ^
1083                                 st_mode.GetHashCode () ^
1084                                 st_nlink.GetHashCode () ^
1085                                 st_uid.GetHashCode () ^
1086                                 st_gid.GetHashCode () ^
1087                                 st_rdev.GetHashCode () ^
1088                                 st_size.GetHashCode () ^
1089                                 st_blksize.GetHashCode () ^
1090                                 st_blocks.GetHashCode () ^
1091                                 st_atime.GetHashCode () ^
1092                                 st_mtime.GetHashCode () ^
1093                                 st_ctime.GetHashCode () ^
1094                                 st_atime_nsec.GetHashCode () ^
1095                                 st_mtime_nsec.GetHashCode () ^
1096                                 st_ctime_nsec.GetHashCode ();
1097                 }
1098
1099                 public override bool Equals (object obj)
1100                 {
1101                         if (obj == null || obj.GetType() != GetType ())
1102                                 return false;
1103                         Stat value = (Stat) obj;
1104                         return value.st_dev == st_dev &&
1105                                 value.st_ino == st_ino &&
1106                                 value.st_mode == st_mode &&
1107                                 value.st_nlink == st_nlink &&
1108                                 value.st_uid == st_uid &&
1109                                 value.st_gid == st_gid &&
1110                                 value.st_rdev == st_rdev &&
1111                                 value.st_size == st_size &&
1112                                 value.st_blksize == st_blksize &&
1113                                 value.st_blocks == st_blocks &&
1114                                 value.st_atime == st_atime &&
1115                                 value.st_mtime == st_mtime &&
1116                                 value.st_ctime == st_ctime &&
1117                                 value.st_atime_nsec == st_atime_nsec &&
1118                                 value.st_mtime_nsec == st_mtime_nsec &&
1119                                 value.st_ctime_nsec == st_ctime_nsec;
1120                 }
1121
1122                 public bool Equals (Stat value)
1123                 {
1124                         return value.st_dev == st_dev &&
1125                                 value.st_ino == st_ino &&
1126                                 value.st_mode == st_mode &&
1127                                 value.st_nlink == st_nlink &&
1128                                 value.st_uid == st_uid &&
1129                                 value.st_gid == st_gid &&
1130                                 value.st_rdev == st_rdev &&
1131                                 value.st_size == st_size &&
1132                                 value.st_blksize == st_blksize &&
1133                                 value.st_blocks == st_blocks &&
1134                                 value.st_atime == st_atime &&
1135                                 value.st_mtime == st_mtime &&
1136                                 value.st_ctime == st_ctime &&
1137                                 value.st_atime_nsec == st_atime_nsec &&
1138                                 value.st_mtime_nsec == st_mtime_nsec &&
1139                                 value.st_ctime_nsec == st_ctime_nsec;
1140                 }
1141
1142                 public static bool operator== (Stat lhs, Stat rhs)
1143                 {
1144                         return lhs.Equals (rhs);
1145                 }
1146
1147                 public static bool operator!= (Stat lhs, Stat rhs)
1148                 {
1149                         return !lhs.Equals (rhs);
1150                 }
1151         }
1152
1153         // `struct statvfs' isn't portable, so don't generate To/From methods.
1154         [Map]
1155         [CLSCompliant (false)]
1156         public struct Statvfs
1157                 : IEquatable <Statvfs>
1158         {
1159                 public                  ulong f_bsize;    // file system block size
1160                 public                  ulong f_frsize;   // fragment size
1161                 [fsblkcnt_t] public     ulong f_blocks;   // size of fs in f_frsize units
1162                 [fsblkcnt_t] public     ulong f_bfree;    // # free blocks
1163                 [fsblkcnt_t] public     ulong f_bavail;   // # free blocks for non-root
1164                 [fsfilcnt_t] public     ulong f_files;    // # inodes
1165                 [fsfilcnt_t] public     ulong f_ffree;    // # free inodes
1166                 [fsfilcnt_t] public     ulong f_favail;   // # free inodes for non-root
1167                 public                  ulong f_fsid;     // file system id
1168                 public MountFlags             f_flag;     // mount flags
1169                 public                  ulong f_namemax;  // maximum filename length
1170
1171                 public override int GetHashCode ()
1172                 {
1173                         return f_bsize.GetHashCode () ^
1174                                 f_frsize.GetHashCode () ^
1175                                 f_blocks.GetHashCode () ^
1176                                 f_bfree.GetHashCode () ^
1177                                 f_bavail.GetHashCode () ^
1178                                 f_files.GetHashCode () ^
1179                                 f_ffree.GetHashCode () ^
1180                                 f_favail.GetHashCode () ^
1181                                 f_fsid.GetHashCode () ^
1182                                 f_flag.GetHashCode () ^
1183                                 f_namemax.GetHashCode ();
1184                 }
1185
1186                 public override bool Equals (object obj)
1187                 {
1188                         if (obj == null || obj.GetType() != GetType ())
1189                                 return false;
1190                         Statvfs value = (Statvfs) obj;
1191                         return value.f_bsize == f_bsize &&
1192                                 value.f_frsize == f_frsize &&
1193                                 value.f_blocks == f_blocks &&
1194                                 value.f_bfree == f_bfree &&
1195                                 value.f_bavail == f_bavail &&
1196                                 value.f_files == f_files &&
1197                                 value.f_ffree == f_ffree &&
1198                                 value.f_favail == f_favail &&
1199                                 value.f_fsid == f_fsid &&
1200                                 value.f_flag == f_flag &&
1201                                 value.f_namemax == f_namemax;
1202                 }
1203
1204                 public bool Equals (Statvfs value)
1205                 {
1206                         return value.f_bsize == f_bsize &&
1207                                 value.f_frsize == f_frsize &&
1208                                 value.f_blocks == f_blocks &&
1209                                 value.f_bfree == f_bfree &&
1210                                 value.f_bavail == f_bavail &&
1211                                 value.f_files == f_files &&
1212                                 value.f_ffree == f_ffree &&
1213                                 value.f_favail == f_favail &&
1214                                 value.f_fsid == f_fsid &&
1215                                 value.f_flag == f_flag &&
1216                                 value.f_namemax == f_namemax;
1217                 }
1218
1219                 public static bool operator== (Statvfs lhs, Statvfs rhs)
1220                 {
1221                         return lhs.Equals (rhs);
1222                 }
1223
1224                 public static bool operator!= (Statvfs lhs, Statvfs rhs)
1225                 {
1226                         return !lhs.Equals (rhs);
1227                 }
1228         }
1229
1230         [Map ("struct timeval")]
1231         public struct Timeval
1232                 : IEquatable <Timeval>
1233         {
1234                 [time_t]      public long tv_sec;   // seconds
1235                 [suseconds_t] public long tv_usec;  // microseconds
1236
1237                 public override int GetHashCode ()
1238                 {
1239                         return tv_sec.GetHashCode () ^ tv_usec.GetHashCode ();
1240                 }
1241
1242                 public override bool Equals (object obj)
1243                 {
1244                         if (obj == null || obj.GetType () != GetType ())
1245                                 return false;
1246                         Timeval value = (Timeval) obj;
1247                         return value.tv_sec == tv_sec && value.tv_usec == tv_usec;
1248                 }
1249
1250                 public bool Equals (Timeval value)
1251                 {
1252                         return value.tv_sec == tv_sec && value.tv_usec == tv_usec;
1253                 }
1254
1255                 public static bool operator== (Timeval lhs, Timeval rhs)
1256                 {
1257                         return lhs.Equals (rhs);
1258                 }
1259
1260                 public static bool operator!= (Timeval lhs, Timeval rhs)
1261                 {
1262                         return !lhs.Equals (rhs);
1263                 }
1264         }
1265
1266         [Map ("struct timezone")]
1267         public struct Timezone
1268                 : IEquatable <Timezone>
1269         {
1270                 public  int tz_minuteswest; // minutes W of Greenwich
1271 #pragma warning disable 169             
1272                 private int tz_dsttime;     // type of dst correction (OBSOLETE)
1273 #pragma warning restore 169             
1274
1275                 public override int GetHashCode ()
1276                 {
1277                         return tz_minuteswest.GetHashCode ();
1278                 }
1279
1280                 public override bool Equals (object obj)
1281                 {
1282                         if (obj == null || obj.GetType () != GetType ())
1283                                 return false;
1284                         Timezone value = (Timezone) obj;
1285                         return value.tz_minuteswest == tz_minuteswest;
1286                 }
1287
1288                 public bool Equals (Timezone value)
1289                 {
1290                         return value.tz_minuteswest == tz_minuteswest;
1291                 }
1292
1293                 public static bool operator== (Timezone lhs, Timezone rhs)
1294                 {
1295                         return lhs.Equals (rhs);
1296                 }
1297
1298                 public static bool operator!= (Timezone lhs, Timezone rhs)
1299                 {
1300                         return !lhs.Equals (rhs);
1301                 }
1302         }
1303
1304         [Map ("struct utimbuf")]
1305         public struct Utimbuf
1306                 : IEquatable <Utimbuf>
1307         {
1308                 [time_t] public long    actime;   // access time
1309                 [time_t] public long    modtime;  // modification time
1310
1311                 public override int GetHashCode ()
1312                 {
1313                         return actime.GetHashCode () ^ modtime.GetHashCode ();
1314                 }
1315
1316                 public override bool Equals (object obj)
1317                 {
1318                         if (obj == null || obj.GetType () != GetType ())
1319                                 return false;
1320                         Utimbuf value = (Utimbuf) obj;
1321                         return value.actime == actime && value.modtime == modtime;
1322                 }
1323
1324                 public bool Equals (Utimbuf value)
1325                 {
1326                         return value.actime == actime && value.modtime == modtime;
1327                 }
1328
1329                 public static bool operator== (Utimbuf lhs, Utimbuf rhs)
1330                 {
1331                         return lhs.Equals (rhs);
1332                 }
1333
1334                 public static bool operator!= (Utimbuf lhs, Utimbuf rhs)
1335                 {
1336                         return !lhs.Equals (rhs);
1337                 }
1338         }
1339
1340         [Map ("struct timespec")]
1341         public struct Timespec
1342                 : IEquatable <Timespec>
1343         {
1344                 [time_t] public long    tv_sec;   // Seconds.
1345                 public          long    tv_nsec;  // Nanoseconds.
1346
1347                 public override int GetHashCode ()
1348                 {
1349                         return tv_sec.GetHashCode () ^ tv_nsec.GetHashCode ();
1350                 }
1351
1352                 public override bool Equals (object obj)
1353                 {
1354                         if (obj == null || obj.GetType () != GetType ())
1355                                 return false;
1356                         Timespec value = (Timespec) obj;
1357                         return value.tv_sec == tv_sec && value.tv_nsec == tv_nsec;
1358                 }
1359
1360                 public bool Equals (Timespec value)
1361                 {
1362                         return value.tv_sec == tv_sec && value.tv_nsec == tv_nsec;
1363                 }
1364
1365                 public static bool operator== (Timespec lhs, Timespec rhs)
1366                 {
1367                         return lhs.Equals (rhs);
1368                 }
1369
1370                 public static bool operator!= (Timespec lhs, Timespec rhs)
1371                 {
1372                         return !lhs.Equals (rhs);
1373                 }
1374         }
1375
1376         [Map ("struct iovec")]
1377         public struct Iovec
1378         {
1379                 public IntPtr   iov_base; // Starting address
1380                 [CLSCompliant (false)]
1381                 public ulong    iov_len;  // Number of bytes to transfer
1382         }
1383
1384         [Flags][Map]
1385         public enum EpollFlags {
1386                 EPOLL_CLOEXEC = 02000000,
1387                 EPOLL_NONBLOCK = 04000,
1388         }
1389
1390         [Flags][Map]
1391         [CLSCompliant (false)]
1392         public enum EpollEvents : uint {
1393                 EPOLLIN = 0x001,
1394                 EPOLLPRI = 0x002,
1395                 EPOLLOUT = 0x004,
1396                 EPOLLRDNORM = 0x040,
1397                 EPOLLRDBAND = 0x080,
1398                 EPOLLWRNORM = 0x100,
1399                 EPOLLWRBAND = 0x200,
1400                 EPOLLMSG = 0x400,
1401                 EPOLLERR = 0x008,
1402                 EPOLLHUP = 0x010,
1403                 EPOLLRDHUP = 0x2000,
1404                 EPOLLONESHOT = 1 << 30,
1405                 EPOLLET = unchecked ((uint) (1 << 31))
1406         }
1407
1408         public enum EpollOp {
1409                 EPOLL_CTL_ADD = 1,
1410                 EPOLL_CTL_DEL = 2,
1411                 EPOLL_CTL_MOD = 3,
1412         }
1413
1414         [StructLayout (LayoutKind.Explicit, Size=12, Pack=1)]
1415         [CLSCompliant (false)]
1416         public struct EpollEvent {
1417                 [FieldOffset (0)]
1418                 public EpollEvents events;
1419                 [FieldOffset (4)]
1420                 public int fd;
1421                 [FieldOffset (4)]
1422                 public IntPtr ptr;
1423                 [FieldOffset (4)]
1424                 public uint u32;
1425                 [FieldOffset (4)]
1426                 public ulong u64;
1427         }
1428
1429         [Map ("struct linger")]
1430         [CLSCompliant (false)]
1431         public struct Linger {
1432                 public int l_onoff;
1433                 public int l_linger;
1434         }
1435
1436         [Map]
1437         [StructLayout (LayoutKind.Sequential)]
1438         [CLSCompliant (false)]
1439         public struct InAddr : IEquatable<InAddr> {
1440                 public uint s_addr;
1441
1442                 public unsafe InAddr (byte b0, byte b1, byte b2, byte b3)
1443                 {
1444                         s_addr = 0;
1445                         fixed (uint* ptr = &s_addr) {
1446                                 byte* bytePtr = (byte*) ptr;
1447                                 bytePtr[0] = b0;
1448                                 bytePtr[1] = b1;
1449                                 bytePtr[2] = b2;
1450                                 bytePtr[3] = b3;
1451                         }
1452                 }
1453
1454                 public unsafe InAddr (byte[] buffer)
1455                 {
1456                         if (buffer.Length != 4)
1457                                 throw new ArgumentException ("buffer.Length != 4", "buffer");
1458                         s_addr = 0;
1459                         fixed (uint* ptr = &s_addr)
1460                                 Marshal.Copy (buffer, 0, (IntPtr) ptr, 4);
1461                 }
1462
1463                 public unsafe void CopyFrom (byte[] source, int startIndex)
1464                 {
1465                         fixed (uint* ptr = &s_addr)
1466                                 Marshal.Copy (source, startIndex, (IntPtr) ptr, 4);
1467                 }
1468
1469                 public unsafe void CopyTo (byte[] destination, int startIndex)
1470                 {
1471                         fixed (uint* ptr = &s_addr)
1472                                 Marshal.Copy ((IntPtr) ptr, destination, startIndex, 4);
1473                 }
1474
1475                 public unsafe byte this[int index] {
1476                         get {
1477                                 if (index < 0 || index >= 4)
1478                                         throw new ArgumentOutOfRangeException ("index", "index < 0 || index >= 4");
1479                                 fixed (uint* ptr = &s_addr)
1480                                         return ((byte*) ptr)[index];
1481                         }
1482                         set {
1483                                 if (index < 0 || index >= 4)
1484                                         throw new ArgumentOutOfRangeException ("index", "index < 0 || index >= 4");
1485                                 fixed (uint* ptr = &s_addr)
1486                                         ((byte*) ptr)[index] = value;
1487                         }
1488                 }
1489
1490                 public override string ToString ()
1491                 {
1492                         return NativeConvert.ToIPAddress (this).ToString ();
1493                 }
1494
1495                 public override int GetHashCode ()
1496                 {
1497                         return s_addr.GetHashCode ();
1498                 }
1499                 public override bool Equals (object obj)
1500                 {
1501                         if (!(obj is InAddr))
1502                                 return false;
1503                         return Equals ((InAddr) obj);
1504                 }
1505                 public bool Equals (InAddr value)
1506                 {
1507                         return s_addr == value.s_addr;
1508                 }
1509         }
1510
1511         [Map]
1512         [StructLayout (LayoutKind.Sequential)]
1513         public struct In6Addr : IEquatable<In6Addr> {
1514                 ulong addr0;
1515                 ulong addr1;
1516
1517                 public unsafe In6Addr (byte[] buffer)
1518                 {
1519                         if (buffer.Length != 16)
1520                                 throw new ArgumentException ("buffer.Length != 16", "buffer");
1521                         addr0 = addr1 = 0;
1522                         fixed (ulong* ptr = &addr0)
1523                                 Marshal.Copy (buffer, 0, (IntPtr) ptr, 16);
1524                 }
1525
1526                 public unsafe void CopyFrom (byte[] source, int startIndex)
1527                 {
1528                         fixed (ulong* ptr = &addr0)
1529                                 Marshal.Copy (source, startIndex, (IntPtr) ptr, 16);
1530                 }
1531
1532                 public unsafe void CopyTo (byte[] destination, int startIndex)
1533                 {
1534                         fixed (ulong* ptr = &addr0)
1535                                 Marshal.Copy ((IntPtr) ptr, destination, startIndex, 16);
1536                 }
1537
1538                 public unsafe byte this[int index] {
1539                         get {
1540                                 if (index < 0 || index >= 16)
1541                                         throw new ArgumentOutOfRangeException ("index", "index < 0 || index >= 16");
1542                                 fixed (ulong* ptr = &addr0)
1543                                         return ((byte*) ptr)[index];
1544                         }
1545                         set {
1546                                 if (index < 0 || index >= 16)
1547                                         throw new ArgumentOutOfRangeException ("index", "index < 0 || index >= 16");
1548                                 fixed (ulong* ptr = &addr0)
1549                                         ((byte*) ptr)[index] = value;
1550                         }
1551                 }
1552
1553                 public override string ToString ()
1554                 {
1555                         return NativeConvert.ToIPAddress (this).ToString ();
1556                 }
1557
1558                 public override int GetHashCode ()
1559                 {
1560                         return addr0.GetHashCode () ^ addr1.GetHashCode ();
1561                 }
1562                 public override bool Equals (object obj)
1563                 {
1564                         if (!(obj is In6Addr))
1565                                 return false;
1566                         return Equals ((In6Addr) obj);
1567                 }
1568                 public bool Equals (In6Addr value)
1569                 {
1570                         return addr0 == value.addr0 && addr1 == value.addr1;
1571                 }
1572         }
1573
1574         #endregion
1575
1576         #region Classes
1577
1578         public sealed class Dirent
1579                 : IEquatable <Dirent>
1580         {
1581                 [CLSCompliant (false)]
1582                 public /* ino_t */ ulong  d_ino;
1583                 public /* off_t */ long   d_off;
1584                 [CLSCompliant (false)]
1585                 public ushort             d_reclen;
1586                 public byte               d_type;
1587                 public string             d_name;
1588
1589                 public override int GetHashCode ()
1590                 {
1591                         return d_ino.GetHashCode () ^ d_off.GetHashCode () ^ 
1592                                 d_reclen.GetHashCode () ^ d_type.GetHashCode () ^
1593                                 d_name.GetHashCode ();
1594                 }
1595
1596                 public override bool Equals (object obj)
1597                 {
1598                         if (obj == null || GetType() != obj.GetType())
1599                                 return false;
1600                         Dirent d = (Dirent) obj;
1601                         return Equals (d);
1602                 }
1603
1604                 public bool Equals (Dirent value)
1605                 {
1606                         if (value == null)
1607                                 return false;
1608                         return value.d_ino == d_ino && value.d_off == d_off &&
1609                                 value.d_reclen == d_reclen && value.d_type == d_type &&
1610                                 value.d_name == d_name;
1611                 }
1612
1613                 public override string ToString ()
1614                 {
1615                         return d_name;
1616                 }
1617
1618                 public static bool operator== (Dirent lhs, Dirent rhs)
1619                 {
1620                         return Object.Equals (lhs, rhs);
1621                 }
1622
1623                 public static bool operator!= (Dirent lhs, Dirent rhs)
1624                 {
1625                         return !Object.Equals (lhs, rhs);
1626                 }
1627         }
1628
1629         public sealed class Fstab
1630                 : IEquatable <Fstab>
1631         {
1632                 public string fs_spec;
1633                 public string fs_file;
1634                 public string fs_vfstype;
1635                 public string fs_mntops;
1636                 public string fs_type;
1637                 public int    fs_freq;
1638                 public int    fs_passno;
1639
1640                 public override int GetHashCode ()
1641                 {
1642                         return fs_spec.GetHashCode () ^ fs_file.GetHashCode () ^
1643                                 fs_vfstype.GetHashCode () ^ fs_mntops.GetHashCode () ^
1644                                 fs_type.GetHashCode () ^ fs_freq ^ fs_passno;
1645                 }
1646
1647                 public override bool Equals (object obj)
1648                 {
1649                         if (obj == null || GetType() != obj.GetType())
1650                                 return false;
1651                         Fstab f = (Fstab) obj;
1652                         return Equals (f);
1653                 }
1654
1655                 public bool Equals (Fstab value)
1656                 {
1657                         if (value == null)
1658                                 return false;
1659                         return value.fs_spec == fs_spec && value.fs_file == fs_file &&
1660                                 value.fs_vfstype == fs_vfstype && value.fs_mntops == fs_mntops &&
1661                                 value.fs_type == fs_type && value.fs_freq == fs_freq && 
1662                                 value.fs_passno == fs_passno;
1663                 }
1664
1665                 public override string ToString ()
1666                 {
1667                         return fs_spec;
1668                 }
1669
1670                 public static bool operator== (Fstab lhs, Fstab rhs)
1671                 {
1672                         return Object.Equals (lhs, rhs);
1673                 }
1674
1675                 public static bool operator!= (Fstab lhs, Fstab rhs)
1676                 {
1677                         return !Object.Equals (lhs, rhs);
1678                 }
1679         }
1680
1681         public sealed class Group
1682                 : IEquatable <Group>
1683         {
1684                 public string           gr_name;
1685                 public string           gr_passwd;
1686                 [CLSCompliant (false)]
1687                 public /* gid_t */ uint gr_gid;
1688                 public string[]         gr_mem;
1689
1690                 public override int GetHashCode ()
1691                 {
1692                         int memhc = 0;
1693                         for (int i = 0; i < gr_mem.Length; ++i)
1694                                 memhc ^= gr_mem[i].GetHashCode ();
1695
1696                         return gr_name.GetHashCode () ^ gr_passwd.GetHashCode () ^ 
1697                                 gr_gid.GetHashCode () ^ memhc;
1698                 }
1699
1700                 public override bool Equals (object obj)
1701                 {
1702                         if (obj == null || GetType() != obj.GetType())
1703                                 return false;
1704                         Group g = (Group) obj;
1705                         return Equals (g);
1706                 }
1707
1708                 public bool Equals (Group value)
1709                 {
1710                         if (value == null)
1711                                 return false;
1712                         if (value.gr_gid != gr_gid)
1713                                 return false;
1714                         if (value.gr_gid == gr_gid && value.gr_name == gr_name &&
1715                                 value.gr_passwd == gr_passwd) {
1716                                 if (value.gr_mem == gr_mem)
1717                                         return true;
1718                                 if (value.gr_mem == null || gr_mem == null)
1719                                         return false;
1720                                 if (value.gr_mem.Length != gr_mem.Length)
1721                                         return false;
1722                                 for (int i = 0; i < gr_mem.Length; ++i)
1723                                         if (gr_mem[i] != value.gr_mem[i])
1724                                                 return false;
1725                                 return true;
1726                         }
1727                         return false;
1728                 }
1729
1730                 // Generate string in /etc/group format
1731                 public override string ToString ()
1732                 {
1733                         StringBuilder sb = new StringBuilder ();
1734                         sb.Append (gr_name).Append (":").Append (gr_passwd).Append (":");
1735                         sb.Append (gr_gid).Append (":");
1736                         GetMembers (sb, gr_mem);
1737                         return sb.ToString ();
1738                 }
1739
1740                 private static void GetMembers (StringBuilder sb, string[] members)
1741                 {
1742                         if (members.Length > 0)
1743                                 sb.Append (members[0]);
1744                         for (int i = 1; i < members.Length; ++i) {
1745                                 sb.Append (",");
1746                                 sb.Append (members[i]);
1747                         }
1748                 }
1749
1750                 public static bool operator== (Group lhs, Group rhs)
1751                 {
1752                         return Object.Equals (lhs, rhs);
1753                 }
1754
1755                 public static bool operator!= (Group lhs, Group rhs)
1756                 {
1757                         return !Object.Equals (lhs, rhs);
1758                 }
1759         }
1760
1761         public sealed class Passwd
1762                 : IEquatable <Passwd>
1763         {
1764                 public string           pw_name;
1765                 public string           pw_passwd;
1766                 [CLSCompliant (false)]
1767                 public /* uid_t */ uint pw_uid;
1768                 [CLSCompliant (false)]
1769                 public /* gid_t */ uint pw_gid;
1770                 public string           pw_gecos;
1771                 public string           pw_dir;
1772                 public string           pw_shell;
1773
1774                 public override int GetHashCode ()
1775                 {
1776                         return pw_name.GetHashCode () ^ pw_passwd.GetHashCode () ^ 
1777                                 pw_uid.GetHashCode () ^ pw_gid.GetHashCode () ^
1778                                 pw_gecos.GetHashCode () ^ pw_dir.GetHashCode () ^
1779                                 pw_dir.GetHashCode () ^ pw_shell.GetHashCode ();
1780                 }
1781
1782                 public override bool Equals (object obj)
1783                 {
1784                         if (obj == null || GetType() != obj.GetType())
1785                                 return false;
1786                         Passwd p = (Passwd) obj;
1787                         return Equals (p);
1788                 }
1789
1790                 public bool Equals (Passwd value)
1791                 {
1792                         if (value == null)
1793                                 return false;
1794                         return value.pw_uid == pw_uid && value.pw_gid == pw_gid && 
1795                                 value.pw_name == pw_name && value.pw_passwd == pw_passwd && 
1796                                 value.pw_gecos == pw_gecos && value.pw_dir == pw_dir && 
1797                                 value.pw_shell == pw_shell;
1798                 }
1799
1800                 // Generate string in /etc/passwd format
1801                 public override string ToString ()
1802                 {
1803                         return string.Format ("{0}:{1}:{2}:{3}:{4}:{5}:{6}",
1804                                 pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell);
1805                 }
1806
1807                 public static bool operator== (Passwd lhs, Passwd rhs)
1808                 {
1809                         return Object.Equals (lhs, rhs);
1810                 }
1811
1812                 public static bool operator!= (Passwd lhs, Passwd rhs)
1813                 {
1814                         return !Object.Equals (lhs, rhs);
1815                 }
1816         }
1817
1818         public sealed class Utsname
1819                 : IEquatable <Utsname>
1820         {
1821                 public string sysname;
1822                 public string nodename;
1823                 public string release;
1824                 public string version;
1825                 public string machine;
1826                 public string domainname;
1827
1828                 public override int GetHashCode ()
1829                 {
1830                         return sysname.GetHashCode () ^ nodename.GetHashCode () ^ 
1831                                 release.GetHashCode () ^ version.GetHashCode () ^
1832                                 machine.GetHashCode () ^ domainname.GetHashCode ();
1833                 }
1834
1835                 public override bool Equals (object obj)
1836                 {
1837                         if (obj == null || GetType() != obj.GetType())
1838                                 return false;
1839                         Utsname u = (Utsname) obj;
1840                         return Equals (u);
1841                 }
1842
1843                 public bool Equals (Utsname value)
1844                 {
1845                         return value.sysname == sysname && value.nodename == nodename && 
1846                                 value.release == release && value.version == version && 
1847                                 value.machine == machine && value.domainname == domainname;
1848                 }
1849
1850                 // Generate string in /etc/passwd format
1851                 public override string ToString ()
1852                 {
1853                         return string.Format ("{0} {1} {2} {3} {4}",
1854                                 sysname, nodename, release, version, machine);
1855                 }
1856
1857                 public static bool operator== (Utsname lhs, Utsname rhs)
1858                 {
1859                         return Object.Equals (lhs, rhs);
1860                 }
1861
1862                 public static bool operator!= (Utsname lhs, Utsname rhs)
1863                 {
1864                         return !Object.Equals (lhs, rhs);
1865                 }
1866         }
1867
1868         // This struct is used by the native code.
1869         // Its layout must be the same as the start of the Sockaddr class and the start of the _SockaddrDynamic struct
1870         [Map]
1871         [StructLayout (LayoutKind.Sequential)]
1872         internal struct _SockaddrHeader {
1873                 internal SockaddrType type;
1874                 internal UnixAddressFamily sa_family;
1875         }
1876
1877         // Base class for all Sockaddr types.
1878         // This class is not abstract, instances of this class can be used to determine the sa_family value.
1879         // This class and all classes which are deriving from it and are passed to the native code have to be blittable.
1880         [CLSCompliant (false)]
1881         [StructLayout (LayoutKind.Sequential)]
1882         public class Sockaddr {
1883                 // Note: the layout of the first members must match the layout of struct _SockaddrHeader
1884                 // 'type' must be the first field of the class as it is used to find the address of the class itself
1885                 internal SockaddrType type;
1886                 internal UnixAddressFamily _sa_family;
1887
1888                 public UnixAddressFamily sa_family {
1889                         get { return _sa_family; }
1890                         set { _sa_family = value; }
1891                 }
1892
1893                 public Sockaddr ()
1894                 {
1895                         this.type = SockaddrType.Sockaddr;
1896                         this.sa_family = UnixAddressFamily.AF_UNSPEC;
1897                 }
1898
1899                 internal Sockaddr (SockaddrType type, UnixAddressFamily sa_family)
1900                 {
1901                         this.type = type;
1902                         this.sa_family = sa_family;
1903                 }
1904
1905                 [DllImport (Syscall.MPH, SetLastError=true, 
1906                                 EntryPoint="Mono_Posix_Sockaddr_GetNativeSize")]
1907                 static extern unsafe int GetNativeSize (_SockaddrHeader* address, out long size);
1908
1909                 internal unsafe long GetNativeSize ()
1910                 {
1911                         long size;
1912                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (this).type)
1913                         fixed (byte* data = Sockaddr.GetDynamicData (this)) {
1914                                 var dyn = new _SockaddrDynamic (this, data, useMaxLength: false);
1915                                 if (GetNativeSize (Sockaddr.GetNative (&dyn, addr), out size) != 0)
1916                                                 throw new ArgumentException ("Failed to get size of native struct", "this");
1917                         }
1918                         return size;
1919                 }
1920
1921
1922                 // In order to create a wrapper for a syscall which accepts a "struct sockaddr" argument but does not modify it, use:
1923
1924                 // fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
1925                 // fixed (byte* data = Sockaddr.GetDynamicData (address)) {
1926                 //     var dyn = new _SockaddrDynamic (address, data, useMaxLength: false);
1927                 //     return sys_syscall (..., Sockaddr.GetNative (&dyn, addr));
1928                 // }
1929
1930                 // For syscalls which modify the argument, use:
1931
1932                 // fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
1933                 // fixed (byte* data = Sockaddr.GetDynamicData (address)) {
1934                 //     var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
1935                 //     rettype r = sys_syscall (..., Sockaddr.GetNative (&dyn, addr));
1936                 //     dyn.Update (address);
1937                 //     return r;
1938                 // }
1939
1940                 // This sequence will handle
1941                 // - normal Sockaddrs like SockaddrIn and SockaddrIn6 which will be passed directly,
1942                 // - sockaddrs like SockaddrUn and SockaddrStorage which need a wrapper and
1943                 // - null (which will be passed as null)
1944                 // without any heap memory allocations.
1945
1946
1947                 // This is a fake Sockaddr which is passed to the fixed() statement if the address was null.
1948                 // Sockaddr.GetNative() will return a null pointer for this Sockaddr.
1949                 static Sockaddr nullSockaddr = new Sockaddr ();
1950
1951                 internal static Sockaddr GetAddress (Sockaddr address)
1952                 {
1953                         if (address == null)
1954                                 return nullSockaddr;
1955                         else
1956                                 return address;
1957                 }
1958
1959                 internal static unsafe _SockaddrHeader* GetNative (_SockaddrDynamic* dyn, SockaddrType* addr)
1960                 {
1961                         if (dyn->data != null) {
1962                                 return (_SockaddrHeader*) dyn;
1963                         } else {
1964                                 fixed (SockaddrType* nullType = &nullSockaddr.type)
1965                                         if (addr == nullType)
1966                                                 return null;
1967                                 return (_SockaddrHeader*) addr;
1968                         }
1969                 }
1970
1971                 // Return an array containing the dynamic data (for SockaddrStorage and SockaddrUn) or null
1972                 internal static byte[] GetDynamicData (Sockaddr addr)
1973                 {
1974                         if (addr == null)
1975                                 return null;
1976                         return addr.DynamicData ();
1977                 }
1978
1979                 // This methods is overwritten in SockaddrStorage and SockaddrUn
1980                 internal virtual byte[] DynamicData ()
1981                 {
1982                         return null;
1983                 }
1984
1985                 // This methods should only be called for SockaddrStorage and SockaddrUn where they are overwritten
1986                 internal virtual long GetDynamicLength ()
1987                 {
1988                         throw new NotImplementedException ();
1989                 }
1990
1991                 internal virtual void SetDynamicLength (long value)
1992                 {
1993                         throw new NotImplementedException ();
1994                 }
1995
1996                 public SockaddrStorage ToSockaddrStorage ()
1997                 {
1998                         var storage = new SockaddrStorage ((int) GetNativeSize ());
1999                         storage.SetTo (this);
2000                         return storage;
2001                 }
2002
2003                 public static Sockaddr FromSockaddrStorage (SockaddrStorage storage)
2004                 {
2005                         var ret = new Sockaddr ();
2006                         storage.CopyTo (ret);
2007                         return ret;
2008                 }
2009         }
2010
2011         // This struct is required to manually marshal Sockaddr* classes which include an array (currently SockaddrStorage and SockaddrUn).
2012         // This is needed because the marshalling code will not work if the classes derived from Sockaddr aren't blittable.
2013         [Map]
2014         unsafe struct _SockaddrDynamic {
2015                 // Note: the layout of the first members must match the layout of struct _SockaddrHeader
2016                 public SockaddrType type;
2017                 public UnixAddressFamily sa_family;
2018                 public byte* data;
2019                 public long len;
2020
2021                 public _SockaddrDynamic (Sockaddr address, byte* data, bool useMaxLength)
2022                 {
2023                         if (data == null) {
2024                                 // When data is null, no wrapper is needed.
2025                                 // Initialize everything to zero, Sockaddr.GetNative() will then
2026                                 // use the Sockaddr structure directly.
2027                                 this = new _SockaddrDynamic ();
2028                                 return;
2029                         }
2030
2031                         var dynData = address.DynamicData ();
2032
2033                         type = address.type & ~SockaddrType.MustBeWrapped;
2034                         sa_family = address.sa_family;
2035                         this.data = data;
2036                         if (useMaxLength) {
2037                                 len = dynData.Length;
2038                         } else {
2039                                 len = address.GetDynamicLength ();
2040                                 if (len < 0 || len > dynData.Length)
2041                                         throw new ArgumentException ("len < 0 || len > dynData.Length", "address");
2042                         }
2043                 }
2044
2045                 public void Update (Sockaddr address)
2046                 {
2047                         // When data is null, no wrapper was needed.
2048                         if (data == null)
2049                                 return;
2050
2051                         address.sa_family = sa_family;
2052                         address.SetDynamicLength (len);
2053                 }
2054         };
2055
2056         // This is a class which can store arbitrary sockaddrs, even if they are not known the the Mono.Unix wrapper or the family does not have a corresponding value in the UnixAddressFamily enumeration.
2057         [CLSCompliant (false)]
2058         public sealed class SockaddrStorage : Sockaddr, IEquatable<SockaddrStorage> {
2059                 // Note: The sa_family field is ignored when passing a SockaddrStorage to a syscall (but it will be set when a SockaddrStorage is returned from a syscall). Instead of the sa_family field, the value embedded in data is used.
2060                 public byte[] data { get; set; }
2061                 public long data_len { get; set; }
2062
2063                 internal override byte[] DynamicData ()
2064                 {
2065                         return data;
2066                 }
2067
2068                 internal override long GetDynamicLength ()
2069                 {
2070                         return data_len;
2071                 }
2072
2073                 internal override void SetDynamicLength (long value)
2074                 {
2075                         data_len = value;
2076                 }
2077
2078                 [DllImport (Syscall.MPH, SetLastError=true,
2079                                 EntryPoint="Mono_Posix_SockaddrStorage_get_size")]
2080                 static extern int get_size ();
2081                 static readonly int default_size = get_size ();
2082
2083                 public SockaddrStorage ()
2084                         : base (SockaddrType.SockaddrStorage | SockaddrType.MustBeWrapped, UnixAddressFamily.AF_UNSPEC)
2085                 {
2086                         data = new byte[default_size];
2087                         data_len = 0;
2088                 }
2089
2090                 public SockaddrStorage (int size)
2091                         : base (SockaddrType.SockaddrStorage | SockaddrType.MustBeWrapped, UnixAddressFamily.AF_UNSPEC)
2092                 {
2093                         data = new byte[size];
2094                         data_len = 0;
2095                 }
2096
2097                 public unsafe void SetTo (Sockaddr address)
2098                 {
2099                         if (address == null)
2100                                 throw new ArgumentNullException ("address");
2101
2102                         var size = address.GetNativeSize ();
2103                         if (size > data.Length)
2104                                 data = new byte[size];
2105                         fixed (byte* ptr = data)
2106                                 if (!NativeConvert.TryCopy (address, (IntPtr) ptr))
2107                                         throw new ArgumentException ("Failed to convert to native struct", "address");
2108                         data_len = size;
2109                         sa_family = address.sa_family;
2110                 }
2111
2112                 public unsafe void CopyTo (Sockaddr address)
2113                 {
2114                         if (address == null)
2115                                 throw new ArgumentNullException ("address");
2116                         if (data_len < 0 || data_len > data.Length)
2117                                 throw new ArgumentException ("data_len < 0 || data_len > data.Length", "this");
2118
2119                         fixed (byte* ptr = data)
2120                                 if (!NativeConvert.TryCopy ((IntPtr) ptr, data_len, address))
2121                                         throw new ArgumentException ("Failed to convert from native struct", "this");
2122                 }
2123
2124                 public override string ToString ()
2125                 {
2126                         var sb = new StringBuilder ();
2127                         sb.AppendFormat ("{{sa_family={0}, data_len={1}, data=(", sa_family, data_len);
2128                         for (int i = 0; i < data_len; i++) {
2129                                 if (i != 0)
2130                                         sb.Append (" ");
2131                                 sb.Append (data[i].ToString ("x2"));
2132                         }
2133                         sb.Append (")");
2134                         return sb.ToString ();
2135                 }
2136
2137                 public override int GetHashCode ()
2138                 {
2139                         unchecked {
2140                                 int hash = 0x1234;
2141                                 for (int i = 0; i < data_len; i++)
2142                                         hash += i ^ data[i];
2143                                 return hash;
2144                         }
2145                 }
2146
2147                 public override bool Equals (object obj)
2148                 {
2149                         if (!(obj is SockaddrStorage))
2150                                 return false;
2151                         return Equals ((SockaddrStorage) obj);
2152                 }
2153
2154                 public bool Equals (SockaddrStorage value)
2155                 {
2156                         if (value == null)
2157                                 return false;
2158                         if (data_len != value.data_len)
2159                                 return false;
2160                         for (int i = 0; i < data_len; i++)
2161                                 if (data[i] != value.data[i])
2162                                         return false;
2163                         return true;
2164                 }
2165         }
2166
2167         [CLSCompliant (false)]
2168         public sealed class SockaddrUn : Sockaddr, IEquatable<SockaddrUn> {
2169                 public UnixAddressFamily sun_family { // AF_UNIX
2170                         get { return sa_family; }
2171                         set { sa_family = value; }
2172                 }
2173                 public byte[] sun_path { get; set; }
2174                 public long sun_path_len { get; set; } // Indicates how many bytes of sun_path are valid. Must not be larger than sun_path.Length.
2175
2176                 internal override byte[] DynamicData ()
2177                 {
2178                         return sun_path;
2179                 }
2180
2181                 internal override long GetDynamicLength ()
2182                 {
2183                         return sun_path_len;
2184                 }
2185
2186                 internal override void SetDynamicLength (long value)
2187                 {
2188                         sun_path_len = value;
2189                 }
2190
2191                 [DllImport (Syscall.MPH, SetLastError=true,
2192                                 EntryPoint="Mono_Posix_SockaddrUn_get_sizeof_sun_path")]
2193                 static extern int get_sizeof_sun_path ();
2194                 static readonly int sizeof_sun_path = get_sizeof_sun_path ();
2195
2196                 public SockaddrUn ()
2197                         : base (SockaddrType.SockaddrUn | SockaddrType.MustBeWrapped, UnixAddressFamily.AF_UNIX)
2198                 {
2199                         sun_path = new byte[sizeof_sun_path];
2200                         sun_path_len = 0;
2201                 }
2202
2203                 public SockaddrUn (int size)
2204                         : base (SockaddrType.SockaddrUn | SockaddrType.MustBeWrapped, UnixAddressFamily.AF_UNIX)
2205                 {
2206                         sun_path = new byte[size];
2207                         sun_path_len = 0;
2208                 }
2209
2210                 public SockaddrUn (string path, bool linuxAbstractNamespace = false)
2211                         : base (SockaddrType.SockaddrUn | SockaddrType.MustBeWrapped, UnixAddressFamily.AF_UNIX)
2212                 {
2213                         if (path == null)
2214                                 throw new ArgumentNullException ("path");
2215                         var bytes = UnixEncoding.Instance.GetBytes (path);
2216                         if (linuxAbstractNamespace) {
2217                                 sun_path = new byte[1 + bytes.Length];
2218                                 Array.Copy (bytes, 0, sun_path, 1, bytes.Length);
2219                         } else {
2220                                 sun_path = bytes;
2221                         }
2222                         sun_path_len = sun_path.Length;
2223                 }
2224
2225                 public bool IsLinuxAbstractNamespace {
2226                         get {
2227                                 return sun_path_len > 0 && sun_path[0] == 0;
2228                         }
2229                 }
2230
2231                 public string Path {
2232                         get {
2233                                 var offset = IsLinuxAbstractNamespace ? 1 : 0;
2234                                 // Remove data after null terminator
2235                                 int length;
2236                                 for (length = 0; offset + length < sun_path_len; length++)
2237                                         if (sun_path[offset + length] == 0)
2238                                                 break;
2239                                 return UnixEncoding.Instance.GetString (sun_path, offset, length);
2240                         }
2241                 }
2242
2243                 public override string ToString ()
2244                 {
2245                         return string.Format ("{{sa_family={0}, sun_path=\"{1}{2}\"}}", sa_family, IsLinuxAbstractNamespace ? "\\0" : "", Path);
2246                 }
2247
2248                 public static new SockaddrUn FromSockaddrStorage (SockaddrStorage storage)
2249                 {
2250                         // This will make the SockaddrUn larger than it needs to be (because
2251                         // storage.data_len includes the sun_family field), but it will be
2252                         // large enough.
2253                         var ret = new SockaddrUn ((int) storage.data_len);
2254                         storage.CopyTo (ret);
2255                         return ret;
2256                 }
2257
2258                 public override int GetHashCode ()
2259                 {
2260                         return sun_family.GetHashCode () ^ IsLinuxAbstractNamespace.GetHashCode () ^ Path.GetHashCode ();
2261                 }
2262
2263                 public override bool Equals (object obj)
2264                 {
2265                         if (!(obj is SockaddrUn))
2266                                 return false;
2267                         return Equals ((SockaddrUn) obj);
2268                 }
2269
2270                 public bool Equals (SockaddrUn value)
2271                 {
2272                         if (value == null)
2273                                 return false;
2274                         return sun_family == value.sun_family
2275                                 && IsLinuxAbstractNamespace == value.IsLinuxAbstractNamespace
2276                                 && Path == value.Path;
2277                 }
2278         }
2279
2280         [Map ("struct sockaddr_in")]
2281         [CLSCompliant (false)]
2282         [StructLayout (LayoutKind.Sequential)]
2283         public sealed class SockaddrIn : Sockaddr, IEquatable<SockaddrIn> {
2284                 public UnixAddressFamily sin_family { // AF_INET
2285                         get { return sa_family; }
2286                         set { sa_family = value; }
2287                 }
2288                 public ushort sin_port;   // Port number.
2289                 public InAddr sin_addr;   // IP address.
2290
2291                 public SockaddrIn ()
2292                         : base (SockaddrType.SockaddrIn, UnixAddressFamily.AF_INET)
2293                 {
2294                 }
2295
2296                 public override string ToString ()
2297                 {
2298                         return string.Format ("{{sin_family={0}, sin_port=htons({1}), sin_addr={2}}}", sa_family, Syscall.ntohs(sin_port), sin_addr);
2299                 }
2300
2301                 public static new SockaddrIn FromSockaddrStorage (SockaddrStorage storage)
2302                 {
2303                         var ret = new SockaddrIn ();
2304                         storage.CopyTo (ret);
2305                         return ret;
2306                 }
2307
2308                 public override int GetHashCode ()
2309                 {
2310                         return sin_family.GetHashCode () ^ sin_port.GetHashCode () ^ sin_addr.GetHashCode ();
2311                 }
2312
2313                 public override bool Equals (object obj)
2314                 {
2315                         if (!(obj is SockaddrIn))
2316                                 return false;
2317                         return Equals ((SockaddrIn) obj);
2318                 }
2319
2320                 public bool Equals (SockaddrIn value)
2321                 {
2322                         if (value == null)
2323                                 return false;
2324                         return sin_family == value.sin_family
2325                                 && sin_port == value.sin_port
2326                                 && sin_addr.Equals (value.sin_addr);
2327                 }
2328         }
2329
2330         [Map ("struct sockaddr_in6")]
2331         [CLSCompliant (false)]
2332         [StructLayout (LayoutKind.Sequential)]
2333         public sealed class SockaddrIn6 : Sockaddr, IEquatable<SockaddrIn6> {
2334                 public UnixAddressFamily sin6_family { // AF_INET6
2335                         get { return sa_family; }
2336                         set { sa_family = value; }
2337                 }
2338                 public ushort  sin6_port;     // Port number.
2339                 public uint    sin6_flowinfo; // IPv6 traffic class and flow information.
2340                 public In6Addr sin6_addr;     // IPv6 address.
2341                 public uint    sin6_scope_id; // Set of interfaces for a scope.
2342
2343                 public SockaddrIn6 ()
2344                         : base (SockaddrType.SockaddrIn6, UnixAddressFamily.AF_INET6)
2345                 {
2346                 }
2347
2348                 public override string ToString ()
2349                 {
2350                         return string.Format ("{{sin6_family={0}, sin6_port=htons({1}), sin6_flowinfo={2}, sin6_addr={3}, sin6_scope_id={4}}}", sa_family, Syscall.ntohs (sin6_port), sin6_flowinfo, sin6_addr, sin6_scope_id);
2351                 }
2352
2353                 public static new SockaddrIn6 FromSockaddrStorage (SockaddrStorage storage)
2354                 {
2355                         var ret = new SockaddrIn6 ();
2356                         storage.CopyTo (ret);
2357                         return ret;
2358                 }
2359
2360                 public override int GetHashCode ()
2361                 {
2362                         return sin6_family.GetHashCode () ^ sin6_port.GetHashCode () ^ sin6_flowinfo.GetHashCode () ^ sin6_addr.GetHashCode () ^ sin6_scope_id.GetHashCode ();
2363                 }
2364
2365                 public override bool Equals (object obj)
2366                 {
2367                         if (!(obj is SockaddrIn6))
2368                                 return false;
2369                         return Equals ((SockaddrIn6) obj);
2370                 }
2371
2372                 public bool Equals (SockaddrIn6 value)
2373                 {
2374                         if (value == null)
2375                                 return false;
2376                         return sin6_family == value.sin6_family
2377                                 && sin6_port == value.sin6_port
2378                                 && sin6_flowinfo == value.sin6_flowinfo
2379                                 && sin6_addr.Equals (value.sin6_addr)
2380                                 && sin6_scope_id == value.sin6_scope_id;
2381                 }
2382         }
2383
2384         //
2385         // Convention: Functions *not* part of the standard C library AND part of
2386         // a POSIX and/or Unix standard (X/Open, SUS, XPG, etc.) go here.
2387         //
2388         // For example, the man page should be similar to:
2389         //
2390         //    CONFORMING TO (or CONFORMS TO)
2391         //           XPG2, SUSv2, POSIX, etc.
2392         //
2393         // BSD- and GNU-specific exports can also be placed here.
2394         //
2395         // Non-POSIX/XPG/etc. functions can also be placed here if:
2396         //  (a) They'd be likely to be covered in a Steven's-like book
2397         //  (b) The functions would be present in libc.so (or equivalent).
2398         //
2399         // If a function has its own library, that's a STRONG indicator that the
2400         // function should get a different binding, probably in its own assembly, 
2401         // so that package management can work sanely.  (That is, we'd like to avoid
2402         // scenarios where FooLib.dll is installed, but it requires libFooLib.so to
2403         // run, and libFooLib.so doesn't exist.  That would be confusing.)
2404         //
2405         // The only methods in here should be:
2406         //  (1) low-level functions
2407         //  (2) "Trivial" function overloads.  For example, if the parameters to a
2408         //      function are related (e.g. getgroups(2))
2409         //  (3) The return type SHOULD NOT be changed.  If you want to provide a
2410         //      convenience function with a nicer return type, place it into one of
2411         //      the Mono.Unix.Unix* wrapper classes, and give it a .NET-styled name.
2412         //      - EXCEPTION: No public functions should have a `void' return type.
2413         //        `void' return types should be replaced with `int'.
2414         //        Rationality: `void'-return functions typically require a
2415         //        complicated call sequence, such as clear errno, then call, then
2416         //        check errno to see if any errors occurred.  This sequence can't 
2417         //        be done safely in managed code, as errno may change as part of 
2418         //        the P/Invoke mechanism.
2419         //        Instead, add a MonoPosixHelper export which does:
2420         //          errno = 0;
2421         //          INVOKE SYSCALL;
2422         //          return errno == 0 ? 0 : -1;
2423         //        This lets managed code check the return value in the usual manner.
2424         //  (4) Exceptions SHOULD NOT be thrown.  EXCEPTIONS: 
2425         //      - If you're wrapping *broken* methods which make assumptions about 
2426         //        input data, such as that an argument refers to N bytes of data.  
2427         //        This is currently limited to cuserid(3) and encrypt(3).
2428         //      - If you call functions which themselves generate exceptions.  
2429         //        This is the case for using NativeConvert, which will throw an
2430         //        exception if an invalid/unsupported value is used.
2431         //
2432         // Naming Conventions:
2433         //  - Syscall method names should have the same name as the function being
2434         //    wrapped (e.g. Syscall.read ==> read(2)).  This allows people to
2435         //    consult the appropriate man page if necessary.
2436         //  - Methods need not have the same arguments IF this simplifies or
2437         //    permits correct usage.  The current example is syslog, in which
2438         //    syslog(3)'s single `priority' argument is split into SyslogFacility
2439         //    and SyslogLevel arguments.
2440         //  - Type names (structures, classes, enumerations) are always PascalCased.
2441         //  - Enumerations are named as <MethodName><ArgumentName>, and are located
2442         //    in the Mono.Unix.Native namespace.  For readability, if ArgumentName 
2443         //    is "cmd", use Command instead.  For example, fcntl(2) takes a
2444         //    FcntlCommand argument.  This naming convention is to provide an
2445         //    assocation between an enumeration and where it should be used, and
2446         //    allows a single method to accept multiple different enumerations 
2447         //    (see mmap(2), which takes MmapProts and MmapFlags).
2448         //    - EXCEPTION: if an enumeration is shared between multiple different
2449         //      methods, AND/OR the "obvious" enumeration name conflicts with an
2450         //      existing .NET type, a more appropriate name should be used.
2451         //      Example: FilePermissions
2452         //    - EXCEPTION: [Flags] enumerations should get plural names to follow
2453         //      .NET name guidelines.  Usually this doesn't result in a change
2454         //      (OpenFlags is the `flags' parameter for open(2)), but it can
2455         //      (mmap(2) prot ==> MmapProts, access(2) mode ==> AccessModes).
2456         //  - Enumerations should have the [Map] and (optional) [Flags] attributes.
2457         //    [Map] is required for make-map to find the type and generate the
2458         //    appropriate NativeConvert conversion functions.
2459         //  - Enumeration contents should match the original Unix names.  This helps
2460         //    with documentation (the existing man pages are still useful), and is
2461         //    required for use with the make-map generation program.
2462         //  - Structure names should be the PascalCased version of the actual
2463         //    structure name (struct flock ==> Flock).  Structure members should
2464         //    have the same names, or a (reasonably) portable subset (Dirent being
2465         //    the poster child for questionable members).
2466         //    - Whether the managed type should be a reference type (class) or a 
2467         //      value type (struct) should be determined on a case-by-case basis: 
2468         //      if you ever need to be able to use NULL for it (such as with Dirent, 
2469         //      Group, Passwd, as these are method return types and `null' is used 
2470         //      to signify the end), it should be a reference type; otherwise, use 
2471         //      your discretion, and keep any expected usage patterns in mind.
2472         //  - Syscall should be a Single Point Of Truth (SPOT).  There should be
2473         //    only ONE way to do anything.  By convention, the Linux function names
2474         //    are used, but that need not always be the case (use your discretion).
2475         //    It SHOULD NOT be required that developers know what platform they're
2476         //    on, and choose among a set of similar functions.  In short, anything
2477         //    that requires a platform check is BAD -- Mono.Unix is a wrapper, and
2478         //    we can afford to clean things up whenever possible.
2479         //    - Examples: 
2480         //      - Syscall.statfs: Solaris/Mac OS X provide statfs(2), Linux provides
2481         //        statvfs(2).  MonoPosixHelper will "thunk" between the two,
2482         //        exporting a statvfs that works across platforms.
2483         //      - Syscall.getfsent: Glibc export which Solaris lacks, while Solaris
2484         //        instead provides getvfsent(3).  MonoPosixHelper provides wrappers
2485         //        to convert getvfsent(3) into Fstab data.
2486         //    - Exception: If it isn't possible to cleanly wrap platforms, then the
2487         //      method shouldn't be exported.  The user will be expected to do their
2488         //      own platform check and their own DllImports.
2489         //      Examples: mount(2), umount(2), etc.
2490         //    - Note: if a platform doesn't support a function AT ALL, the
2491         //      MonoPosixHelper wrapper won't be compiled, resulting in a
2492         //      EntryPointNotFoundException.  This is also consistent with a missing 
2493         //      P/Invoke into libc.so.
2494         //
2495         [CLSCompliant (false)]
2496         public sealed class Syscall : Stdlib
2497         {
2498                 new internal const string LIBC  = "libc";
2499
2500                 private Syscall () {}
2501
2502                 //
2503                 // <aio.h>
2504                 //
2505
2506                 // TODO: aio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), 
2507                 // aio_return(3), aio_suspend(3), aio_write(3)
2508                 //
2509                 // Then update UnixStream.BeginRead to use the aio* functions.
2510
2511
2512                 #region <attr/xattr.h> Declarations
2513                 //
2514                 // <attr/xattr.h> -- COMPLETE
2515                 //
2516
2517                 // setxattr(2)
2518                 //    int setxattr (const char *path, const char *name,
2519                 //        const void *value, size_t size, int flags);
2520                 [DllImport (MPH, SetLastError=true,
2521                                 EntryPoint="Mono_Posix_Syscall_setxattr")]
2522                 public static extern int setxattr (
2523                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2524                                 string path, 
2525                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2526                                 string name, byte[] value, ulong size, XattrFlags flags);
2527
2528                 public static int setxattr (string path, string name, byte [] value, ulong size)
2529                 {
2530                         return setxattr (path, name, value, size, XattrFlags.XATTR_AUTO);
2531                 }
2532
2533                 public static int setxattr (string path, string name, byte [] value, XattrFlags flags)
2534                 {
2535                         return setxattr (path, name, value, (ulong) value.Length, flags);
2536                 }
2537
2538                 public static int setxattr (string path, string name, byte [] value)
2539                 {
2540                         return setxattr (path, name, value, (ulong) value.Length);
2541                 }
2542
2543                 // lsetxattr(2)
2544                 //        int lsetxattr (const char *path, const char *name,
2545                 //                   const void *value, size_t size, int flags);
2546                 [DllImport (MPH, SetLastError=true,
2547                                 EntryPoint="Mono_Posix_Syscall_lsetxattr")]
2548                 public static extern int lsetxattr (
2549                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2550                                 string path, 
2551                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2552                                 string name, byte[] value, ulong size, XattrFlags flags);
2553
2554                 public static int lsetxattr (string path, string name, byte [] value, ulong size)
2555                 {
2556                         return lsetxattr (path, name, value, size, XattrFlags.XATTR_AUTO);
2557                 }
2558
2559                 public static int lsetxattr (string path, string name, byte [] value, XattrFlags flags)
2560                 {
2561                         return lsetxattr (path, name, value, (ulong) value.Length, flags);
2562                 }
2563
2564                 public static int lsetxattr (string path, string name, byte [] value)
2565                 {
2566                         return lsetxattr (path, name, value, (ulong) value.Length);
2567                 }
2568
2569                 // fsetxattr(2)
2570                 //        int fsetxattr (int fd, const char *name,
2571                 //                   const void *value, size_t size, int flags);
2572                 [DllImport (MPH, SetLastError=true,
2573                                 EntryPoint="Mono_Posix_Syscall_fsetxattr")]
2574                 public static extern int fsetxattr (int fd, 
2575                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2576                                 string name, byte[] value, ulong size, XattrFlags flags);
2577
2578                 public static int fsetxattr (int fd, string name, byte [] value, ulong size)
2579                 {
2580                         return fsetxattr (fd, name, value, size, XattrFlags.XATTR_AUTO);
2581                 }
2582
2583                 public static int fsetxattr (int fd, string name, byte [] value, XattrFlags flags)
2584                 {
2585                         return fsetxattr (fd, name, value, (ulong) value.Length, flags);
2586                 }
2587
2588                 public static int fsetxattr (int fd, string name, byte [] value)
2589                 {
2590                         return fsetxattr (fd, name, value, (ulong) value.Length);
2591                 }
2592
2593                 // getxattr(2)
2594                 //        ssize_t getxattr (const char *path, const char *name,
2595                 //                      void *value, size_t size);
2596                 [DllImport (MPH, SetLastError=true,
2597                                 EntryPoint="Mono_Posix_Syscall_getxattr")]
2598                 public static extern long getxattr (
2599                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2600                                 string path, 
2601                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2602                                 string name, byte[] value, ulong size);
2603
2604                 public static long getxattr (string path, string name, byte [] value)
2605                 {
2606                         return getxattr (path, name, value, (ulong) value.Length);
2607                 }
2608
2609                 public static long getxattr (string path, string name, out byte [] value)
2610                 {
2611                         value = null;
2612                         long size = getxattr (path, name, value, 0);
2613                         if (size <= 0)
2614                                 return size;
2615
2616                         value = new byte [size];
2617                         return getxattr (path, name, value, (ulong) size);
2618                 }
2619
2620                 // lgetxattr(2)
2621                 //        ssize_t lgetxattr (const char *path, const char *name,
2622                 //                       void *value, size_t size);
2623                 [DllImport (MPH, SetLastError=true,
2624                                 EntryPoint="Mono_Posix_Syscall_lgetxattr")]
2625                 public static extern long lgetxattr (
2626                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2627                                 string path, 
2628                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2629                                 string name, byte[] value, ulong size);
2630
2631                 public static long lgetxattr (string path, string name, byte [] value)
2632                 {
2633                         return lgetxattr (path, name, value, (ulong) value.Length);
2634                 }
2635
2636                 public static long lgetxattr (string path, string name, out byte [] value)
2637                 {
2638                         value = null;
2639                         long size = lgetxattr (path, name, value, 0);
2640                         if (size <= 0)
2641                                 return size;
2642
2643                         value = new byte [size];
2644                         return lgetxattr (path, name, value, (ulong) size);
2645                 }
2646
2647                 // fgetxattr(2)
2648                 //        ssize_t fgetxattr (int fd, const char *name, void *value, size_t size);
2649                 [DllImport (MPH, SetLastError=true,
2650                                 EntryPoint="Mono_Posix_Syscall_fgetxattr")]
2651                 public static extern long fgetxattr (int fd, 
2652                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2653                                 string name, byte[] value, ulong size);
2654
2655                 public static long fgetxattr (int fd, string name, byte [] value)
2656                 {
2657                         return fgetxattr (fd, name, value, (ulong) value.Length);
2658                 }
2659
2660                 public static long fgetxattr (int fd, string name, out byte [] value)
2661                 {
2662                         value = null;
2663                         long size = fgetxattr (fd, name, value, 0);
2664                         if (size <= 0)
2665                                 return size;
2666
2667                         value = new byte [size];
2668                         return fgetxattr (fd, name, value, (ulong) size);
2669                 }
2670
2671                 // listxattr(2)
2672                 //        ssize_t listxattr (const char *path, char *list, size_t size);
2673                 [DllImport (MPH, SetLastError=true,
2674                                 EntryPoint="Mono_Posix_Syscall_listxattr")]
2675                 public static extern long listxattr (
2676                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2677                                 string path, byte[] list, ulong size);
2678
2679                 // Slight modification: returns 0 on success, negative on error
2680                 public static long listxattr (string path, Encoding encoding, out string [] values)
2681                 {
2682                         values = null;
2683                         long size = listxattr (path, null, 0);
2684                         if (size == 0)
2685                                 values = new string [0];
2686                         if (size <= 0)
2687                                 return (int) size;
2688
2689                         byte[] list = new byte [size];
2690                         long ret = listxattr (path, list, (ulong) size);
2691                         if (ret < 0)
2692                                 return (int) ret;
2693
2694                         GetValues (list, encoding, out values);
2695                         return 0;
2696                 }
2697
2698                 public static long listxattr (string path, out string[] values)
2699                 {
2700                         return listxattr (path, UnixEncoding.Instance, out values);
2701                 }
2702
2703                 private static void GetValues (byte[] list, Encoding encoding, out string[] values)
2704                 {
2705                         int num_values = 0;
2706                         for (int i = 0; i < list.Length; ++i)
2707                                 if (list [i] == 0)
2708                                         ++num_values;
2709
2710                         values = new string [num_values];
2711                         num_values = 0;
2712                         int str_start = 0;
2713                         for (int i = 0; i < list.Length; ++i) {
2714                                 if (list [i] == 0) {
2715                                         values [num_values++] = encoding.GetString (list, str_start, i - str_start);
2716                                         str_start = i+1;
2717                                 }
2718                         }
2719                 }
2720
2721                 // llistxattr(2)
2722                 //        ssize_t llistxattr (const char *path, char *list, size_t size);
2723                 [DllImport (MPH, SetLastError=true,
2724                                 EntryPoint="Mono_Posix_Syscall_llistxattr")]
2725                 public static extern long llistxattr (
2726                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2727                                 string path, byte[] list, ulong size);
2728
2729                 // Slight modification: returns 0 on success, negative on error
2730                 public static long llistxattr (string path, Encoding encoding, out string [] values)
2731                 {
2732                         values = null;
2733                         long size = llistxattr (path, null, 0);
2734                         if (size == 0)
2735                                 values = new string [0];
2736                         if (size <= 0)
2737                                 return (int) size;
2738
2739                         byte[] list = new byte [size];
2740                         long ret = llistxattr (path, list, (ulong) size);
2741                         if (ret < 0)
2742                                 return (int) ret;
2743
2744                         GetValues (list, encoding, out values);
2745                         return 0;
2746                 }
2747
2748                 public static long llistxattr (string path, out string[] values)
2749                 {
2750                         return llistxattr (path, UnixEncoding.Instance, out values);
2751                 }
2752
2753                 // flistxattr(2)
2754                 //        ssize_t flistxattr (int fd, char *list, size_t size);
2755                 [DllImport (MPH, SetLastError=true,
2756                                 EntryPoint="Mono_Posix_Syscall_flistxattr")]
2757                 public static extern long flistxattr (int fd, byte[] list, ulong size);
2758
2759                 // Slight modification: returns 0 on success, negative on error
2760                 public static long flistxattr (int fd, Encoding encoding, out string [] values)
2761                 {
2762                         values = null;
2763                         long size = flistxattr (fd, null, 0);
2764                         if (size == 0)
2765                                 values = new string [0];
2766                         if (size <= 0)
2767                                 return (int) size;
2768
2769                         byte[] list = new byte [size];
2770                         long ret = flistxattr (fd, list, (ulong) size);
2771                         if (ret < 0)
2772                                 return (int) ret;
2773
2774                         GetValues (list, encoding, out values);
2775                         return 0;
2776                 }
2777
2778                 public static long flistxattr (int fd, out string[] values)
2779                 {
2780                         return flistxattr (fd, UnixEncoding.Instance, out values);
2781                 }
2782
2783                 [DllImport (MPH, SetLastError=true,
2784                                 EntryPoint="Mono_Posix_Syscall_removexattr")]
2785                 public static extern int removexattr (
2786                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2787                                 string path, 
2788                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2789                                 string name);
2790
2791                 [DllImport (MPH, SetLastError=true,
2792                                 EntryPoint="Mono_Posix_Syscall_lremovexattr")]
2793                 public static extern int lremovexattr (
2794                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2795                                 string path, 
2796                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2797                                 string name);
2798
2799                 [DllImport (MPH, SetLastError=true,
2800                                 EntryPoint="Mono_Posix_Syscall_fremovexattr")]
2801                 public static extern int fremovexattr (int fd, 
2802                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2803                                 string name);
2804                 #endregion
2805
2806                 #region <dirent.h> Declarations
2807                 //
2808                 // <dirent.h>
2809                 //
2810                 // TODO: scandir(3), alphasort(3), versionsort(3), getdirentries(3)
2811
2812                 [DllImport (LIBC, SetLastError=true)]
2813                 public static extern IntPtr opendir (
2814                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2815                                 string name);
2816
2817                 [DllImport (LIBC, SetLastError=true)]
2818                 public static extern int closedir (IntPtr dir);
2819
2820                 // seekdir(3):
2821                 //    void seekdir (DIR *dir, off_t offset);
2822                 //    Slight modification.  Returns -1 on error, 0 on success.
2823                 [DllImport (MPH, SetLastError=true,
2824                                 EntryPoint="Mono_Posix_Syscall_seekdir")]
2825                 public static extern int seekdir (IntPtr dir, long offset);
2826
2827                 // telldir(3)
2828                 //    off_t telldir(DIR *dir);
2829                 [DllImport (MPH, SetLastError=true,
2830                                 EntryPoint="Mono_Posix_Syscall_telldir")]
2831                 public static extern long telldir (IntPtr dir);
2832
2833                 [DllImport (MPH, SetLastError=true,
2834                                 EntryPoint="Mono_Posix_Syscall_rewinddir")]
2835                 public static extern int rewinddir (IntPtr dir);
2836
2837                 private struct _Dirent {
2838                         [ino_t] public ulong      d_ino;
2839                         [off_t] public long       d_off;
2840                         public ushort             d_reclen;
2841                         public byte               d_type;
2842                         public IntPtr             d_name;
2843                 }
2844
2845                 private static void CopyDirent (Dirent to, ref _Dirent from)
2846                 {
2847                         try {
2848                                 to.d_ino    = from.d_ino;
2849                                 to.d_off    = from.d_off;
2850                                 to.d_reclen = from.d_reclen;
2851                                 to.d_type   = from.d_type;
2852                                 to.d_name   = UnixMarshal.PtrToString (from.d_name);
2853                         }
2854                         finally {
2855                                 Stdlib.free (from.d_name);
2856                                 from.d_name = IntPtr.Zero;
2857                         }
2858                 }
2859
2860                 internal static object readdir_lock = new object ();
2861
2862                 [DllImport (MPH, SetLastError=true,
2863                                 EntryPoint="Mono_Posix_Syscall_readdir")]
2864                 private static extern int sys_readdir (IntPtr dir, out _Dirent dentry);
2865
2866                 public static Dirent readdir (IntPtr dir)
2867                 {
2868                         _Dirent dentry;
2869                         int r;
2870                         lock (readdir_lock) {
2871                                 r = sys_readdir (dir, out dentry);
2872                         }
2873                         if (r != 0)
2874                                 return null;
2875                         Dirent d = new Dirent ();
2876                         CopyDirent (d, ref dentry);
2877                         return d;
2878                 }
2879
2880                 [DllImport (MPH, SetLastError=true,
2881                                 EntryPoint="Mono_Posix_Syscall_readdir_r")]
2882                 private static extern int sys_readdir_r (IntPtr dirp, out _Dirent entry, out IntPtr result);
2883
2884                 public static int readdir_r (IntPtr dirp, Dirent entry, out IntPtr result)
2885                 {
2886                         entry.d_ino    = 0;
2887                         entry.d_off    = 0;
2888                         entry.d_reclen = 0;
2889                         entry.d_type   = 0;
2890                         entry.d_name   = null;
2891
2892                         _Dirent _d;
2893                         int r = sys_readdir_r (dirp, out _d, out result);
2894
2895                         if (r == 0 && result != IntPtr.Zero) {
2896                                 CopyDirent (entry, ref _d);
2897                         }
2898
2899                         return r;
2900                 }
2901
2902                 [DllImport (LIBC, SetLastError=true)]
2903                 public static extern int dirfd (IntPtr dir);
2904
2905                 [DllImport (LIBC, SetLastError=true)]
2906                 public static extern IntPtr fdopendir (int fd);
2907                 #endregion
2908
2909                 #region <fcntl.h> Declarations
2910                 //
2911                 // <fcntl.h> -- COMPLETE
2912                 //
2913
2914                 [DllImport (MPH, SetLastError=true, 
2915                                 EntryPoint="Mono_Posix_Syscall_fcntl")]
2916                 public static extern int fcntl (int fd, FcntlCommand cmd);
2917
2918                 [DllImport (MPH, SetLastError=true, 
2919                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg")]
2920                 public static extern int fcntl (int fd, FcntlCommand cmd, long arg);
2921
2922                 [DllImport (MPH, SetLastError=true, 
2923                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg_int")]
2924                 public static extern int fcntl (int fd, FcntlCommand cmd, int arg);
2925
2926                 [DllImport (MPH, SetLastError=true, 
2927                                 EntryPoint="Mono_Posix_Syscall_fcntl_arg_ptr")]
2928                 public static extern int fcntl (int fd, FcntlCommand cmd, IntPtr ptr);
2929
2930                 public static int fcntl (int fd, FcntlCommand cmd, DirectoryNotifyFlags arg)
2931                 {
2932                         if (cmd != FcntlCommand.F_NOTIFY) {
2933                                 SetLastError (Errno.EINVAL);
2934                                 return -1;
2935                         }
2936                         long _arg = NativeConvert.FromDirectoryNotifyFlags (arg);
2937                         return fcntl (fd, FcntlCommand.F_NOTIFY, _arg);
2938                 }
2939
2940                 [DllImport (MPH, SetLastError=true, 
2941                                 EntryPoint="Mono_Posix_Syscall_fcntl_lock")]
2942                 public static extern int fcntl (int fd, FcntlCommand cmd, ref Flock @lock);
2943
2944                 [DllImport (MPH, SetLastError=true, 
2945                                 EntryPoint="Mono_Posix_Syscall_open")]
2946                 public static extern int open (
2947                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2948                                 string pathname, OpenFlags flags);
2949
2950                 // open(2)
2951                 //    int open(const char *pathname, int flags, mode_t mode);
2952                 [DllImport (MPH, SetLastError=true, 
2953                                 EntryPoint="Mono_Posix_Syscall_open_mode")]
2954                 public static extern int open (
2955                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2956                                 string pathname, OpenFlags flags, FilePermissions mode);
2957
2958                 // creat(2)
2959                 //    int creat(const char *pathname, mode_t mode);
2960                 [DllImport (MPH, SetLastError=true, 
2961                                 EntryPoint="Mono_Posix_Syscall_creat")]
2962                 public static extern int creat (
2963                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2964                                 string pathname, FilePermissions mode);
2965
2966                 // posix_fadvise(2)
2967                 //    int posix_fadvise(int fd, off_t offset, off_t len, int advice);
2968                 [DllImport (MPH, SetLastError=true, 
2969                                 EntryPoint="Mono_Posix_Syscall_posix_fadvise")]
2970                 public static extern int posix_fadvise (int fd, long offset, 
2971                         long len, PosixFadviseAdvice advice);
2972
2973                 // posix_fallocate(P)
2974                 //    int posix_fallocate(int fd, off_t offset, size_t len);
2975                 [DllImport (MPH, SetLastError=true, 
2976                                 EntryPoint="Mono_Posix_Syscall_posix_fallocate")]
2977                 public static extern int posix_fallocate (int fd, long offset, ulong len);
2978
2979                 [DllImport (LIBC, SetLastError=true, 
2980                                 EntryPoint="openat")]
2981                 private static extern int sys_openat (int dirfd,
2982                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2983                                 string pathname, int flags);
2984
2985                 // openat(2)
2986                 //    int openat(int dirfd, const char *pathname, int flags, mode_t mode);
2987                 [DllImport (LIBC, SetLastError=true, 
2988                                 EntryPoint="openat")]
2989                 private static extern int sys_openat (int dirfd,
2990                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
2991                                 string pathname, int flags, uint mode);
2992
2993                 public static int openat (int dirfd, string pathname, OpenFlags flags)
2994                 {
2995                         int _flags = NativeConvert.FromOpenFlags (flags);
2996                         return sys_openat (dirfd, pathname, _flags);
2997                 }
2998
2999                 public static int openat (int dirfd, string pathname, OpenFlags flags, FilePermissions mode)
3000                 {
3001                         int _flags = NativeConvert.FromOpenFlags (flags);
3002                         uint _mode = NativeConvert.FromFilePermissions (mode);
3003                         return sys_openat (dirfd, pathname, _flags, _mode);
3004                 }
3005
3006                 [DllImport (MPH, SetLastError=true, 
3007                                 EntryPoint="Mono_Posix_Syscall_get_at_fdcwd")]
3008                 private static extern int get_at_fdcwd ();
3009
3010                 public static readonly int AT_FDCWD = get_at_fdcwd ();
3011
3012                 #endregion
3013
3014                 #region <fstab.h> Declarations
3015                 //
3016                 // <fstab.h>  -- COMPLETE
3017                 //
3018                 [Map]
3019                 private struct _Fstab {
3020                         public IntPtr fs_spec;
3021                         public IntPtr fs_file;
3022                         public IntPtr fs_vfstype;
3023                         public IntPtr fs_mntops;
3024                         public IntPtr fs_type;
3025                         public int    fs_freq;
3026                         public int    fs_passno;
3027                         public IntPtr _fs_buf_;
3028                 }
3029
3030                 private static void CopyFstab (Fstab to, ref _Fstab from)
3031                 {
3032                         try {
3033                                 to.fs_spec     = UnixMarshal.PtrToString (from.fs_spec);
3034                                 to.fs_file     = UnixMarshal.PtrToString (from.fs_file);
3035                                 to.fs_vfstype  = UnixMarshal.PtrToString (from.fs_vfstype);
3036                                 to.fs_mntops   = UnixMarshal.PtrToString (from.fs_mntops);
3037                                 to.fs_type     = UnixMarshal.PtrToString (from.fs_type);
3038                                 to.fs_freq     = from.fs_freq;
3039                                 to.fs_passno   = from.fs_passno;
3040                         }
3041                         finally {
3042                                 Stdlib.free (from._fs_buf_);
3043                                 from._fs_buf_ = IntPtr.Zero;
3044                         }
3045                 }
3046
3047                 internal static object fstab_lock = new object ();
3048
3049                 [DllImport (MPH, SetLastError=true,
3050                                 EntryPoint="Mono_Posix_Syscall_endfsent")]
3051                 private static extern int sys_endfsent ();
3052
3053                 public static int endfsent ()
3054                 {
3055                         lock (fstab_lock) {
3056                                 return sys_endfsent ();
3057                         }
3058                 }
3059
3060                 [DllImport (MPH, SetLastError=true,
3061                                 EntryPoint="Mono_Posix_Syscall_getfsent")]
3062                 private static extern int sys_getfsent (out _Fstab fs);
3063
3064                 public static Fstab getfsent ()
3065                 {
3066                         _Fstab fsbuf;
3067                         int r;
3068                         lock (fstab_lock) {
3069                                 r = sys_getfsent (out fsbuf);
3070                         }
3071                         if (r != 0)
3072                                 return null;
3073                         Fstab fs = new Fstab ();
3074                         CopyFstab (fs, ref fsbuf);
3075                         return fs;
3076                 }
3077
3078                 [DllImport (MPH, SetLastError=true,
3079                                 EntryPoint="Mono_Posix_Syscall_getfsfile")]
3080                 private static extern int sys_getfsfile (
3081                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3082                                 string mount_point, out _Fstab fs);
3083
3084                 public static Fstab getfsfile (string mount_point)
3085                 {
3086                         _Fstab fsbuf;
3087                         int r;
3088                         lock (fstab_lock) {
3089                                 r = sys_getfsfile (mount_point, out fsbuf);
3090                         }
3091                         if (r != 0)
3092                                 return null;
3093                         Fstab fs = new Fstab ();
3094                         CopyFstab (fs, ref fsbuf);
3095                         return fs;
3096                 }
3097
3098                 [DllImport (MPH, SetLastError=true,
3099                                 EntryPoint="Mono_Posix_Syscall_getfsspec")]
3100                 private static extern int sys_getfsspec (
3101                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3102                                 string special_file, out _Fstab fs);
3103
3104                 public static Fstab getfsspec (string special_file)
3105                 {
3106                         _Fstab fsbuf;
3107                         int r;
3108                         lock (fstab_lock) {
3109                                 r = sys_getfsspec (special_file, out fsbuf);
3110                         }
3111                         if (r != 0)
3112                                 return null;
3113                         Fstab fs = new Fstab ();
3114                         CopyFstab (fs, ref fsbuf);
3115                         return fs;
3116                 }
3117
3118                 [DllImport (MPH, SetLastError=true,
3119                                 EntryPoint="Mono_Posix_Syscall_setfsent")]
3120                 private static extern int sys_setfsent ();
3121
3122                 public static int setfsent ()
3123                 {
3124                         lock (fstab_lock) {
3125                                 return sys_setfsent ();
3126                         }
3127                 }
3128
3129                 #endregion
3130
3131                 #region <grp.h> Declarations
3132                 //
3133                 // <grp.h>
3134                 //
3135                 // TODO: putgrent(3), fgetgrent_r(), initgroups(3)
3136
3137                 // getgrouplist(2)
3138                 [DllImport (LIBC, SetLastError=true, EntryPoint="getgrouplist")]
3139                 private static extern int sys_getgrouplist (string user, uint grp, uint [] groups,ref int ngroups);
3140
3141                 public static Group [] getgrouplist (string username)
3142                 {
3143                         if (username == null)
3144                                 throw new ArgumentNullException ("username");
3145                         if (username.Trim () == "")
3146                                 throw new ArgumentException ("Username cannot be empty", "username");
3147                         // Syscall to getpwnam to retrieve user uid
3148                         Passwd pw = Syscall.getpwnam (username);
3149                         if (pw == null)
3150                                 throw new ArgumentException (string.Format ("User {0} does not exist", username), "username");
3151                         return getgrouplist (pw);
3152                 }
3153
3154                 public static Group [] getgrouplist (Passwd user)
3155                 {
3156                         if (user == null)
3157                                 throw new ArgumentNullException ("user");
3158                         // initializing ngroups by 16 to get the group count
3159                         int ngroups = 8;
3160                         int res = -1;
3161                         // allocating buffer to store group uid's
3162                         uint [] groups=null;
3163                         do {
3164                                 Array.Resize (ref groups, ngroups*=2);
3165                                 res = sys_getgrouplist (user.pw_name, user.pw_gid, groups, ref ngroups);
3166                         }
3167                         while (res == -1);
3168                         List<Group> result = new List<Group> ();
3169                         Group gr = null;
3170                         for (int i = 0; i < res; i++) {
3171                                 gr = Syscall.getgrgid (groups [i]);
3172                                 if (gr != null)
3173                                         result.Add (gr);
3174                         }
3175                         return result.ToArray ();
3176                 }
3177
3178                 // setgroups(2)
3179                 //    int setgroups (size_t size, const gid_t *list);
3180                 [DllImport (MPH, SetLastError=true,
3181                                 EntryPoint="Mono_Posix_Syscall_setgroups")]
3182                 public static extern int setgroups (ulong size, uint[] list);
3183
3184                 public static int setgroups (uint [] list)
3185                 {
3186                         return setgroups ((ulong) list.Length, list);
3187                 }
3188
3189                 [Map]
3190                 private struct _Group
3191                 {
3192                         public IntPtr           gr_name;
3193                         public IntPtr           gr_passwd;
3194                         [gid_t] public uint     gr_gid;
3195                         public int              _gr_nmem_;
3196                         public IntPtr           gr_mem;
3197                         public IntPtr           _gr_buf_;
3198                 }
3199
3200                 private static void CopyGroup (Group to, ref _Group from)
3201                 {
3202                         try {
3203                                 to.gr_gid    = from.gr_gid;
3204                                 to.gr_name   = UnixMarshal.PtrToString (from.gr_name);
3205                                 to.gr_passwd = UnixMarshal.PtrToString (from.gr_passwd);
3206                                 to.gr_mem    = UnixMarshal.PtrToStringArray (from._gr_nmem_, from.gr_mem);
3207                         }
3208                         finally {
3209                                 Stdlib.free (from.gr_mem);
3210                                 Stdlib.free (from._gr_buf_);
3211                                 from.gr_mem   = IntPtr.Zero;
3212                                 from._gr_buf_ = IntPtr.Zero;
3213                         }
3214                 }
3215
3216                 internal static object grp_lock = new object ();
3217
3218                 [DllImport (MPH, SetLastError=true,
3219                                 EntryPoint="Mono_Posix_Syscall_getgrnam")]
3220                 private static extern int sys_getgrnam (string name, out _Group group);
3221
3222                 public static Group getgrnam (string name)
3223                 {
3224                         _Group group;
3225                         int r;
3226                         lock (grp_lock) {
3227                                 r = sys_getgrnam (name, out group);
3228                         }
3229                         if (r != 0)
3230                                 return null;
3231                         Group gr = new Group ();
3232                         CopyGroup (gr, ref group);
3233                         return gr;
3234                 }
3235
3236                 // getgrgid(3)
3237                 //    struct group *getgrgid(gid_t gid);
3238                 [DllImport (MPH, SetLastError=true,
3239                                 EntryPoint="Mono_Posix_Syscall_getgrgid")]
3240                 private static extern int sys_getgrgid (uint uid, out _Group group);
3241
3242                 public static Group getgrgid (uint uid)
3243                 {
3244                         _Group group;
3245                         int r;
3246                         lock (grp_lock) {
3247                                 r = sys_getgrgid (uid, out group);
3248                         }
3249                         if (r != 0)
3250                                 return null;
3251                         Group gr = new Group ();
3252                         CopyGroup (gr, ref group);
3253                         return gr;
3254                 }
3255
3256                 [DllImport (MPH, SetLastError=true,
3257                                 EntryPoint="Mono_Posix_Syscall_getgrnam_r")]
3258                 private static extern int sys_getgrnam_r (
3259                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3260                                 string name, out _Group grbuf, out IntPtr grbufp);
3261
3262                 public static int getgrnam_r (string name, Group grbuf, out Group grbufp)
3263                 {
3264                         grbufp = null;
3265                         _Group group;
3266                         IntPtr _grbufp;
3267                         int r = sys_getgrnam_r (name, out group, out _grbufp);
3268                         if (r == 0 && _grbufp != IntPtr.Zero) {
3269                                 CopyGroup (grbuf, ref group);
3270                                 grbufp = grbuf;
3271                         }
3272                         return r;
3273                 }
3274
3275                 // getgrgid_r(3)
3276                 //    int getgrgid_r(gid_t gid, struct group *gbuf, char *buf,
3277                 //        size_t buflen, struct group **gbufp);
3278                 [DllImport (MPH, SetLastError=true,
3279                                 EntryPoint="Mono_Posix_Syscall_getgrgid_r")]
3280                 private static extern int sys_getgrgid_r (uint uid, out _Group grbuf, out IntPtr grbufp);
3281
3282                 public static int getgrgid_r (uint uid, Group grbuf, out Group grbufp)
3283                 {
3284                         grbufp = null;
3285                         _Group group;
3286                         IntPtr _grbufp;
3287                         int r = sys_getgrgid_r (uid, out group, out _grbufp);
3288                         if (r == 0 && _grbufp != IntPtr.Zero) {
3289                                 CopyGroup (grbuf, ref group);
3290                                 grbufp = grbuf;
3291                         }
3292                         return r;
3293                 }
3294
3295                 [DllImport (MPH, SetLastError=true,
3296                                 EntryPoint="Mono_Posix_Syscall_getgrent")]
3297                 private static extern int sys_getgrent (out _Group grbuf);
3298
3299                 public static Group getgrent ()
3300                 {
3301                         _Group group;
3302                         int r;
3303                         lock (grp_lock) {
3304                                 r = sys_getgrent (out group);
3305                         }
3306                         if (r != 0)
3307                                 return null;
3308                         Group gr = new Group();
3309                         CopyGroup (gr, ref group);
3310                         return gr;
3311                 }
3312
3313                 [DllImport (MPH, SetLastError=true, 
3314                                 EntryPoint="Mono_Posix_Syscall_setgrent")]
3315                 private static extern int sys_setgrent ();
3316
3317                 public static int setgrent ()
3318                 {
3319                         lock (grp_lock) {
3320                                 return sys_setgrent ();
3321                         }
3322                 }
3323
3324                 [DllImport (MPH, SetLastError=true, 
3325                                 EntryPoint="Mono_Posix_Syscall_endgrent")]
3326                 private static extern int sys_endgrent ();
3327
3328                 public static int endgrent ()
3329                 {
3330                         lock (grp_lock) {
3331                                 return sys_endgrent ();
3332                         }
3333                 }
3334
3335                 [DllImport (MPH, SetLastError=true,
3336                                 EntryPoint="Mono_Posix_Syscall_fgetgrent")]
3337                 private static extern int sys_fgetgrent (IntPtr stream, out _Group grbuf);
3338
3339                 public static Group fgetgrent (IntPtr stream)
3340                 {
3341                         _Group group;
3342                         int r;
3343                         lock (grp_lock) {
3344                                 r = sys_fgetgrent (stream, out group);
3345                         }
3346                         if (r != 0)
3347                                 return null;
3348                         Group gr = new Group ();
3349                         CopyGroup (gr, ref group);
3350                         return gr;
3351                 }
3352                 #endregion
3353
3354                 #region <pwd.h> Declarations
3355                 //
3356                 // <pwd.h>
3357                 //
3358                 // TODO: putpwent(3), fgetpwent_r()
3359                 //
3360                 // SKIPPING: getpw(3): it's dangerous.  Use getpwuid(3) instead.
3361
3362                 [Map]
3363                 private struct _Passwd
3364                 {
3365                         public IntPtr           pw_name;
3366                         public IntPtr           pw_passwd;
3367                         [uid_t] public uint     pw_uid;
3368                         [gid_t] public uint     pw_gid;
3369                         public IntPtr           pw_gecos;
3370                         public IntPtr           pw_dir;
3371                         public IntPtr           pw_shell;
3372                         public IntPtr           _pw_buf_;
3373                 }
3374
3375                 private static void CopyPasswd (Passwd to, ref _Passwd from)
3376                 {
3377                         try {
3378                                 to.pw_name   = UnixMarshal.PtrToString (from.pw_name);
3379                                 to.pw_passwd = UnixMarshal.PtrToString (from.pw_passwd);
3380                                 to.pw_uid    = from.pw_uid;
3381                                 to.pw_gid    = from.pw_gid;
3382                                 to.pw_gecos  = UnixMarshal.PtrToString (from.pw_gecos);
3383                                 to.pw_dir    = UnixMarshal.PtrToString (from.pw_dir);
3384                                 to.pw_shell  = UnixMarshal.PtrToString (from.pw_shell);
3385                         }
3386                         finally {
3387                                 Stdlib.free (from._pw_buf_);
3388                                 from._pw_buf_ = IntPtr.Zero;
3389                         }
3390                 }
3391
3392                 internal static object pwd_lock = new object ();
3393
3394                 [DllImport (MPH, SetLastError=true,
3395                                 EntryPoint="Mono_Posix_Syscall_getpwnam")]
3396                 private static extern int sys_getpwnam (string name, out _Passwd passwd);
3397
3398                 public static Passwd getpwnam (string name)
3399                 {
3400                         _Passwd passwd;
3401                         int r;
3402                         lock (pwd_lock) {
3403                                 r = sys_getpwnam (name, out passwd);
3404                         }
3405                         if (r != 0)
3406                                 return null;
3407                         Passwd pw = new Passwd ();
3408                         CopyPasswd (pw, ref passwd);
3409                         return pw;
3410                 }
3411
3412                 // getpwuid(3)
3413                 //    struct passwd *getpwnuid(uid_t uid);
3414                 [DllImport (MPH, SetLastError=true,
3415                                 EntryPoint="Mono_Posix_Syscall_getpwuid")]
3416                 private static extern int sys_getpwuid (uint uid, out _Passwd passwd);
3417
3418                 public static Passwd getpwuid (uint uid)
3419                 {
3420                         _Passwd passwd;
3421                         int r;
3422                         lock (pwd_lock) {
3423                                 r = sys_getpwuid (uid, out passwd);
3424                         }
3425                         if (r != 0)
3426                                 return null;
3427                         Passwd pw = new Passwd ();
3428                         CopyPasswd (pw, ref passwd);
3429                         return pw;
3430                 }
3431
3432                 [DllImport (MPH, SetLastError=true,
3433                                 EntryPoint="Mono_Posix_Syscall_getpwnam_r")]
3434                 private static extern int sys_getpwnam_r (
3435                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3436                                 string name, out _Passwd pwbuf, out IntPtr pwbufp);
3437
3438                 public static int getpwnam_r (string name, Passwd pwbuf, out Passwd pwbufp)
3439                 {
3440                         pwbufp = null;
3441                         _Passwd passwd;
3442                         IntPtr _pwbufp;
3443                         int r = sys_getpwnam_r (name, out passwd, out _pwbufp);
3444                         if (r == 0 && _pwbufp != IntPtr.Zero) {
3445                                 CopyPasswd (pwbuf, ref passwd);
3446                                 pwbufp = pwbuf;
3447                         }
3448                         return r;
3449                 }
3450
3451                 // getpwuid_r(3)
3452                 //    int getpwuid_r(uid_t uid, struct passwd *pwbuf, char *buf, size_t
3453                 //        buflen, struct passwd **pwbufp);
3454                 [DllImport (MPH, SetLastError=true,
3455                                 EntryPoint="Mono_Posix_Syscall_getpwuid_r")]
3456                 private static extern int sys_getpwuid_r (uint uid, out _Passwd pwbuf, out IntPtr pwbufp);
3457
3458                 public static int getpwuid_r (uint uid, Passwd pwbuf, out Passwd pwbufp)
3459                 {
3460                         pwbufp = null;
3461                         _Passwd passwd;
3462                         IntPtr _pwbufp;
3463                         int r = sys_getpwuid_r (uid, out passwd, out _pwbufp);
3464                         if (r == 0 && _pwbufp != IntPtr.Zero) {
3465                                 CopyPasswd (pwbuf, ref passwd);
3466                                 pwbufp = pwbuf;
3467                         }
3468                         return r;
3469                 }
3470
3471                 [DllImport (MPH, SetLastError=true,
3472                                 EntryPoint="Mono_Posix_Syscall_getpwent")]
3473                 private static extern int sys_getpwent (out _Passwd pwbuf);
3474
3475                 public static Passwd getpwent ()
3476                 {
3477                         _Passwd passwd;
3478                         int r;
3479                         lock (pwd_lock) {
3480                                 r = sys_getpwent (out passwd);
3481                         }
3482                         if (r != 0)
3483                                 return null;
3484                         Passwd pw = new Passwd ();
3485                         CopyPasswd (pw, ref passwd);
3486                         return pw;
3487                 }
3488
3489                 [DllImport (MPH, SetLastError=true, 
3490                                 EntryPoint="Mono_Posix_Syscall_setpwent")]
3491                 private static extern int sys_setpwent ();
3492
3493                 public static int setpwent ()
3494                 {
3495                         lock (pwd_lock) {
3496                                 return sys_setpwent ();
3497                         }
3498                 }
3499
3500                 [DllImport (MPH, SetLastError=true, 
3501                                 EntryPoint="Mono_Posix_Syscall_endpwent")]
3502                 private static extern int sys_endpwent ();
3503
3504                 public static int endpwent ()
3505                 {
3506                         lock (pwd_lock) {
3507                                 return sys_endpwent ();
3508                         }
3509                 }
3510
3511                 [DllImport (MPH, SetLastError=true,
3512                                 EntryPoint="Mono_Posix_Syscall_fgetpwent")]
3513                 private static extern int sys_fgetpwent (IntPtr stream, out _Passwd pwbuf);
3514
3515                 public static Passwd fgetpwent (IntPtr stream)
3516                 {
3517                         _Passwd passwd;
3518                         int r;
3519                         lock (pwd_lock) {
3520                                 r = sys_fgetpwent (stream, out passwd);
3521                         }
3522                         if (r != 0)
3523                                 return null;
3524                         Passwd pw = new Passwd ();
3525                         CopyPasswd (pw, ref passwd);
3526                         return pw;
3527                 }
3528                 #endregion
3529
3530                 #region <signal.h> Declarations
3531                 //
3532                 // <signal.h>
3533                 //
3534                 [DllImport (MPH, SetLastError=true,
3535                                 EntryPoint="Mono_Posix_Syscall_psignal")]
3536                 private static extern int psignal (int sig, string s);
3537
3538                 public static int psignal (Signum sig, string s)
3539                 {
3540                         int signum = NativeConvert.FromSignum (sig);
3541                         return psignal (signum, s);
3542                 }
3543
3544                 // kill(2)
3545                 //    int kill(pid_t pid, int sig);
3546                 [DllImport (LIBC, SetLastError=true, EntryPoint="kill")]
3547                 private static extern int sys_kill (int pid, int sig);
3548
3549                 public static int kill (int pid, Signum sig)
3550                 {
3551                         int _sig = NativeConvert.FromSignum (sig);
3552                         return sys_kill (pid, _sig);
3553                 }
3554
3555                 private static object signal_lock = new object ();
3556
3557                 [DllImport (LIBC, SetLastError=true, EntryPoint="strsignal")]
3558                 private static extern IntPtr sys_strsignal (int sig);
3559
3560                 public static string strsignal (Signum sig)
3561                 {
3562                         int s = NativeConvert.FromSignum (sig);
3563                         lock (signal_lock) {
3564                                 IntPtr r = sys_strsignal (s);
3565                                 return UnixMarshal.PtrToString (r);
3566                         }
3567                 }
3568
3569                 // TODO: sigaction(2)
3570                 // TODO: sigsuspend(2)
3571                 // TODO: sigpending(2)
3572
3573                 #endregion
3574
3575                 #region <stdio.h> Declarations
3576                 //
3577                 // <stdio.h>
3578                 //
3579                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_L_ctermid")]
3580                 private static extern int _L_ctermid ();
3581
3582                 public static readonly int L_ctermid = _L_ctermid ();
3583
3584                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_L_cuserid")]
3585                 private static extern int _L_cuserid ();
3586
3587                 public static readonly int L_cuserid = _L_cuserid ();
3588
3589                 internal static object getlogin_lock = new object ();
3590
3591                 [DllImport (LIBC, SetLastError=true, EntryPoint="cuserid")]
3592                 private static extern IntPtr sys_cuserid ([Out] StringBuilder @string);
3593
3594                 [Obsolete ("\"Nobody knows precisely what cuserid() does... " + 
3595                                 "DO NOT USE cuserid().\n" +
3596                                 "`string' must hold L_cuserid characters.  Use getlogin_r instead.")]
3597                 public static string cuserid (StringBuilder @string)
3598                 {
3599                         if (@string.Capacity < L_cuserid) {
3600                                 throw new ArgumentOutOfRangeException ("string", "string.Capacity < L_cuserid");
3601                         }
3602                         lock (getlogin_lock) {
3603                                 IntPtr r = sys_cuserid (@string);
3604                                 return UnixMarshal.PtrToString (r);
3605                         }
3606                 }
3607
3608                 [DllImport (LIBC, SetLastError=true)]
3609                 public static extern int renameat (int olddirfd,
3610                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3611                                 string oldpath, int newdirfd,
3612                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3613                                 string newpath);
3614                 #endregion
3615
3616                 #region <stdlib.h> Declarations
3617                 //
3618                 // <stdlib.h>
3619                 //
3620                 [DllImport (LIBC, SetLastError=true)]
3621                 public static extern int mkstemp (StringBuilder template);
3622
3623                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdtemp")]
3624                 private static extern IntPtr sys_mkdtemp (StringBuilder template);
3625
3626                 public static StringBuilder mkdtemp (StringBuilder template)
3627                 {
3628                         if (sys_mkdtemp (template) == IntPtr.Zero)
3629                                 return null;
3630                         return template;
3631                 }
3632
3633                 [DllImport (LIBC, SetLastError=true)]
3634                 public static extern int ttyslot ();
3635
3636                 [Obsolete ("This is insecure and should not be used", true)]
3637                 public static int setkey (string key)
3638                 {
3639                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
3640                 }
3641
3642                 #endregion
3643
3644                 #region <string.h> Declarations
3645                 //
3646                 // <string.h>
3647                 //
3648
3649                 // strerror_r(3)
3650                 //    int strerror_r(int errnum, char *buf, size_t n);
3651                 [DllImport (MPH, SetLastError=true, 
3652                                 EntryPoint="Mono_Posix_Syscall_strerror_r")]
3653                 private static extern int sys_strerror_r (int errnum, 
3654                                 [Out] StringBuilder buf, ulong n);
3655
3656                 public static int strerror_r (Errno errnum, StringBuilder buf, ulong n)
3657                 {
3658                         int e = NativeConvert.FromErrno (errnum);
3659                         return sys_strerror_r (e, buf, n);
3660                 }
3661
3662                 public static int strerror_r (Errno errnum, StringBuilder buf)
3663                 {
3664                         return strerror_r (errnum, buf, (ulong) buf.Capacity);
3665                 }
3666
3667                 #endregion
3668
3669                 #region <sys/epoll.h> Declarations
3670
3671                 public static int epoll_create (int size)
3672                 {
3673                         return sys_epoll_create (size);
3674                 }
3675
3676                 public static int epoll_create (EpollFlags flags)
3677                 {
3678                         return sys_epoll_create1 (flags);
3679                 }
3680
3681                 public static int epoll_ctl (int epfd, EpollOp op, int fd, EpollEvents events)
3682                 {
3683                         EpollEvent ee = new EpollEvent ();
3684                         ee.events = events;
3685                         ee.fd = fd;
3686
3687                         return epoll_ctl (epfd, op, fd, ref ee);
3688                 }
3689
3690                 public static int epoll_wait (int epfd, EpollEvent [] events, int max_events, int timeout)
3691                 {
3692                         if (events.Length < max_events)
3693                                 throw new ArgumentOutOfRangeException ("events", "Must refer to at least 'max_events' elements.");
3694
3695                         return sys_epoll_wait (epfd, events, max_events, timeout);
3696                 }
3697
3698                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_create")]
3699                 private static extern int sys_epoll_create (int size);
3700
3701                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_create1")]
3702                 private static extern int sys_epoll_create1 (EpollFlags flags);
3703
3704                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_ctl")]
3705                 public static extern int epoll_ctl (int epfd, EpollOp op, int fd, ref EpollEvent ee);
3706
3707                 [DllImport (LIBC, SetLastError=true, EntryPoint="epoll_wait")]
3708                 private static extern int sys_epoll_wait (int epfd, EpollEvent [] ee, int maxevents, int timeout);
3709                 #endregion
3710                 
3711                 #region <sys/mman.h> Declarations
3712                 //
3713                 // <sys/mman.h>
3714                 //
3715
3716                 // posix_madvise(P)
3717                 //    int posix_madvise(void *addr, size_t len, int advice);
3718                 [DllImport (MPH, SetLastError=true, 
3719                                 EntryPoint="Mono_Posix_Syscall_posix_madvise")]
3720                 public static extern int posix_madvise (IntPtr addr, ulong len, 
3721                         PosixMadviseAdvice advice);
3722
3723                 public static readonly IntPtr MAP_FAILED = unchecked((IntPtr)(-1));
3724
3725                 [DllImport (MPH, SetLastError=true, 
3726                                 EntryPoint="Mono_Posix_Syscall_mmap")]
3727                 public static extern IntPtr mmap (IntPtr start, ulong length, 
3728                                 MmapProts prot, MmapFlags flags, int fd, long offset);
3729
3730                 [DllImport (MPH, SetLastError=true, 
3731                                 EntryPoint="Mono_Posix_Syscall_munmap")]
3732                 public static extern int munmap (IntPtr start, ulong length);
3733
3734                 [DllImport (MPH, SetLastError=true, 
3735                                 EntryPoint="Mono_Posix_Syscall_mprotect")]
3736                 public static extern int mprotect (IntPtr start, ulong len, MmapProts prot);
3737
3738                 [DllImport (MPH, SetLastError=true, 
3739                                 EntryPoint="Mono_Posix_Syscall_msync")]
3740                 public static extern int msync (IntPtr start, ulong len, MsyncFlags flags);
3741
3742                 [DllImport (MPH, SetLastError=true, 
3743                                 EntryPoint="Mono_Posix_Syscall_mlock")]
3744                 public static extern int mlock (IntPtr start, ulong len);
3745
3746                 [DllImport (MPH, SetLastError=true, 
3747                                 EntryPoint="Mono_Posix_Syscall_munlock")]
3748                 public static extern int munlock (IntPtr start, ulong len);
3749
3750                 [DllImport (LIBC, SetLastError=true, EntryPoint="mlockall")]
3751                 private static extern int sys_mlockall (int flags);
3752
3753                 public static int mlockall (MlockallFlags flags)
3754                 {
3755                         int _flags = NativeConvert.FromMlockallFlags (flags);
3756                         return sys_mlockall (_flags);
3757                 }
3758
3759                 [DllImport (LIBC, SetLastError=true)]
3760                 public static extern int munlockall ();
3761
3762                 [DllImport (MPH, SetLastError=true, 
3763                                 EntryPoint="Mono_Posix_Syscall_mremap")]
3764                 public static extern IntPtr mremap (IntPtr old_address, ulong old_size, 
3765                                 ulong new_size, MremapFlags flags);
3766
3767                 [DllImport (MPH, SetLastError=true, 
3768                                 EntryPoint="Mono_Posix_Syscall_mincore")]
3769                 public static extern int mincore (IntPtr start, ulong length, byte[] vec);
3770
3771                 [DllImport (MPH, SetLastError=true, 
3772                                 EntryPoint="Mono_Posix_Syscall_remap_file_pages")]
3773                 public static extern int remap_file_pages (IntPtr start, ulong size,
3774                                 MmapProts prot, long pgoff, MmapFlags flags);
3775
3776                 #endregion
3777
3778                 #region <sys/poll.h> Declarations
3779                 //
3780                 // <sys/poll.h> -- COMPLETE
3781                 //
3782
3783                 private struct _pollfd {
3784                         public int fd;
3785                         public short events;
3786                         public short revents;
3787                 }
3788
3789                 [DllImport (LIBC, SetLastError=true, EntryPoint="poll")]
3790                 private static extern int sys_poll (_pollfd[] ufds, uint nfds, int timeout);
3791
3792                 public static int poll (Pollfd [] fds, uint nfds, int timeout)
3793                 {
3794                         if (fds.Length < nfds)
3795                                 throw new ArgumentOutOfRangeException ("fds", "Must refer to at least `nfds' elements");
3796
3797                         _pollfd[] send = new _pollfd[nfds];
3798
3799                         for (int i = 0; i < send.Length; i++) {
3800                                 send [i].fd     = fds [i].fd;
3801                                 send [i].events = NativeConvert.FromPollEvents (fds [i].events);
3802                         }
3803
3804                         int r = sys_poll (send, nfds, timeout);
3805
3806                         for (int i = 0; i < send.Length; i++) {
3807                                 fds [i].revents = NativeConvert.ToPollEvents (send [i].revents);
3808                         }
3809
3810                         return r;
3811                 }
3812
3813                 public static int poll (Pollfd [] fds, int timeout)
3814                 {
3815                         return poll (fds, (uint) fds.Length, timeout);
3816                 }
3817
3818                 //
3819                 // <sys/ptrace.h>
3820                 //
3821
3822                 // TODO: ptrace(2)
3823
3824                 //
3825                 // <sys/resource.h>
3826                 //
3827
3828                 // TODO: setrlimit(2)
3829                 // TODO: getrlimit(2)
3830                 // TODO: getrusage(2)
3831
3832                 #endregion
3833
3834                 #region <sys/sendfile.h> Declarations
3835                 //
3836                 // <sys/sendfile.h> -- COMPLETE
3837                 //
3838
3839                 [DllImport (MPH, SetLastError=true,
3840                                 EntryPoint="Mono_Posix_Syscall_sendfile")]
3841                 public static extern long sendfile (int out_fd, int in_fd, 
3842                                 ref long offset, ulong count);
3843
3844                 #endregion
3845
3846                 #region <sys/stat.h> Declarations
3847                 //
3848                 // <sys/stat.h>  -- COMPLETE
3849                 //
3850                 [DllImport (MPH, SetLastError=true, 
3851                                 EntryPoint="Mono_Posix_Syscall_stat")]
3852                 public static extern int stat (
3853                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3854                                 string file_name, out Stat buf);
3855
3856                 [DllImport (MPH, SetLastError=true, 
3857                                 EntryPoint="Mono_Posix_Syscall_fstat")]
3858                 public static extern int fstat (int filedes, out Stat buf);
3859
3860                 [DllImport (MPH, SetLastError=true, 
3861                                 EntryPoint="Mono_Posix_Syscall_lstat")]
3862                 public static extern int lstat (
3863                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3864                                 string file_name, out Stat buf);
3865
3866                 // TODO:
3867                 // S_ISDIR, S_ISCHR, S_ISBLK, S_ISREG, S_ISFIFO, S_ISLNK, S_ISSOCK
3868                 // All take FilePermissions
3869
3870                 // chmod(2)
3871                 //    int chmod(const char *path, mode_t mode);
3872                 [DllImport (LIBC, SetLastError=true, EntryPoint="chmod")]
3873                 private static extern int sys_chmod (
3874                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3875                                 string path, uint mode);
3876
3877                 public static int chmod (string path, FilePermissions mode)
3878                 {
3879                         uint _mode = NativeConvert.FromFilePermissions (mode);
3880                         return sys_chmod (path, _mode);
3881                 }
3882
3883                 // fchmod(2)
3884                 //    int chmod(int filedes, mode_t mode);
3885                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchmod")]
3886                 private static extern int sys_fchmod (int filedes, uint mode);
3887
3888                 public static int fchmod (int filedes, FilePermissions mode)
3889                 {
3890                         uint _mode = NativeConvert.FromFilePermissions (mode);
3891                         return sys_fchmod (filedes, _mode);
3892                 }
3893
3894                 // umask(2)
3895                 //    mode_t umask(mode_t mask);
3896                 [DllImport (LIBC, SetLastError=true, EntryPoint="umask")]
3897                 private static extern uint sys_umask (uint mask);
3898
3899                 public static FilePermissions umask (FilePermissions mask)
3900                 {
3901                         uint _mask = NativeConvert.FromFilePermissions (mask);
3902                         uint r = sys_umask (_mask);
3903                         return NativeConvert.ToFilePermissions (r);
3904                 }
3905
3906                 // mkdir(2)
3907                 //    int mkdir(const char *pathname, mode_t mode);
3908                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdir")]
3909                 private static extern int sys_mkdir (
3910                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3911                                 string oldpath, uint mode);
3912
3913                 public static int mkdir (string oldpath, FilePermissions mode)
3914                 {
3915                         uint _mode = NativeConvert.FromFilePermissions (mode);
3916                         return sys_mkdir (oldpath, _mode);
3917                 }
3918
3919                 // mknod(2)
3920                 //    int mknod (const char *pathname, mode_t mode, dev_t dev);
3921                 [DllImport (MPH, SetLastError=true,
3922                                 EntryPoint="Mono_Posix_Syscall_mknod")]
3923                 public static extern int mknod (
3924                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3925                                 string pathname, FilePermissions mode, ulong dev);
3926
3927                 // mkfifo(3)
3928                 //    int mkfifo(const char *pathname, mode_t mode);
3929                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkfifo")]
3930                 private static extern int sys_mkfifo (
3931                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3932                                 string pathname, uint mode);
3933
3934                 public static int mkfifo (string pathname, FilePermissions mode)
3935                 {
3936                         uint _mode = NativeConvert.FromFilePermissions (mode);
3937                         return sys_mkfifo (pathname, _mode);
3938                 }
3939
3940                 // fchmodat(2)
3941                 //    int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
3942                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchmodat")]
3943                 private static extern int sys_fchmodat (int dirfd,
3944                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3945                                 string pathname, uint mode, int flags);
3946
3947                 public static int fchmodat (int dirfd, string pathname, FilePermissions mode, AtFlags flags)
3948                 {
3949                         uint _mode = NativeConvert.FromFilePermissions (mode);
3950                         int _flags = NativeConvert.FromAtFlags (flags);
3951                         return sys_fchmodat (dirfd, pathname, _mode, _flags);
3952                 }
3953
3954                 [DllImport (MPH, SetLastError=true, 
3955                                 EntryPoint="Mono_Posix_Syscall_fstatat")]
3956                 public static extern int fstatat (int dirfd,
3957                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3958                                 string file_name, out Stat buf, AtFlags flags);
3959
3960                 [DllImport (MPH, SetLastError=true, 
3961                                 EntryPoint="Mono_Posix_Syscall_get_utime_now")]
3962                 private static extern long get_utime_now ();
3963
3964                 [DllImport (MPH, SetLastError=true, 
3965                                 EntryPoint="Mono_Posix_Syscall_get_utime_omit")]
3966                 private static extern long get_utime_omit ();
3967
3968                 public static readonly long UTIME_NOW = get_utime_now ();
3969
3970                 public static readonly long UTIME_OMIT = get_utime_omit ();
3971
3972                 [DllImport (MPH, SetLastError=true, 
3973                                 EntryPoint="Mono_Posix_Syscall_futimens")]
3974                 private static extern int sys_futimens (int fd, Timespec[] times);
3975
3976                 public static int futimens (int fd, Timespec[] times)
3977                 {
3978                         if (times != null && times.Length != 2) {
3979                                 SetLastError (Errno.EINVAL);
3980                                 return -1;
3981                         }
3982                         return sys_futimens (fd, times);
3983                 }
3984
3985                 [DllImport (MPH, SetLastError=true, 
3986                                 EntryPoint="Mono_Posix_Syscall_utimensat")]
3987                 private static extern int sys_utimensat (int dirfd,
3988                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
3989                                 string pathname, Timespec[] times, int flags);
3990
3991                 public static int utimensat (int dirfd, string pathname, Timespec[] times, AtFlags flags)
3992                 {
3993                         if (times != null && times.Length != 2) {
3994                                 SetLastError (Errno.EINVAL);
3995                                 return -1;
3996                         }
3997                         int _flags = NativeConvert.FromAtFlags (flags);
3998                         return sys_utimensat (dirfd, pathname, times, _flags);
3999                 }
4000
4001                 // mkdirat(2)
4002                 //    int mkdirat(int dirfd, const char *pathname, mode_t mode);
4003                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkdirat")]
4004                 private static extern int sys_mkdirat (int dirfd,
4005                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4006                                 string oldpath, uint mode);
4007
4008                 public static int mkdirat (int dirfd, string oldpath, FilePermissions mode)
4009                 {
4010                         uint _mode = NativeConvert.FromFilePermissions (mode);
4011                         return sys_mkdirat (dirfd, oldpath, _mode);
4012                 }
4013
4014                 // mknodat(2)
4015                 //    int mknodat (int dirfd, const char *pathname, mode_t mode, dev_t dev);
4016                 [DllImport (MPH, SetLastError=true,
4017                                 EntryPoint="Mono_Posix_Syscall_mknodat")]
4018                 public static extern int mknodat (int dirfd,
4019                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4020                                 string pathname, FilePermissions mode, ulong dev);
4021
4022                 // mkfifoat(3)
4023                 //    int mkfifoat(int dirfd, const char *pathname, mode_t mode);
4024                 [DllImport (LIBC, SetLastError=true, EntryPoint="mkfifoat")]
4025                 private static extern int sys_mkfifoat (int dirfd,
4026                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4027                                 string pathname, uint mode);
4028
4029                 public static int mkfifoat (int dirfd, string pathname, FilePermissions mode)
4030                 {
4031                         uint _mode = NativeConvert.FromFilePermissions (mode);
4032                         return sys_mkfifoat (dirfd, pathname, _mode);
4033                 }
4034                 #endregion
4035
4036                 #region <sys/stat.h> Declarations
4037                 //
4038                 // <sys/statvfs.h>
4039                 //
4040
4041                 [DllImport (MPH, SetLastError=true,
4042                                 EntryPoint="Mono_Posix_Syscall_statvfs")]
4043                 public static extern int statvfs (
4044                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4045                                 string path, out Statvfs buf);
4046
4047                 [DllImport (MPH, SetLastError=true,
4048                                 EntryPoint="Mono_Posix_Syscall_fstatvfs")]
4049                 public static extern int fstatvfs (int fd, out Statvfs buf);
4050
4051                 #endregion
4052
4053                 #region <sys/time.h> Declarations
4054                 //
4055                 // <sys/time.h>
4056                 //
4057                 // TODO: adjtime(), getitimer(2), setitimer(2)
4058
4059                 [DllImport (MPH, SetLastError=true, 
4060                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
4061                 public static extern int gettimeofday (out Timeval tv, out Timezone tz);
4062
4063                 [DllImport (MPH, SetLastError=true,
4064                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
4065                 private static extern int gettimeofday (out Timeval tv, IntPtr ignore);
4066
4067                 public static int gettimeofday (out Timeval tv)
4068                 {
4069                         return gettimeofday (out tv, IntPtr.Zero);
4070                 }
4071
4072                 [DllImport (MPH, SetLastError=true,
4073                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
4074                 private static extern int gettimeofday (IntPtr ignore, out Timezone tz);
4075
4076                 public static int gettimeofday (out Timezone tz)
4077                 {
4078                         return gettimeofday (IntPtr.Zero, out tz);
4079                 }
4080
4081                 [DllImport (MPH, SetLastError=true,
4082                                 EntryPoint="Mono_Posix_Syscall_settimeofday")]
4083                 public static extern int settimeofday (ref Timeval tv, ref Timezone tz);
4084
4085                 [DllImport (MPH, SetLastError=true,
4086                                 EntryPoint="Mono_Posix_Syscall_gettimeofday")]
4087                 private static extern int settimeofday (ref Timeval tv, IntPtr ignore);
4088
4089                 public static int settimeofday (ref Timeval tv)
4090                 {
4091                         return settimeofday (ref tv, IntPtr.Zero);
4092                 }
4093
4094                 [DllImport (MPH, SetLastError=true, 
4095                                 EntryPoint="Mono_Posix_Syscall_utimes")]
4096                 private static extern int sys_utimes (
4097                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4098                                 string filename, Timeval[] tvp);
4099
4100                 public static int utimes (string filename, Timeval[] tvp)
4101                 {
4102                         if (tvp != null && tvp.Length != 2) {
4103                                 SetLastError (Errno.EINVAL);
4104                                 return -1;
4105                         }
4106                         return sys_utimes (filename, tvp);
4107                 }
4108
4109                 [DllImport (MPH, SetLastError=true, 
4110                                 EntryPoint="Mono_Posix_Syscall_lutimes")]
4111                 private static extern int sys_lutimes (
4112                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4113                                 string filename, Timeval[] tvp);
4114
4115                 public static int lutimes (string filename, Timeval[] tvp)
4116                 {
4117                         if (tvp != null && tvp.Length != 2) {
4118                                 SetLastError (Errno.EINVAL);
4119                                 return -1;
4120                         }
4121                         return sys_lutimes (filename, tvp);
4122                 }
4123
4124                 [DllImport (MPH, SetLastError=true, 
4125                                 EntryPoint="Mono_Posix_Syscall_futimes")]
4126                 private static extern int sys_futimes (int fd, Timeval[] tvp);
4127
4128                 public static int futimes (int fd, Timeval[] tvp)
4129                 {
4130                         if (tvp != null && tvp.Length != 2) {
4131                                 SetLastError (Errno.EINVAL);
4132                                 return -1;
4133                         }
4134                         return sys_futimes (fd, tvp);
4135                 }
4136
4137                 #endregion
4138
4139                 //
4140                 // <sys/timeb.h>
4141                 //
4142
4143                 // TODO: ftime(3)
4144
4145                 //
4146                 // <sys/times.h>
4147                 //
4148
4149                 // TODO: times(2)
4150
4151                 //
4152                 // <sys/utsname.h>
4153                 //
4154
4155                 [Map]
4156                 private struct _Utsname
4157                 {
4158                         public IntPtr sysname;
4159                         public IntPtr nodename;
4160                         public IntPtr release;
4161                         public IntPtr version;
4162                         public IntPtr machine;
4163                         public IntPtr domainname;
4164                         public IntPtr _buf_;
4165                 }
4166
4167                 private static void CopyUtsname (ref Utsname to, ref _Utsname from)
4168                 {
4169                         try {
4170                                 to = new Utsname ();
4171                                 to.sysname     = UnixMarshal.PtrToString (from.sysname);
4172                                 to.nodename    = UnixMarshal.PtrToString (from.nodename);
4173                                 to.release     = UnixMarshal.PtrToString (from.release);
4174                                 to.version     = UnixMarshal.PtrToString (from.version);
4175                                 to.machine     = UnixMarshal.PtrToString (from.machine);
4176                                 to.domainname  = UnixMarshal.PtrToString (from.domainname);
4177                         }
4178                         finally {
4179                                 Stdlib.free (from._buf_);
4180                                 from._buf_ = IntPtr.Zero;
4181                         }
4182                 }
4183
4184                 [DllImport (MPH, SetLastError=true, 
4185                                 EntryPoint="Mono_Posix_Syscall_uname")]
4186                 private static extern int sys_uname (out _Utsname buf);
4187
4188                 public static int uname (out Utsname buf)
4189                 {
4190                         _Utsname _buf;
4191                         int r = sys_uname (out _buf);
4192                         buf = new Utsname ();
4193                         if (r == 0) {
4194                                 CopyUtsname (ref buf, ref _buf);
4195                         }
4196                         return r;
4197                 }
4198
4199                 #region <sys/wait.h> Declarations
4200                 //
4201                 // <sys/wait.h>
4202                 //
4203
4204                 // wait(2)
4205                 //    pid_t wait(int *status);
4206                 [DllImport (LIBC, SetLastError=true)]
4207                 public static extern int wait (out int status);
4208
4209                 // waitpid(2)
4210                 //    pid_t waitpid(pid_t pid, int *status, int options);
4211                 [DllImport (LIBC, SetLastError=true)]
4212                 private static extern int waitpid (int pid, out int status, int options);
4213
4214                 public static int waitpid (int pid, out int status, WaitOptions options)
4215                 {
4216                         int _options = NativeConvert.FromWaitOptions (options);
4217                         return waitpid (pid, out status, _options);
4218                 }
4219
4220                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFEXITED")]
4221                 private static extern int _WIFEXITED (int status);
4222
4223                 public static bool WIFEXITED (int status)
4224                 {
4225                         return _WIFEXITED (status) != 0;
4226                 }
4227
4228                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WEXITSTATUS")]
4229                 public static extern int WEXITSTATUS (int status);
4230
4231                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFSIGNALED")]
4232                 private static extern int _WIFSIGNALED (int status);
4233
4234                 public static bool WIFSIGNALED (int status)
4235                 {
4236                         return _WIFSIGNALED (status) != 0;
4237                 }
4238
4239                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WTERMSIG")]
4240                 private static extern int _WTERMSIG (int status);
4241
4242                 public static Signum WTERMSIG (int status)
4243                 {
4244                         int r = _WTERMSIG (status);
4245                         return NativeConvert.ToSignum (r);
4246                 }
4247
4248                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WIFSTOPPED")]
4249                 private static extern int _WIFSTOPPED (int status);
4250
4251                 public static bool WIFSTOPPED (int status)
4252                 {
4253                         return _WIFSTOPPED (status) != 0;
4254                 }
4255
4256                 [DllImport (MPH, EntryPoint="Mono_Posix_Syscall_WSTOPSIG")]
4257                 private static extern int _WSTOPSIG (int status);
4258
4259                 public static Signum WSTOPSIG (int status)
4260                 {
4261                         int r = _WSTOPSIG (status);
4262                         return NativeConvert.ToSignum (r);
4263                 }
4264
4265                 //
4266                 // <termios.h>
4267                 //
4268
4269                 #endregion
4270
4271                 #region <syslog.h> Declarations
4272                 //
4273                 // <syslog.h>
4274                 //
4275
4276                 [DllImport (MPH, SetLastError=true,
4277                                 EntryPoint="Mono_Posix_Syscall_openlog")]
4278                 private static extern int sys_openlog (IntPtr ident, int option, int facility);
4279
4280                 public static int openlog (IntPtr ident, SyslogOptions option, 
4281                                 SyslogFacility defaultFacility)
4282                 {
4283                         int _option   = NativeConvert.FromSyslogOptions (option);
4284                         int _facility = NativeConvert.FromSyslogFacility (defaultFacility);
4285
4286                         return sys_openlog (ident, _option, _facility);
4287                 }
4288
4289                 [DllImport (MPH, SetLastError=true,
4290                                 EntryPoint="Mono_Posix_Syscall_syslog")]
4291                 private static extern int sys_syslog (int priority, string message);
4292
4293                 public static int syslog (SyslogFacility facility, SyslogLevel level, string message)
4294                 {
4295                         int _facility = NativeConvert.FromSyslogFacility (facility);
4296                         int _level = NativeConvert.FromSyslogLevel (level);
4297                         return sys_syslog (_facility | _level, GetSyslogMessage (message));
4298                 }
4299
4300                 public static int syslog (SyslogLevel level, string message)
4301                 {
4302                         int _level = NativeConvert.FromSyslogLevel (level);
4303                         return sys_syslog (_level, GetSyslogMessage (message));
4304                 }
4305
4306                 private static string GetSyslogMessage (string message)
4307                 {
4308                         return UnixMarshal.EscapeFormatString (message, new char[]{'m'});
4309                 }
4310
4311                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
4312                                 "Use syslog(SyslogFacility, SyslogLevel, string) instead.")]
4313                 public static int syslog (SyslogFacility facility, SyslogLevel level, 
4314                                 string format, params object[] parameters)
4315                 {
4316                         int _facility = NativeConvert.FromSyslogFacility (facility);
4317                         int _level = NativeConvert.FromSyslogLevel (level);
4318
4319                         object[] _parameters = new object[checked(parameters.Length+2)];
4320                         _parameters [0] = _facility | _level;
4321                         _parameters [1] = format;
4322                         Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
4323                         return (int) XPrintfFunctions.syslog (_parameters);
4324                 }
4325
4326                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
4327                                 "Use syslog(SyslogLevel, string) instead.")]
4328                 public static int syslog (SyslogLevel level, string format, 
4329                                 params object[] parameters)
4330                 {
4331                         int _level = NativeConvert.FromSyslogLevel (level);
4332
4333                         object[] _parameters = new object[checked(parameters.Length+2)];
4334                         _parameters [0] = _level;
4335                         _parameters [1] = format;
4336                         Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
4337                         return (int) XPrintfFunctions.syslog (_parameters);
4338                 }
4339
4340                 [DllImport (MPH, SetLastError=true,
4341                                 EntryPoint="Mono_Posix_Syscall_closelog")]
4342                 public static extern int closelog ();
4343
4344                 [DllImport (LIBC, SetLastError=true, EntryPoint="setlogmask")]
4345                 private static extern int sys_setlogmask (int mask);
4346
4347                 public static int setlogmask (SyslogLevel mask)
4348                 {
4349                         int _mask = NativeConvert.FromSyslogLevel (mask);
4350                         return sys_setlogmask (_mask);
4351                 }
4352
4353                 #endregion
4354
4355                 #region <time.h> Declarations
4356
4357                 //
4358                 // <time.h>
4359                 //
4360
4361                 // nanosleep(2)
4362                 //    int nanosleep(const struct timespec *req, struct timespec *rem);
4363                 [DllImport (MPH, SetLastError=true,
4364                                 EntryPoint="Mono_Posix_Syscall_nanosleep")]
4365                 public static extern int nanosleep (ref Timespec req, ref Timespec rem);
4366
4367                 // stime(2)
4368                 //    int stime(time_t *t);
4369                 [DllImport (MPH, SetLastError=true,
4370                                 EntryPoint="Mono_Posix_Syscall_stime")]
4371                 public static extern int stime (ref long t);
4372
4373                 // time(2)
4374                 //    time_t time(time_t *t);
4375                 [DllImport (MPH, SetLastError=true,
4376                                 EntryPoint="Mono_Posix_Syscall_time")]
4377                 public static extern long time (out long t);
4378
4379                 //
4380                 // <ulimit.h>
4381                 //
4382
4383                 // TODO: ulimit(3)
4384
4385                 #endregion
4386
4387                 #region <unistd.h> Declarations
4388                 //
4389                 // <unistd.h>
4390                 //
4391                 // TODO: euidaccess(), usleep(3), get_current_dir_name(), group_member(),
4392                 //       other TODOs listed below.
4393
4394                 [DllImport (LIBC, SetLastError=true, EntryPoint="access")]
4395                 private static extern int sys_access (
4396                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4397                                 string pathname, int mode);
4398
4399                 public static int access (string pathname, AccessModes mode)
4400                 {
4401                         int _mode = NativeConvert.FromAccessModes (mode);
4402                         return sys_access (pathname, _mode);
4403                 }
4404
4405                 // lseek(2)
4406                 //    off_t lseek(int filedes, off_t offset, int whence);
4407                 [DllImport (MPH, SetLastError=true, 
4408                                 EntryPoint="Mono_Posix_Syscall_lseek")]
4409                 private static extern long sys_lseek (int fd, long offset, int whence);
4410
4411                 public static long lseek (int fd, long offset, SeekFlags whence)
4412                 {
4413                         short _whence = NativeConvert.FromSeekFlags (whence);
4414                         return sys_lseek (fd, offset, _whence);
4415                 }
4416
4417     [DllImport (LIBC, SetLastError=true)]
4418                 public static extern int close (int fd);
4419
4420                 // read(2)
4421                 //    ssize_t read(int fd, void *buf, size_t count);
4422                 [DllImport (MPH, SetLastError=true, 
4423                                 EntryPoint="Mono_Posix_Syscall_read")]
4424                 public static extern long read (int fd, IntPtr buf, ulong count);
4425
4426                 public static unsafe long read (int fd, void *buf, ulong count)
4427                 {
4428                         return read (fd, (IntPtr) buf, count);
4429                 }
4430
4431                 // write(2)
4432                 //    ssize_t write(int fd, const void *buf, size_t count);
4433                 [DllImport (MPH, SetLastError=true, 
4434                                 EntryPoint="Mono_Posix_Syscall_write")]
4435                 public static extern long write (int fd, IntPtr buf, ulong count);
4436
4437                 public static unsafe long write (int fd, void *buf, ulong count)
4438                 {
4439                         return write (fd, (IntPtr) buf, count);
4440                 }
4441
4442                 // pread(2)
4443                 //    ssize_t pread(int fd, void *buf, size_t count, off_t offset);
4444                 [DllImport (MPH, SetLastError=true, 
4445                                 EntryPoint="Mono_Posix_Syscall_pread")]
4446                 public static extern long pread (int fd, IntPtr buf, ulong count, long offset);
4447
4448                 public static unsafe long pread (int fd, void *buf, ulong count, long offset)
4449                 {
4450                         return pread (fd, (IntPtr) buf, count, offset);
4451                 }
4452
4453                 // pwrite(2)
4454                 //    ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
4455                 [DllImport (MPH, SetLastError=true, 
4456                                 EntryPoint="Mono_Posix_Syscall_pwrite")]
4457                 public static extern long pwrite (int fd, IntPtr buf, ulong count, long offset);
4458
4459                 public static unsafe long pwrite (int fd, void *buf, ulong count, long offset)
4460                 {
4461                         return pwrite (fd, (IntPtr) buf, count, offset);
4462                 }
4463
4464                 [DllImport (MPH, SetLastError=true, 
4465                                 EntryPoint="Mono_Posix_Syscall_pipe")]
4466                 public static extern int pipe (out int reading, out int writing);
4467
4468                 public static int pipe (int[] filedes)
4469                 {
4470                         if (filedes == null || filedes.Length != 2) {
4471                                 // TODO: set errno
4472                                 return -1;
4473                         }
4474                         int reading, writing;
4475                         int r = pipe (out reading, out writing);
4476                         filedes[0] = reading;
4477                         filedes[1] = writing;
4478                         return r;
4479                 }
4480
4481                 [DllImport (LIBC, SetLastError=true)]
4482                 public static extern uint alarm (uint seconds);
4483
4484                 [DllImport (LIBC, SetLastError=true)]
4485                 public static extern uint sleep (uint seconds);
4486
4487                 [DllImport (LIBC, SetLastError=true)]
4488                 public static extern uint ualarm (uint usecs, uint interval);
4489
4490                 [DllImport (LIBC, SetLastError=true)]
4491                 public static extern int pause ();
4492
4493                 // chown(2)
4494                 //    int chown(const char *path, uid_t owner, gid_t group);
4495                 [DllImport (LIBC, SetLastError=true)]
4496                 public static extern int chown (
4497                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4498                                 string path, uint owner, uint group);
4499
4500                 // fchown(2)
4501                 //    int fchown(int fd, uid_t owner, gid_t group);
4502                 [DllImport (LIBC, SetLastError=true)]
4503                 public static extern int fchown (int fd, uint owner, uint group);
4504
4505                 // lchown(2)
4506                 //    int lchown(const char *path, uid_t owner, gid_t group);
4507                 [DllImport (LIBC, SetLastError=true)]
4508                 public static extern int lchown (
4509                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4510                                 string path, uint owner, uint group);
4511
4512                 [DllImport (LIBC, SetLastError=true)]
4513                 public static extern int chdir (
4514                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4515                                 string path);
4516
4517                 [DllImport (LIBC, SetLastError=true)]
4518                 public static extern int fchdir (int fd);
4519
4520                 // getcwd(3)
4521                 //    char *getcwd(char *buf, size_t size);
4522                 [DllImport (MPH, SetLastError=true,
4523                                 EntryPoint="Mono_Posix_Syscall_getcwd")]
4524                 public static extern IntPtr getcwd ([Out] StringBuilder buf, ulong size);
4525
4526                 public static StringBuilder getcwd (StringBuilder buf)
4527                 {
4528                         getcwd (buf, (ulong) buf.Capacity);
4529                         return buf;
4530                 }
4531
4532                 // getwd(2) is deprecated; don't expose it.
4533
4534                 [DllImport (LIBC, SetLastError=true)]
4535                 public static extern int dup (int fd);
4536
4537                 [DllImport (LIBC, SetLastError=true)]
4538                 public static extern int dup2 (int fd, int fd2);
4539
4540                 // TODO: does Mono marshal arrays properly?
4541                 [DllImport (LIBC, SetLastError=true)]
4542                 public static extern int execve (
4543                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4544                                 string path, string[] argv, string[] envp);
4545
4546                 [DllImport (LIBC, SetLastError=true)]
4547                 public static extern int fexecve (int fd, string[] argv, string[] envp);
4548
4549                 [DllImport (LIBC, SetLastError=true)]
4550                 public static extern int execv (
4551                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4552                                 string path, string[] argv);
4553
4554                 // TODO: execle, execl, execlp
4555                 [DllImport (LIBC, SetLastError=true)]
4556                 public static extern int execvp (
4557                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4558                                 string path, string[] argv);
4559
4560                 [DllImport (LIBC, SetLastError=true)]
4561                 public static extern int nice (int inc);
4562
4563                 [DllImport (LIBC, SetLastError=true)]
4564                 [CLSCompliant (false)]
4565                 public static extern int _exit (int status);
4566
4567                 [DllImport (MPH, SetLastError=true,
4568                                 EntryPoint="Mono_Posix_Syscall_fpathconf")]
4569                 public static extern long fpathconf (int filedes, PathconfName name, Errno defaultError);
4570
4571                 public static long fpathconf (int filedes, PathconfName name)
4572                 {
4573                         return fpathconf (filedes, name, (Errno) 0);
4574                 }
4575
4576                 [DllImport (MPH, SetLastError=true,
4577                                 EntryPoint="Mono_Posix_Syscall_pathconf")]
4578                 public static extern long pathconf (
4579                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4580                                 string path, PathconfName name, Errno defaultError);
4581
4582                 public static long pathconf (string path, PathconfName name)
4583                 {
4584                         return pathconf (path, name, (Errno) 0);
4585                 }
4586
4587                 [DllImport (MPH, SetLastError=true,
4588                                 EntryPoint="Mono_Posix_Syscall_sysconf")]
4589                 public static extern long sysconf (SysconfName name, Errno defaultError);
4590
4591                 public static long sysconf (SysconfName name)
4592                 {
4593                         return sysconf (name, (Errno) 0);
4594                 }
4595
4596                 // confstr(3)
4597                 //    size_t confstr(int name, char *buf, size_t len);
4598                 [DllImport (MPH, SetLastError=true,
4599                                 EntryPoint="Mono_Posix_Syscall_confstr")]
4600                 public static extern ulong confstr (ConfstrName name, [Out] StringBuilder buf, ulong len);
4601
4602                 // getpid(2)
4603                 //    pid_t getpid(void);
4604                 [DllImport (LIBC, SetLastError=true)]
4605                 public static extern int getpid ();
4606
4607                 // getppid(2)
4608                 //    pid_t getppid(void);
4609                 [DllImport (LIBC, SetLastError=true)]
4610                 public static extern int getppid ();
4611
4612                 // setpgid(2)
4613                 //    int setpgid(pid_t pid, pid_t pgid);
4614                 [DllImport (LIBC, SetLastError=true)]
4615                 public static extern int setpgid (int pid, int pgid);
4616
4617                 // getpgid(2)
4618                 //    pid_t getpgid(pid_t pid);
4619                 [DllImport (LIBC, SetLastError=true)]
4620                 public static extern int getpgid (int pid);
4621
4622                 [DllImport (LIBC, SetLastError=true)]
4623                 public static extern int setpgrp ();
4624
4625                 // getpgrp(2)
4626                 //    pid_t getpgrp(void);
4627                 [DllImport (LIBC, SetLastError=true)]
4628                 public static extern int getpgrp ();
4629
4630                 // setsid(2)
4631                 //    pid_t setsid(void);
4632                 [DllImport (LIBC, SetLastError=true)]
4633                 public static extern int setsid ();
4634
4635                 // getsid(2)
4636                 //    pid_t getsid(pid_t pid);
4637                 [DllImport (LIBC, SetLastError=true)]
4638                 public static extern int getsid (int pid);
4639
4640                 // getuid(2)
4641                 //    uid_t getuid(void);
4642                 [DllImport (LIBC, SetLastError=true)]
4643                 public static extern uint getuid ();
4644
4645                 // geteuid(2)
4646                 //    uid_t geteuid(void);
4647                 [DllImport (LIBC, SetLastError=true)]
4648                 public static extern uint geteuid ();
4649
4650                 // getgid(2)
4651                 //    gid_t getgid(void);
4652                 [DllImport (LIBC, SetLastError=true)]
4653                 public static extern uint getgid ();
4654
4655                 // getegid(2)
4656                 //    gid_t getgid(void);
4657                 [DllImport (LIBC, SetLastError=true)]
4658                 public static extern uint getegid ();
4659
4660                 // getgroups(2)
4661                 //    int getgroups(int size, gid_t list[]);
4662                 [DllImport (LIBC, SetLastError=true)]
4663                 public static extern int getgroups (int size, uint[] list);
4664
4665                 public static int getgroups (uint[] list)
4666                 {
4667                         return getgroups (list.Length, list);
4668                 }
4669
4670                 // setuid(2)
4671                 //    int setuid(uid_t uid);
4672                 [DllImport (LIBC, SetLastError=true)]
4673                 public static extern int setuid (uint uid);
4674
4675                 // setreuid(2)
4676                 //    int setreuid(uid_t ruid, uid_t euid);
4677                 [DllImport (LIBC, SetLastError=true)]
4678                 public static extern int setreuid (uint ruid, uint euid);
4679
4680                 // setregid(2)
4681                 //    int setregid(gid_t ruid, gid_t euid);
4682                 [DllImport (LIBC, SetLastError=true)]
4683                 public static extern int setregid (uint rgid, uint egid);
4684
4685                 // seteuid(2)
4686                 //    int seteuid(uid_t euid);
4687                 [DllImport (LIBC, SetLastError=true)]
4688                 public static extern int seteuid (uint euid);
4689
4690                 // setegid(2)
4691                 //    int setegid(gid_t euid);
4692                 [DllImport (LIBC, SetLastError=true)]
4693                 public static extern int setegid (uint uid);
4694
4695                 // setgid(2)
4696                 //    int setgid(gid_t gid);
4697                 [DllImport (LIBC, SetLastError=true)]
4698                 public static extern int setgid (uint gid);
4699
4700                 // getresuid(2)
4701                 //    int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
4702                 [DllImport (LIBC, SetLastError=true)]
4703                 public static extern int getresuid (out uint ruid, out uint euid, out uint suid);
4704
4705                 // getresgid(2)
4706                 //    int getresgid(gid_t *ruid, gid_t *euid, gid_t *suid);
4707                 [DllImport (LIBC, SetLastError=true)]
4708                 public static extern int getresgid (out uint rgid, out uint egid, out uint sgid);
4709
4710                 // setresuid(2)
4711                 //    int setresuid(uid_t ruid, uid_t euid, uid_t suid);
4712                 [DllImport (LIBC, SetLastError=true)]
4713                 public static extern int setresuid (uint ruid, uint euid, uint suid);
4714
4715                 // setresgid(2)
4716                 //    int setresgid(gid_t ruid, gid_t euid, gid_t suid);
4717                 [DllImport (LIBC, SetLastError=true)]
4718                 public static extern int setresgid (uint rgid, uint egid, uint sgid);
4719
4720 #if false
4721                 // fork(2)
4722                 //    pid_t fork(void);
4723                 [DllImport (LIBC, SetLastError=true)]
4724                 [Obsolete ("DO NOT directly call fork(2); it bypasses essential " + 
4725                                 "shutdown code.\nUse System.Diagnostics.Process instead")]
4726                 private static extern int fork ();
4727
4728                 // vfork(2)
4729                 //    pid_t vfork(void);
4730                 [DllImport (LIBC, SetLastError=true)]
4731                 [Obsolete ("DO NOT directly call vfork(2); it bypasses essential " + 
4732                                 "shutdown code.\nUse System.Diagnostics.Process instead")]
4733                 private static extern int vfork ();
4734 #endif
4735
4736                 private static object tty_lock = new object ();
4737
4738                 [DllImport (LIBC, SetLastError=true, EntryPoint="ttyname")]
4739                 private static extern IntPtr sys_ttyname (int fd);
4740
4741                 public static string ttyname (int fd)
4742                 {
4743                         lock (tty_lock) {
4744                                 IntPtr r = sys_ttyname (fd);
4745                                 return UnixMarshal.PtrToString (r);
4746                         }
4747                 }
4748
4749                 // ttyname_r(3)
4750                 //    int ttyname_r(int fd, char *buf, size_t buflen);
4751                 [DllImport (MPH, SetLastError=true,
4752                                 EntryPoint="Mono_Posix_Syscall_ttyname_r")]
4753                 public static extern int ttyname_r (int fd, [Out] StringBuilder buf, ulong buflen);
4754
4755                 public static int ttyname_r (int fd, StringBuilder buf)
4756                 {
4757                         return ttyname_r (fd, buf, (ulong) buf.Capacity);
4758                 }
4759
4760                 [DllImport (LIBC, EntryPoint="isatty")]
4761                 private static extern int sys_isatty (int fd);
4762
4763                 public static bool isatty (int fd)
4764                 {
4765                         return sys_isatty (fd) == 1;
4766                 }
4767
4768                 [DllImport (LIBC, SetLastError=true)]
4769                 public static extern int link (
4770                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4771                                 string oldpath, 
4772                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4773                                 string newpath);
4774
4775                 [DllImport (LIBC, SetLastError=true)]
4776                 public static extern int symlink (
4777                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4778                                 string oldpath, 
4779                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4780                                 string newpath);
4781
4782                 delegate long DoReadlinkFun (byte[] target);
4783
4784                 // Helper function for readlink(string, StringBuilder) and readlinkat (int, string, StringBuilder)
4785                 static int ReadlinkIntoStringBuilder (DoReadlinkFun doReadlink, [Out] StringBuilder buf, ulong bufsiz)
4786                 {
4787                         // bufsiz > int.MaxValue can't work because StringBuilder can store only int.MaxValue chars
4788                         int bufsizInt = checked ((int) bufsiz);
4789                         var target = new byte [bufsizInt];
4790
4791                         var r = doReadlink (target);
4792                         if (r < 0)
4793                                 return checked ((int) r);
4794
4795                         buf.Length = 0;
4796                         var chars = UnixEncoding.Instance.GetChars (target, 0, checked ((int) r));
4797                         // Make sure that at more bufsiz chars are written
4798                         buf.Append (chars, 0, System.Math.Min (bufsizInt, chars.Length));
4799                         if (r == bufsizInt) {
4800                                 // may not have read full contents; fill 'buf' so that caller can properly check
4801                                 buf.Append (new string ('\x00', bufsizInt - buf.Length));
4802                         }
4803                         return buf.Length;
4804                 }
4805
4806                 // readlink(2)
4807                 //    ssize_t readlink(const char *path, char *buf, size_t bufsize);
4808                 public static int readlink (string path, [Out] StringBuilder buf, ulong bufsiz)
4809                 {
4810                         return ReadlinkIntoStringBuilder (target => readlink (path, target), buf, bufsiz);
4811                 }
4812
4813                 public static int readlink (string path, [Out] StringBuilder buf)
4814                 {
4815                         return readlink (path, buf, (ulong) buf.Capacity);
4816                 }
4817
4818                 [DllImport (MPH, SetLastError=true,
4819                                 EntryPoint="Mono_Posix_Syscall_readlink")]
4820                 private static extern long readlink (
4821                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4822                                 string path, byte[] buf, ulong bufsiz);
4823
4824                 public static long readlink (string path, byte[] buf)
4825                 {
4826                         return readlink (path, buf, (ulong) buf.LongLength);
4827                 }
4828
4829                 [DllImport (LIBC, SetLastError=true)]
4830                 public static extern int unlink (
4831                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4832                                 string pathname);
4833
4834                 [DllImport (LIBC, SetLastError=true)]
4835                 public static extern int rmdir (
4836                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4837                                 string pathname);
4838
4839                 // tcgetpgrp(3)
4840                 //    pid_t tcgetpgrp(int fd);
4841                 [DllImport (LIBC, SetLastError=true)]
4842                 public static extern int tcgetpgrp (int fd);
4843
4844                 // tcsetpgrp(3)
4845                 //    int tcsetpgrp(int fd, pid_t pgrp);
4846                 [DllImport (LIBC, SetLastError=true)]
4847                 public static extern int tcsetpgrp (int fd, int pgrp);
4848
4849                 [DllImport (LIBC, SetLastError=true, EntryPoint="getlogin")]
4850                 private static extern IntPtr sys_getlogin ();
4851
4852                 public static string getlogin ()
4853                 {
4854                         lock (getlogin_lock) {
4855                                 IntPtr r = sys_getlogin ();
4856                                 return UnixMarshal.PtrToString (r);
4857                         }
4858                 }
4859
4860                 // getlogin_r(3)
4861                 //    int getlogin_r(char *buf, size_t bufsize);
4862                 [DllImport (MPH, SetLastError=true,
4863                                 EntryPoint="Mono_Posix_Syscall_getlogin_r")]
4864                 public static extern int getlogin_r ([Out] StringBuilder name, ulong bufsize);
4865
4866                 public static int getlogin_r (StringBuilder name)
4867                 {
4868                         return getlogin_r (name, (ulong) name.Capacity);
4869                 }
4870
4871                 [DllImport (LIBC, SetLastError=true)]
4872                 public static extern int setlogin (string name);
4873
4874                 // gethostname(2)
4875                 //    int gethostname(char *name, size_t len);
4876                 [DllImport (MPH, SetLastError=true,
4877                                 EntryPoint="Mono_Posix_Syscall_gethostname")]
4878                 public static extern int gethostname ([Out] StringBuilder name, ulong len);
4879
4880                 public static int gethostname (StringBuilder name)
4881                 {
4882                         return gethostname (name, (ulong) name.Capacity);
4883                 }
4884
4885                 // sethostname(2)
4886                 //    int gethostname(const char *name, size_t len);
4887                 [DllImport (MPH, SetLastError=true,
4888                                 EntryPoint="Mono_Posix_Syscall_sethostname")]
4889                 public static extern int sethostname (string name, ulong len);
4890
4891                 public static int sethostname (string name)
4892                 {
4893                         return sethostname (name, (ulong) name.Length);
4894                 }
4895
4896                 [DllImport (MPH, SetLastError=true,
4897                                 EntryPoint="Mono_Posix_Syscall_gethostid")]
4898                 public static extern long gethostid ();
4899
4900                 [DllImport (MPH, SetLastError=true,
4901                                 EntryPoint="Mono_Posix_Syscall_sethostid")]
4902                 public static extern int sethostid (long hostid);
4903
4904                 // getdomainname(2)
4905                 //    int getdomainname(char *name, size_t len);
4906                 [DllImport (MPH, SetLastError=true,
4907                                 EntryPoint="Mono_Posix_Syscall_getdomainname")]
4908                 public static extern int getdomainname ([Out] StringBuilder name, ulong len);
4909
4910                 public static int getdomainname (StringBuilder name)
4911                 {
4912                         return getdomainname (name, (ulong) name.Capacity);
4913                 }
4914
4915                 // setdomainname(2)
4916                 //    int setdomainname(const char *name, size_t len);
4917                 [DllImport (MPH, SetLastError=true,
4918                                 EntryPoint="Mono_Posix_Syscall_setdomainname")]
4919                 public static extern int setdomainname (string name, ulong len);
4920
4921                 public static int setdomainname (string name)
4922                 {
4923                         return setdomainname (name, (ulong) name.Length);
4924                 }
4925
4926                 [DllImport (LIBC, SetLastError=true)]
4927                 public static extern int vhangup ();
4928
4929                 // Revoke doesn't appear to be POSIX.  Include it?
4930                 [DllImport (LIBC, SetLastError=true)]
4931                 public static extern int revoke (
4932                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4933                                 string file);
4934
4935                 // TODO: profil?  It's not POSIX.
4936
4937                 [DllImport (LIBC, SetLastError=true)]
4938                 public static extern int acct (
4939                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4940                                 string filename);
4941
4942                 [DllImport (LIBC, SetLastError=true, EntryPoint="getusershell")]
4943                 private static extern IntPtr sys_getusershell ();
4944
4945                 internal static object usershell_lock = new object ();
4946
4947                 public static string getusershell ()
4948                 {
4949                         lock (usershell_lock) {
4950                                 IntPtr r = sys_getusershell ();
4951                                 return UnixMarshal.PtrToString (r);
4952                         }
4953                 }
4954
4955                 [DllImport (MPH, SetLastError=true, 
4956                                 EntryPoint="Mono_Posix_Syscall_setusershell")]
4957                 private static extern int sys_setusershell ();
4958
4959                 public static int setusershell ()
4960                 {
4961                         lock (usershell_lock) {
4962                                 return sys_setusershell ();
4963                         }
4964                 }
4965
4966                 [DllImport (MPH, SetLastError=true, 
4967                                 EntryPoint="Mono_Posix_Syscall_endusershell")]
4968                 private static extern int sys_endusershell ();
4969
4970                 public static int endusershell ()
4971                 {
4972                         lock (usershell_lock) {
4973                                 return sys_endusershell ();
4974                         }
4975                 }
4976
4977 #if false
4978                 [DllImport (LIBC, SetLastError=true)]
4979                 private static extern int daemon (int nochdir, int noclose);
4980
4981                 // this implicitly forks, and thus isn't safe.
4982                 private static int daemon (bool nochdir, bool noclose)
4983                 {
4984                         return daemon (nochdir ? 1 : 0, noclose ? 1 : 0);
4985                 }
4986 #endif
4987
4988                 [DllImport (LIBC, SetLastError=true)]
4989                 public static extern int chroot (
4990                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
4991                                 string path);
4992
4993                 // skipping getpass(3) as the man page states:
4994                 //   This function is obsolete.  Do not use it.
4995
4996                 [DllImport (LIBC, SetLastError=true)]
4997                 public static extern int fsync (int fd);
4998
4999                 [DllImport (LIBC, SetLastError=true)]
5000                 public static extern int fdatasync (int fd);
5001
5002                 [DllImport (MPH, SetLastError=true,
5003                                 EntryPoint="Mono_Posix_Syscall_sync")]
5004                 public static extern int sync ();
5005
5006                 [DllImport (LIBC, SetLastError=true)]
5007                 [Obsolete ("Dropped in POSIX 1003.1-2001.  " +
5008                                 "Use Syscall.sysconf (SysconfName._SC_PAGESIZE).")]
5009                 public static extern int getpagesize ();
5010
5011                 // truncate(2)
5012                 //    int truncate(const char *path, off_t length);
5013                 [DllImport (MPH, SetLastError=true, 
5014                                 EntryPoint="Mono_Posix_Syscall_truncate")]
5015                 public static extern int truncate (
5016                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5017                                 string path, long length);
5018
5019                 // ftruncate(2)
5020                 //    int ftruncate(int fd, off_t length);
5021                 [DllImport (MPH, SetLastError=true, 
5022                                 EntryPoint="Mono_Posix_Syscall_ftruncate")]
5023                 public static extern int ftruncate (int fd, long length);
5024
5025                 [DllImport (LIBC, SetLastError=true)]
5026                 public static extern int getdtablesize ();
5027
5028                 [DllImport (LIBC, SetLastError=true)]
5029                 public static extern int brk (IntPtr end_data_segment);
5030
5031                 [DllImport (LIBC, SetLastError=true)]
5032                 public static extern IntPtr sbrk (IntPtr increment);
5033
5034                 // TODO: syscall(2)?
5035                 // Probably safer to skip entirely.
5036
5037                 // lockf(3)
5038                 //    int lockf(int fd, int cmd, off_t len);
5039                 [DllImport (MPH, SetLastError=true, 
5040                                 EntryPoint="Mono_Posix_Syscall_lockf")]
5041                 public static extern int lockf (int fd, LockfCommand cmd, long len);
5042
5043                 [Obsolete ("This is insecure and should not be used", true)]
5044                 public static string crypt (string key, string salt)
5045                 {
5046                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
5047                 }
5048
5049                 [Obsolete ("This is insecure and should not be used", true)]
5050                 public static int encrypt (byte[] block, bool decode)
5051                 {
5052                         throw new SecurityException ("crypt(3) has been broken.  Use something more secure.");
5053                 }
5054
5055                 // swab(3)
5056                 //    void swab(const void *from, void *to, ssize_t n);
5057                 [DllImport (MPH, SetLastError=true, 
5058                                 EntryPoint="Mono_Posix_Syscall_swab")]
5059                 public static extern int swab (IntPtr from, IntPtr to, long n);
5060
5061                 public static unsafe void swab (void* from, void* to, long n)
5062                 {
5063                         swab ((IntPtr) from, (IntPtr) to, n);
5064                 }
5065
5066                 [DllImport (LIBC, SetLastError=true, EntryPoint="faccessat")]
5067                 private static extern int sys_faccessat (int dirfd,
5068                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5069                                 string pathname, int mode, int flags);
5070
5071                 public static int faccessat (int dirfd, string pathname, AccessModes mode, AtFlags flags)
5072                 {
5073                         int _mode = NativeConvert.FromAccessModes (mode);
5074                         int _flags = NativeConvert.FromAtFlags (flags);
5075                         return sys_faccessat (dirfd, pathname, _mode, _flags);
5076                 }
5077
5078                 // fchownat(2)
5079                 //    int fchownat(int dirfd, const char *path, uid_t owner, gid_t group, int flags);
5080                 [DllImport (LIBC, SetLastError=true, EntryPoint="fchownat")]
5081                 private static extern int sys_fchownat (int dirfd,
5082                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5083                                 string pathname, uint owner, uint group, int flags);
5084
5085                 public static int fchownat (int dirfd, string pathname, uint owner, uint group, AtFlags flags)
5086                 {
5087                         int _flags = NativeConvert.FromAtFlags (flags);
5088                         return sys_fchownat (dirfd, pathname, owner, group, _flags);
5089                 }
5090
5091                 [DllImport (LIBC, SetLastError=true, EntryPoint="linkat")]
5092                 private static extern int sys_linkat (int olddirfd,
5093                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5094                                 string oldpath, int newdirfd,
5095                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5096                                 string newpath, int flags);
5097
5098                 public static int linkat (int olddirfd, string oldpath, int newdirfd, string newpath, AtFlags flags)
5099                 {
5100                         int _flags = NativeConvert.FromAtFlags (flags);
5101                         return sys_linkat (olddirfd, oldpath, newdirfd, newpath, _flags);
5102                 }
5103
5104                 // readlinkat(2)
5105                 //    ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsize);
5106                 public static int readlinkat (int dirfd, string pathname, [Out] StringBuilder buf, ulong bufsiz)
5107                 {
5108                         return ReadlinkIntoStringBuilder (target => readlinkat (dirfd, pathname, target), buf, bufsiz);
5109                 }
5110
5111                 public static int readlinkat (int dirfd, string pathname, [Out] StringBuilder buf)
5112                 {
5113                         return readlinkat (dirfd, pathname, buf, (ulong) buf.Capacity);
5114                 }
5115
5116                 [DllImport (MPH, SetLastError=true,
5117                                 EntryPoint="Mono_Posix_Syscall_readlinkat")]
5118                 private static extern long readlinkat (int dirfd,
5119                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5120                                 string pathname, byte[] buf, ulong bufsiz);
5121
5122                 public static long readlinkat (int dirfd, string pathname, byte[] buf)
5123                 {
5124                         return readlinkat (dirfd, pathname, buf, (ulong) buf.LongLength);
5125                 }
5126
5127                 [DllImport (LIBC, SetLastError=true)]
5128                 public static extern int symlinkat (
5129                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5130                                 string oldpath, int dirfd,
5131                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5132                                 string newpath);
5133
5134                 [DllImport (LIBC, SetLastError=true, EntryPoint="unlinkat")]
5135                 private static extern int sys_unlinkat (int dirfd,
5136                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5137                                 string pathname, int flags);
5138
5139                 public static int unlinkat (int dirfd, string pathname, AtFlags flags)
5140                 {
5141                         int _flags = NativeConvert.FromAtFlags (flags);
5142                         return sys_unlinkat (dirfd, pathname, _flags);
5143                 }
5144                 #endregion
5145
5146                 #region <utime.h> Declarations
5147                 //
5148                 // <utime.h>  -- COMPLETE
5149                 //
5150
5151                 [DllImport (MPH, SetLastError=true, 
5152                                 EntryPoint="Mono_Posix_Syscall_utime")]
5153                 private static extern int sys_utime (
5154                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
5155                                 string filename, ref Utimbuf buf, int use_buf);
5156
5157                 public static int utime (string filename, ref Utimbuf buf)
5158                 {
5159                         return sys_utime (filename, ref buf, 1);
5160                 }
5161
5162                 public static int utime (string filename)
5163                 {
5164                         Utimbuf buf = new Utimbuf ();
5165                         return sys_utime (filename, ref buf, 0);
5166                 }
5167                 #endregion
5168
5169                 #region <sys/uio.h> Declarations
5170                 //
5171                 // <sys/uio.h> -- COMPLETE
5172                 //
5173
5174                 // readv(2)
5175                 //    ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
5176                 [DllImport (MPH, SetLastError=true,
5177                                 EntryPoint="Mono_Posix_Syscall_readv")]
5178                 private static extern long sys_readv (int fd, Iovec[] iov, int iovcnt);
5179
5180                 public static long readv (int fd, Iovec[] iov)
5181                 {
5182                         return sys_readv (fd, iov, iov.Length);
5183                 }
5184
5185                 // writev(2)
5186                 //    ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
5187                 [DllImport (MPH, SetLastError=true,
5188                                 EntryPoint="Mono_Posix_Syscall_writev")]
5189                 private static extern long sys_writev (int fd, Iovec[] iov, int iovcnt);
5190
5191                 public static long writev (int fd, Iovec[] iov)
5192                 {
5193                         return sys_writev (fd, iov, iov.Length);
5194                 }
5195
5196                 // preadv(2)
5197                 //    ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset);
5198                 [DllImport (MPH, SetLastError=true,
5199                                 EntryPoint="Mono_Posix_Syscall_preadv")]
5200                 private static extern long sys_preadv (int fd, Iovec[] iov, int iovcnt, long offset);
5201
5202                 public static long preadv (int fd, Iovec[] iov, long offset)
5203                 {
5204                         return sys_preadv (fd, iov, iov.Length, offset);
5205                 }
5206
5207                 // pwritev(2)
5208                 //    ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset);
5209                 [DllImport (MPH, SetLastError=true,
5210                                 EntryPoint="Mono_Posix_Syscall_pwritev")]
5211                 private static extern long sys_pwritev (int fd, Iovec[] iov, int iovcnt, long offset);
5212
5213                 public static long pwritev (int fd, Iovec[] iov, long offset)
5214                 {
5215                         return sys_pwritev (fd, iov, iov.Length, offset);
5216                 }
5217                 #endregion
5218
5219                 #region <arpa/inet.h> Declarations
5220                 //
5221                 // <arpa/inet.h>
5222                 //
5223
5224                 // htonl(3)
5225                 //    uint32_t htonl(uint32_t hostlong);
5226                 [DllImport (LIBC)]
5227                 public static extern uint htonl(uint hostlong);
5228
5229                 // htons(3)
5230                 //    uint16_t htons(uint16_t hostshort);
5231                 [DllImport (LIBC)]
5232                 public static extern ushort htons(ushort hostshort);
5233
5234                 // ntohl(3)
5235                 //    uint32_t ntohl(uint32_t netlong);
5236                 [DllImport (LIBC)]
5237                 public static extern uint ntohl(uint netlong);
5238
5239                 // ntohs(3)
5240                 //    uint16_t ntohs(uint16_t netshort);
5241                 [DllImport (LIBC)]
5242                 public static extern ushort ntohs(ushort netshort);
5243
5244                 #endregion
5245
5246                 #region <socket.h> Declarations
5247                 //
5248                 // <socket.h>
5249                 //
5250
5251                 // socket(2)
5252                 //    int socket(int domain, int type, int protocol);
5253                 [DllImport (LIBC, SetLastError=true, 
5254                                 EntryPoint="socket")]
5255                 static extern int sys_socket (int domain, int type, int protocol);
5256
5257                 public static int socket (UnixAddressFamily domain, UnixSocketType type, UnixSocketFlags flags, UnixSocketProtocol protocol)
5258                 {
5259                         var _domain = NativeConvert.FromUnixAddressFamily (domain);
5260                         var _type = NativeConvert.FromUnixSocketType (type);
5261                         var _flags = NativeConvert.FromUnixSocketFlags (flags);
5262                         // protocol == 0 is a special case (uses default protocol)
5263                         var _protocol = protocol == 0 ? 0 : NativeConvert.FromUnixSocketProtocol (protocol);
5264
5265                         return sys_socket (_domain, _type | _flags, _protocol);
5266                 }
5267
5268                 public static int socket (UnixAddressFamily domain, UnixSocketType type, UnixSocketProtocol protocol)
5269                 {
5270                         return socket (domain, type, 0, protocol);
5271                 }
5272
5273                 // socketpair(2)
5274                 //    int socketpair(int domain, int type, int protocol, int sv[2]);
5275                 [DllImport (MPH, SetLastError=true, 
5276                                 EntryPoint="Mono_Posix_Syscall_socketpair")]
5277                 static extern int sys_socketpair (int domain, int type, int protocol, out int socket1, out int socket2);
5278
5279                 public static int socketpair (UnixAddressFamily domain, UnixSocketType type, UnixSocketFlags flags, UnixSocketProtocol protocol, out int socket1, out int socket2)
5280                 {
5281                         var _domain = NativeConvert.FromUnixAddressFamily (domain);
5282                         var _type = NativeConvert.FromUnixSocketType (type);
5283                         var _flags = NativeConvert.FromUnixSocketFlags (flags);
5284                         // protocol == 0 is a special case (uses default protocol)
5285                         var _protocol = protocol == 0 ? 0 : NativeConvert.FromUnixSocketProtocol (protocol);
5286
5287                         return sys_socketpair (_domain, _type | _flags, _protocol, out socket1, out socket2);
5288                 }
5289
5290                 public static int socketpair (UnixAddressFamily domain, UnixSocketType type, UnixSocketProtocol protocol, out int socket1, out int socket2)
5291                 {
5292                         return socketpair (domain, type, 0, protocol, out socket1, out socket2);
5293                 }
5294
5295                 // sockatmark(2)
5296                 //    int sockatmark(int sockfd);
5297                 [DllImport (LIBC, SetLastError=true)]
5298                 public static extern int sockatmark (int socket);
5299
5300                 // listen(2)
5301                 //    int listen(int sockfd, int backlog);
5302                 [DllImport (LIBC, SetLastError=true)]
5303                 public static extern int listen (int socket, int backlog);
5304
5305                 // getsockopt(2)
5306                 //    int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
5307                 [DllImport (MPH, SetLastError=true, 
5308                                 EntryPoint="Mono_Posix_Syscall_getsockopt")]
5309                 static extern unsafe int sys_getsockopt (int socket, int level, int option_name, void *option_value, ref long option_len);
5310
5311                 [DllImport (MPH, SetLastError=true, 
5312                                 EntryPoint="Mono_Posix_Syscall_getsockopt_timeval")]
5313                 static extern unsafe int sys_getsockopt_timeval (int socket, int level, int option_name, out Timeval option_value);
5314
5315                 [DllImport (MPH, SetLastError=true, 
5316                                 EntryPoint="Mono_Posix_Syscall_getsockopt_linger")]
5317                 static extern unsafe int sys_getsockopt_linger (int socket, int level, int option_name, out Linger option_value);
5318
5319                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, void *option_value, ref long option_len)
5320                 {
5321                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5322                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5323                         return sys_getsockopt (socket, _level, _option_name, option_value, ref option_len);
5324                 }
5325
5326                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, IntPtr option_value, ref long option_len)
5327                 {
5328                         return getsockopt (socket, level, option_name, (void*) option_value, ref option_len);
5329                 }
5330
5331                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out int option_value)
5332                 {
5333                         int value;
5334                         long size = sizeof (int);
5335                         int ret = getsockopt (socket, level, option_name, &value, ref size);
5336                         if (ret != -1 && size != sizeof (int)) {
5337                                 SetLastError (Errno.EINVAL);
5338                                 ret = -1;
5339                         }
5340                         option_value = value;
5341                         return ret;
5342                 }
5343
5344                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, byte[] option_value, ref long option_len)
5345                 {
5346                         if (option_len > (option_value == null ? 0 : option_value.Length))
5347                                 throw new ArgumentOutOfRangeException ("option_len", "option_len > (option_value == null ? 0 : option_value.Length)");
5348                         fixed (byte* ptr = option_value)
5349                                 return getsockopt (socket, level, option_name, ptr, ref option_len);
5350                 }
5351
5352                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out Timeval option_value)
5353                 {
5354                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5355                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5356                         return sys_getsockopt_timeval (socket, _level, _option_name, out option_value);
5357                 }
5358
5359                 public static unsafe int getsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, out Linger option_value)
5360                 {
5361                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5362                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5363                         return sys_getsockopt_linger (socket, _level, _option_name, out option_value);
5364                 }
5365
5366                 // setsockopt(2)
5367                 //    int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
5368                 [DllImport (MPH, SetLastError=true, 
5369                                 EntryPoint="Mono_Posix_Syscall_setsockopt")]
5370                 static extern unsafe int sys_setsockopt (int socket, int level, int option_name, void *option_value, long option_len);
5371
5372                 [DllImport (MPH, SetLastError=true, 
5373                                 EntryPoint="Mono_Posix_Syscall_setsockopt_timeval")]
5374                 static extern unsafe int sys_setsockopt_timeval (int socket, int level, int option_name, ref Timeval option_value);
5375
5376                 [DllImport (MPH, SetLastError=true, 
5377                                 EntryPoint="Mono_Posix_Syscall_setsockopt_linger")]
5378                 static extern unsafe int sys_setsockopt_linger (int socket, int level, int option_name, ref Linger option_value);
5379
5380                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, void *option_value, long option_len)
5381                 {
5382                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5383                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5384                         return sys_setsockopt (socket, _level, _option_name, option_value, option_len);
5385                 }
5386
5387                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, IntPtr option_value, long option_len)
5388                 {
5389                         return setsockopt (socket, level, option_name, (void*) option_value, option_len);
5390                 }
5391
5392                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, int option_value)
5393                 {
5394                         return setsockopt (socket, level, option_name, &option_value, sizeof (int));
5395                 }
5396
5397                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, byte[] option_value, long option_len)
5398                 {
5399                         if (option_len > (option_value == null ? 0 : option_value.Length))
5400                                 throw new ArgumentOutOfRangeException ("option_len", "option_len > (option_value == null ? 0 : option_value.Length)");
5401                         fixed (byte* ptr = option_value)
5402                                 return setsockopt (socket, level, option_name, ptr, option_len);
5403                 }
5404
5405                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, Timeval option_value)
5406                 {
5407                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5408                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5409                         return sys_setsockopt_timeval (socket, _level, _option_name, ref option_value);
5410                 }
5411
5412                 public static unsafe int setsockopt (int socket, UnixSocketProtocol level, UnixSocketOptionName option_name, Linger option_value)
5413                 {
5414                         var _level = NativeConvert.FromUnixSocketProtocol (level);
5415                         var _option_name = NativeConvert.FromUnixSocketOptionName (option_name);
5416                         return sys_setsockopt_linger (socket, _level, _option_name, ref option_value);
5417                 }
5418
5419                 // shutdown(2)
5420                 //    int shutdown(int sockfd, int how);
5421                 [DllImport (LIBC, SetLastError=true, 
5422                                 EntryPoint="shutdown")]
5423                 static extern int sys_shutdown (int socket, int how);
5424
5425                 public static int shutdown (int socket, ShutdownOption how)
5426                 {
5427                         var _how = NativeConvert.FromShutdownOption (how);
5428                         return sys_shutdown (socket, _how);
5429                 }
5430
5431                 // recv(2)
5432                 //    ssize_t recv(int sockfd, void *buf, size_t len, int flags);
5433                 [DllImport (MPH, SetLastError=true, 
5434                                 EntryPoint="Mono_Posix_Syscall_recv")]
5435                 static extern unsafe long sys_recv (int socket, void *buffer, ulong length, int flags);
5436
5437                 public static unsafe long recv (int socket, void *buffer, ulong length, MessageFlags flags)
5438                 {
5439                         int _flags = NativeConvert.FromMessageFlags (flags);
5440                         return sys_recv (socket, buffer, length, _flags);
5441                 }
5442
5443                 public static unsafe long recv (int socket, IntPtr buffer, ulong length, MessageFlags flags)
5444                 {
5445                         return recv (socket, (void*) buffer, length, flags);
5446                 }
5447
5448                 public static unsafe long recv (int socket, byte[] buffer, ulong length, MessageFlags flags)
5449                 {
5450                         if (length > (ulong) (buffer == null ? 0 : buffer.LongLength))
5451                                 throw new ArgumentOutOfRangeException ("length", "length > (buffer == null ? 0 : buffer.LongLength)");
5452                         fixed (byte* ptr = buffer)
5453                                 return recv (socket, ptr, length, flags);
5454                 }
5455
5456                 // send(2)
5457                 //    ssize_t send(int sockfd, const void *buf, size_t len, int flags);
5458                 [DllImport (MPH, SetLastError=true, 
5459                                 EntryPoint="Mono_Posix_Syscall_send")]
5460                 static extern unsafe long sys_send (int socket, void *message, ulong length, int flags);
5461
5462                 public static unsafe long send (int socket, void *message, ulong length, MessageFlags flags)
5463                 {
5464                         int _flags = NativeConvert.FromMessageFlags (flags);
5465                         return sys_send (socket, message, length, _flags);
5466                 }
5467
5468                 public static unsafe long send (int socket, IntPtr message, ulong length, MessageFlags flags)
5469                 {
5470                         return send (socket, (void*) message, length, flags);
5471                 }
5472
5473                 public static unsafe long send (int socket, byte[] message, ulong length, MessageFlags flags)
5474                 {
5475                         if (length > (ulong) (message == null ? 0 : message.LongLength))
5476                                 throw new ArgumentOutOfRangeException ("length", "length > (message == null ? 0 : message.LongLength)");
5477                         fixed (byte* ptr = message)
5478                                 return send (socket, ptr, length, flags);
5479                 }
5480
5481                 // bind(2)
5482                 //    int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
5483                 [DllImport (MPH, SetLastError=true, 
5484                                 EntryPoint="Mono_Posix_Syscall_bind")]
5485                 static extern unsafe int sys_bind (int socket, _SockaddrHeader* address);
5486
5487                 public static unsafe int bind (int socket, Sockaddr address)
5488                 {
5489                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5490                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5491                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: false);
5492                                 return sys_bind (socket, Sockaddr.GetNative (&dyn, addr));
5493                         }
5494                 }
5495
5496                 // connect(2)
5497                 //    int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
5498                 [DllImport (MPH, SetLastError=true, 
5499                                 EntryPoint="Mono_Posix_Syscall_connect")]
5500                 static extern unsafe int sys_connect (int socket, _SockaddrHeader* address);
5501
5502                 public static unsafe int connect (int socket, Sockaddr address)
5503                 {
5504                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5505                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5506                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: false);
5507                                 return sys_connect (socket, Sockaddr.GetNative (&dyn, addr));
5508                         }
5509                 }
5510
5511                 // accept(2)
5512                 //    int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
5513                 [DllImport (MPH, SetLastError=true, 
5514                                 EntryPoint="Mono_Posix_Syscall_accept")]
5515                 static extern unsafe int sys_accept (int socket, _SockaddrHeader* address);
5516
5517                 public static unsafe int accept (int socket, Sockaddr address)
5518                 {
5519                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5520                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5521                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
5522                                 int r = sys_accept (socket, Sockaddr.GetNative (&dyn, addr));
5523                                 dyn.Update (address);
5524                                 return r;
5525                         }
5526                 }
5527
5528                 // accept4(2)
5529                 //    int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);
5530                 [DllImport (MPH, SetLastError=true, 
5531                                 EntryPoint="Mono_Posix_Syscall_accept4")]
5532                 static extern unsafe int sys_accept4 (int socket, _SockaddrHeader* address, int flags);
5533
5534                 public static unsafe int accept4 (int socket, Sockaddr address, UnixSocketFlags flags)
5535                 {
5536                         var _flags = NativeConvert.FromUnixSocketFlags (flags);
5537                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5538                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5539                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
5540                                 int r = sys_accept4 (socket, Sockaddr.GetNative (&dyn, addr), _flags);
5541                                 dyn.Update (address);
5542                                 return r;
5543                         }
5544                 }
5545
5546                 // getpeername(2)
5547                 //    int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
5548                 [DllImport (MPH, SetLastError=true, 
5549                                 EntryPoint="Mono_Posix_Syscall_getpeername")]
5550                 static extern unsafe int sys_getpeername (int socket, _SockaddrHeader* address);
5551
5552                 public static unsafe int getpeername (int socket, Sockaddr address)
5553                 {
5554                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5555                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5556                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
5557                                 int r = sys_getpeername (socket, Sockaddr.GetNative (&dyn, addr));
5558                                 dyn.Update (address);
5559                                 return r;
5560                         }
5561                 }
5562
5563                 // getsockname(2)
5564                 //    int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
5565                 [DllImport (MPH, SetLastError=true, 
5566                                 EntryPoint="Mono_Posix_Syscall_getsockname")]
5567                 static extern unsafe int sys_getsockname (int socket, _SockaddrHeader* address);
5568
5569                 public static unsafe int getsockname (int socket, Sockaddr address)
5570                 {
5571                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5572                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5573                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
5574                                 int r = sys_getsockname (socket, Sockaddr.GetNative (&dyn, addr));
5575                                 dyn.Update (address);
5576                                 return r;
5577                         }
5578                 }
5579
5580                 // recvfrom(2)
5581                 //    ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);
5582                 [DllImport (MPH, SetLastError=true, 
5583                                 EntryPoint="Mono_Posix_Syscall_recvfrom")]
5584                 static extern unsafe long sys_recvfrom (int socket, void *buffer, ulong length, int flags, _SockaddrHeader* address);
5585
5586                 public static unsafe long recvfrom (int socket, void *buffer, ulong length, MessageFlags flags, Sockaddr address)
5587                 {
5588                         int _flags = NativeConvert.FromMessageFlags (flags);
5589                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5590                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5591                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: true);
5592                                 long r = sys_recvfrom (socket, buffer, length, _flags, Sockaddr.GetNative (&dyn, addr));
5593                                 dyn.Update (address);
5594                                 return r;
5595                         }
5596                 }
5597
5598                 public static unsafe long recvfrom (int socket, IntPtr buffer, ulong length, MessageFlags flags, Sockaddr address)
5599                 {
5600                         return recvfrom (socket, (void*) buffer, length, flags, address);
5601                 }
5602
5603                 public static unsafe long recvfrom (int socket, byte[] buffer, ulong length, MessageFlags flags, Sockaddr address)
5604                 {
5605                         if (length > (ulong) buffer.LongLength)
5606                                 throw new ArgumentOutOfRangeException ("length", "length > buffer.LongLength");
5607                         fixed (byte* ptr = buffer)
5608                                 return recvfrom (socket, ptr, length, flags, address);
5609                 }
5610
5611                 // sendto(2)
5612                 //    ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);
5613                 [DllImport (MPH, SetLastError=true, 
5614                                 EntryPoint="Mono_Posix_Syscall_sendto")]
5615                 static extern unsafe long sys_sendto (int socket, void *message, ulong length, int flags, _SockaddrHeader* address);
5616
5617                 public static unsafe long sendto (int socket, void *message, ulong length, MessageFlags flags, Sockaddr address)
5618                 {
5619                         int _flags = NativeConvert.FromMessageFlags (flags);
5620                         fixed (SockaddrType* addr = &Sockaddr.GetAddress (address).type)
5621                         fixed (byte* data = Sockaddr.GetDynamicData (address)) {
5622                                 var dyn = new _SockaddrDynamic (address, data, useMaxLength: false);
5623                                 return sys_sendto (socket, message, length, _flags, Sockaddr.GetNative (&dyn, addr));
5624                         }
5625                 }
5626
5627                 public static unsafe long sendto (int socket, IntPtr message, ulong length, MessageFlags flags, Sockaddr address)
5628                 {
5629                         return sendto (socket, (void*) message, length, flags, address);
5630                 }
5631
5632                 public static unsafe long sendto (int socket, byte[] message, ulong length, MessageFlags flags, Sockaddr address)
5633                 {
5634                         if (length > (ulong) message.LongLength)
5635                                 throw new ArgumentOutOfRangeException ("length", "length > message.LongLength");
5636                         fixed (byte* ptr = message)
5637                                 return sendto (socket, ptr, length, flags, address);
5638                 }
5639
5640                 #endregion
5641         }
5642
5643         #endregion
5644 }
5645
5646 // vim: noexpandtab
5647 // Local Variables: 
5648 // tab-width: 4
5649 // c-basic-offset: 4
5650 // indent-tabs-mode: t
5651 // End: