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