[boehm] Put *_freelists into thread_local_freelists (as in BDWGC v7)
[mono.git] / mcs / class / Mono.Posix / Mono.Unix.Native / Stdlib.cs
1 //
2 // Mono.Unix/Stdlib.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //
7 // (C) 2004-2006 Jonathan Pryor
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29 using System;
30 using System.Collections;
31 using System.IO;
32 using System.Runtime.InteropServices;
33 using System.Text;
34 using Mono.Unix.Native;
35
36 namespace Mono.Unix.Native {
37
38         #region Enumerations
39
40         [Map]
41         public enum Errno : int {
42                 // errors & their values liberally copied from
43                 // FC2 /usr/include/asm/errno.h
44                 
45                 EPERM           =   1, // Operation not permitted 
46                 ENOENT          =   2, // No such file or directory 
47                 ESRCH           =   3, // No such process 
48                 EINTR           =   4, // Interrupted system call 
49                 EIO             =   5, // I/O error 
50                 ENXIO           =   6, // No such device or address 
51                 E2BIG           =   7, // Arg list too long 
52                 ENOEXEC         =   8, // Exec format error 
53                 EBADF           =   9, // Bad file number 
54                 ECHILD          =  10, // No child processes 
55                 EAGAIN          =  11, // Try again 
56                 ENOMEM          =  12, // Out of memory 
57                 EACCES          =  13, // Permission denied 
58                 EFAULT          =  14, // Bad address 
59                 ENOTBLK         =  15, // Block device required 
60                 EBUSY           =  16, // Device or resource busy 
61                 EEXIST          =  17, // File exists 
62                 EXDEV           =  18, // Cross-device link 
63                 ENODEV          =  19, // No such device 
64                 ENOTDIR         =  20, // Not a directory 
65                 EISDIR          =  21, // Is a directory 
66                 EINVAL          =  22, // Invalid argument 
67                 ENFILE          =  23, // File table overflow 
68                 EMFILE          =  24, // Too many open files 
69                 ENOTTY          =  25, // Not a typewriter 
70                 ETXTBSY         =  26, // Text file busy 
71                 EFBIG           =  27, // File too large 
72                 ENOSPC          =  28, // No space left on device 
73                 ESPIPE          =  29, // Illegal seek 
74                 EROFS           =  30, // Read-only file system 
75                 EMLINK          =  31, // Too many links 
76                 EPIPE           =  32, // Broken pipe 
77                 EDOM            =  33, // Math argument out of domain of func 
78                 ERANGE          =  34, // Math result not representable 
79                 EDEADLK         =  35, // Resource deadlock would occur 
80                 ENAMETOOLONG    =  36, // File name too long 
81                 ENOLCK          =  37, // No record locks available 
82                 ENOSYS          =  38, // Function not implemented 
83                 ENOTEMPTY       =  39, // Directory not empty 
84                 ELOOP           =  40, // Too many symbolic links encountered 
85                 EWOULDBLOCK     =  EAGAIN, // Operation would block 
86                 ENOMSG          =  42, // No message of desired type 
87                 EIDRM           =  43, // Identifier removed 
88                 ECHRNG          =  44, // Channel number out of range 
89                 EL2NSYNC        =  45, // Level 2 not synchronized 
90                 EL3HLT          =  46, // Level 3 halted 
91                 EL3RST          =  47, // Level 3 reset 
92                 ELNRNG          =  48, // Link number out of range 
93                 EUNATCH         =  49, // Protocol driver not attached 
94                 ENOCSI          =  50, // No CSI structure available 
95                 EL2HLT          =  51, // Level 2 halted 
96                 EBADE           =  52, // Invalid exchange 
97                 EBADR           =  53, // Invalid request descriptor 
98                 EXFULL          =  54, // Exchange full 
99                 ENOANO          =  55, // No anode 
100                 EBADRQC         =  56, // Invalid request code 
101                 EBADSLT         =  57, // Invalid slot 
102                       
103                 EDEADLOCK             =  EDEADLK,
104                       
105                 EBFONT          =  59, // Bad font file format 
106                 ENOSTR          =  60, // Device not a stream 
107                 ENODATA         =  61, // No data available 
108                 ETIME           =  62, // Timer expired 
109                 ENOSR           =  63, // Out of streams resources 
110                 ENONET          =  64, // Machine is not on the network 
111                 ENOPKG          =  65, // Package not installed 
112                 EREMOTE         =  66, // Object is remote 
113                 ENOLINK         =  67, // Link has been severed 
114                 EADV            =  68, // Advertise error 
115                 ESRMNT          =  69, // Srmount error 
116                 ECOMM           =  70, // Communication error on send 
117                 EPROTO          =  71, // Protocol error 
118                 EMULTIHOP       =  72, // Multihop attempted 
119                 EDOTDOT         =  73, // RFS specific error 
120                 EBADMSG         =  74, // Not a data message 
121                 EOVERFLOW       =  75, // Value too large for defined data type 
122                 ENOTUNIQ        =  76, // Name not unique on network 
123                 EBADFD          =  77, // File descriptor in bad state 
124                 EREMCHG         =  78, // Remote address changed 
125                 ELIBACC         =  79, // Can not access a needed shared library 
126                 ELIBBAD         =  80, // Accessing a corrupted shared library 
127                 ELIBSCN         =  81, // .lib section in a.out corrupted 
128                 ELIBMAX         =  82, // Attempting to link in too many shared libraries 
129                 ELIBEXEC        =  83, // Cannot exec a shared library directly 
130                 EILSEQ          =  84, // Illegal byte sequence 
131                 ERESTART        =  85, // Interrupted system call should be restarted 
132                 ESTRPIPE        =  86, // Streams pipe error 
133                 EUSERS          =  87, // Too many users 
134                 ENOTSOCK        =  88, // Socket operation on non-socket 
135                 EDESTADDRREQ    =  89, // Destination address required 
136                 EMSGSIZE        =  90, // Message too long 
137                 EPROTOTYPE      =  91, // Protocol wrong type for socket 
138                 ENOPROTOOPT     =  92, // Protocol not available 
139                 EPROTONOSUPPORT =  93, // Protocol not supported 
140                 ESOCKTNOSUPPORT =  94, // Socket type not supported 
141                 EOPNOTSUPP      =  95, // Operation not supported on transport endpoint 
142                 EPFNOSUPPORT    =  96, // Protocol family not supported 
143                 EAFNOSUPPORT    =  97, // Address family not supported by protocol 
144                 EADDRINUSE      =  98, // Address already in use 
145                 EADDRNOTAVAIL   =  99, // Cannot assign requested address 
146                 ENETDOWN        = 100, // Network is down 
147                 ENETUNREACH     = 101, // Network is unreachable 
148                 ENETRESET       = 102, // Network dropped connection because of reset 
149                 ECONNABORTED    = 103, // Software caused connection abort 
150                 ECONNRESET      = 104, // Connection reset by peer 
151                 ENOBUFS         = 105, // No buffer space available 
152                 EISCONN         = 106, // Transport endpoint is already connected 
153                 ENOTCONN        = 107, // Transport endpoint is not connected 
154                 ESHUTDOWN       = 108, // Cannot send after transport endpoint shutdown 
155                 ETOOMANYREFS    = 109, // Too many references: cannot splice 
156                 ETIMEDOUT       = 110, // Connection timed out 
157                 ECONNREFUSED    = 111, // Connection refused 
158                 EHOSTDOWN       = 112, // Host is down 
159                 EHOSTUNREACH    = 113, // No route to host 
160                 EALREADY        = 114, // Operation already in progress 
161                 EINPROGRESS     = 115, // Operation now in progress 
162                 ESTALE          = 116, // Stale NFS file handle 
163                 EUCLEAN         = 117, // Structure needs cleaning 
164                 ENOTNAM         = 118, // Not a XENIX named type file 
165                 ENAVAIL         = 119, // No XENIX semaphores available 
166                 EISNAM          = 120, // Is a named type file 
167                 EREMOTEIO       = 121, // Remote I/O error 
168                 EDQUOT          = 122, // Quota exceeded 
169
170                 ENOMEDIUM       = 123, // No medium found 
171                 EMEDIUMTYPE     = 124, // Wrong medium type 
172
173                 ECANCELED       = 125,
174                 ENOKEY          = 126,
175                 EKEYEXPIRED     = 127,
176                 EKEYREVOKED     = 128,
177                 EKEYREJECTED    = 129,
178
179                 EOWNERDEAD      = 130,
180                 ENOTRECOVERABLE = 131,
181
182                 // OS X-specific values: OS X value + 1000
183                 EPROCLIM        = 1067, // Too many processes
184                 EBADRPC         = 1072, // RPC struct is bad
185                 ERPCMISMATCH    = 1073, // RPC version wrong
186                 EPROGUNAVAIL    = 1074, // RPC prog. not avail
187                 EPROGMISMATCH   = 1075, // Program version wrong
188                 EPROCUNAVAIL    = 1076, // Bad procedure for program
189                 EFTYPE          = 1079, // Inappropriate file type or format
190                 EAUTH           = 1080, // Authentication error
191                 ENEEDAUTH       = 1081, // Need authenticator
192                 EPWROFF         = 1082, // Device power is off
193                 EDEVERR         = 1083, // Device error, e.g. paper out
194                 EBADEXEC        = 1085, // Bad executable
195                 EBADARCH        = 1086, // Bad CPU type in executable
196                 ESHLIBVERS      = 1087, // Shared library version mismatch
197                 EBADMACHO       = 1088, // Malformed Macho file
198                 ENOATTR         = 1093, // Attribute not found
199                 ENOPOLICY       = 1103, // No such policy registered
200         }
201
202         #endregion
203
204         #region Classes
205
206         public sealed class FilePosition : MarshalByRefObject, IDisposable 
207                 , IEquatable <FilePosition>
208         {
209
210                 private static readonly int FilePositionDumpSize = 
211                         Stdlib.DumpFilePosition (null, new HandleRef (null, IntPtr.Zero), 0);
212
213                 private HandleRef pos;
214
215                 public FilePosition ()
216                 {
217                         IntPtr p = Stdlib.CreateFilePosition ();
218                         if (p == IntPtr.Zero)
219                                 throw new OutOfMemoryException ("Unable to malloc fpos_t!");
220                         pos = new HandleRef (this, p);
221                 }
222
223                 internal HandleRef Handle {
224                         get {return pos;}
225                 }
226
227                 public void Dispose ()
228                 {
229                         Cleanup ();
230                         GC.SuppressFinalize (this);
231                 }
232
233                 private void Cleanup ()
234                 {
235                         if (pos.Handle != IntPtr.Zero) {
236                                 Stdlib.free (pos.Handle);
237                                 pos = new HandleRef (this, IntPtr.Zero);
238                         }
239                 }
240
241                 public override string ToString ()
242                 {
243                         return "(" + base.ToString () + " " + GetDump () + ")";
244                 }
245
246                 private string GetDump ()
247                 {
248                         if (FilePositionDumpSize <= 0)
249                                 return "internal error";
250
251                         StringBuilder buf = new StringBuilder (FilePositionDumpSize+1);
252
253                         if (Stdlib.DumpFilePosition (buf, Handle, FilePositionDumpSize+1) <= 0)
254                                 return "internal error dumping fpos_t";
255
256                         return buf.ToString ();
257                 }
258
259                 public override bool Equals (object obj)
260                 {
261                         FilePosition fp = obj as FilePosition;
262                         if (obj == null || fp == null)
263                                 return false;
264                         return ToString().Equals (obj.ToString());
265                 }
266
267                 public bool Equals (FilePosition value)
268                 {
269                         if (object.ReferenceEquals (this, value))
270                                 return true;
271                         return ToString().Equals (value.ToString());
272                 }
273
274                 public override int GetHashCode ()
275                 {
276                         return ToString ().GetHashCode ();
277                 }
278
279                 ~FilePosition ()
280                 {
281                         Cleanup ();
282                 }
283
284                 public static bool operator== (FilePosition lhs, FilePosition rhs)
285                 {
286                         return Object.Equals (lhs, rhs);
287                 }
288
289                 public static bool operator!= (FilePosition lhs, FilePosition rhs)
290                 {
291                         return !Object.Equals (lhs, rhs);
292                 }
293         }
294
295
296         public enum SignalAction {
297                 Default,
298                 Ignore,
299                 Error
300         }
301
302         //
303         // Right now using this attribute gives an assert because it
304         // isn't implemented.
305         //
306 #if UNMANAGED_FN_PTR_SUPPORT_FIXED
307         [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
308 #endif
309         public delegate void SignalHandler (int signal);
310
311
312         internal class XPrintfFunctions
313         {
314                 internal delegate object XPrintf (object[] parameters);
315
316                 internal static XPrintf printf;
317                 internal static XPrintf fprintf;
318                 internal static XPrintf snprintf;
319                 internal static XPrintf syslog;
320
321                 static XPrintfFunctions ()
322                 {
323                         CdeclFunction _printf = new CdeclFunction (Stdlib.LIBC, "printf", typeof(int));
324                         printf = new XPrintf (_printf.Invoke);
325
326                         CdeclFunction _fprintf = new CdeclFunction (Stdlib.LIBC, "fprintf", typeof(int));
327                         fprintf = new XPrintf (_fprintf.Invoke);
328
329                         CdeclFunction _snprintf = new CdeclFunction (Stdlib.MPH, 
330                                         "Mono_Posix_Stdlib_snprintf", typeof(int));
331                         snprintf = new XPrintf (_snprintf.Invoke);
332
333                         CdeclFunction _syslog = new CdeclFunction (Syscall.MPH, 
334                                         "Mono_Posix_Stdlib_syslog2", typeof(int));
335                         syslog = new XPrintf (_syslog.Invoke);
336                 }
337         }
338
339         //
340         // Convention: Functions that are part of the C standard library go here.
341         //
342         // For example, the man page should say something similar to:
343         //
344         //    CONFORMING TO
345         //           ISO 9899 (''ANSI C'')
346         //
347         // The intent is that members of this class should be portable to any system
348         // supporting the C runtime (read: non-Unix, including Windows).  Using
349         // anything from Syscall is non-portable, but restricting yourself to just
350         // Stdlib is intended to be portable.
351         //
352         // The only methods in here should be:
353         //  (1) low-level functions (as defined above).
354         //  (2) "Trivial" function overloads.  For example, if the parameters to a
355         //      function are related (e.g. fwrite(3))
356         //  (3) The return type SHOULD NOT be changed.  If you want to provide a
357         //      convenience function with a nicer return type, place it into one of
358         //      the Mono.Unix.Std* wrapper classes, and give it a .NET-styled name.
359         //      - EXCEPTION: No public functions should have a `void' return type.
360         //        `void' return types should be replaced with `int'.
361         //        Rationality: `void'-return functions typically require a
362         //        complicated call sequence, such as clear errno, then call, then
363         //        check errno to see if any errors occurred.  This sequence can't 
364         //        be done safely in managed code, as errno may change as part of 
365         //        the P/Invoke mechanism.
366         //        Instead, add a MonoPosixHelper export which does:
367         //          errno = 0;
368         //          INVOKE SYSCALL;
369         //          return errno == 0 ? 0 : -1;
370         //        This lets managed code check the return value in the usual manner.
371         //  (4) Exceptions SHOULD NOT be thrown.  EXCEPTIONS: 
372         //      - If you're wrapping *broken* methods which make assumptions about 
373         //        input data, such as that an argument refers to N bytes of data.  
374         //        This is currently limited to cuserid(3) and encrypt(3).
375         //      - If you call functions which themselves generate exceptions.  
376         //        This is the case for using NativeConvert, which will throw an
377         //        exception if an invalid/unsupported value is used.
378         //
379         public class Stdlib
380         {
381                 internal const string LIBC = "msvcrt";
382                 internal const string MPH  = "MonoPosixHelper";
383
384                 internal Stdlib () {}
385
386                 #region <errno.h> Declarations
387                 //
388                 // <errno.h>  -- COMPLETE
389                 //
390
391                 public static Errno GetLastError ()
392                 {
393                         int errno = Marshal.GetLastWin32Error ();
394                         return NativeConvert.ToErrno (errno);
395                 }
396
397                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
398                                 EntryPoint="Mono_Posix_Stdlib_SetLastError")]
399                 private static extern void SetLastError (int error);
400
401                 protected static void SetLastError (Errno error)
402                 {
403                         int _error = NativeConvert.FromErrno (error);
404                         SetLastError (_error);
405                 }
406
407                 #endregion
408
409                 //
410                 // <signal.h>
411                 //
412                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
413                                 EntryPoint="Mono_Posix_Stdlib_InvokeSignalHandler")]
414                 internal static extern void InvokeSignalHandler (int signum, IntPtr handler);
415
416                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
417                                 EntryPoint="Mono_Posix_Stdlib_SIG_DFL")]
418                 private static extern IntPtr GetDefaultSignal ();
419
420                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
421                                 EntryPoint="Mono_Posix_Stdlib_SIG_ERR")]
422                 private static extern IntPtr GetErrorSignal ();
423
424                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
425                                 EntryPoint="Mono_Posix_Stdlib_SIG_IGN")]
426                 private static extern IntPtr GetIgnoreSignal ();
427
428                 private static readonly IntPtr _SIG_DFL = GetDefaultSignal ();
429                 private static readonly IntPtr _SIG_ERR = GetErrorSignal ();
430                 private static readonly IntPtr _SIG_IGN = GetIgnoreSignal ();
431
432                 private static void _ErrorHandler (int signum)
433                 {
434                         Console.Error.WriteLine ("Error handler invoked for signum " + 
435                                         signum + ".  Don't do that.");
436                 }
437
438                 private static void _DefaultHandler (int signum)
439                 {
440                         Console.Error.WriteLine ("Default handler invoked for signum " + 
441                                         signum + ".  Don't do that.");
442                 }
443
444                 private static void _IgnoreHandler (int signum)
445                 {
446                         Console.Error.WriteLine ("Ignore handler invoked for signum " + 
447                                         signum + ".  Don't do that.");
448                 }
449
450                 [CLSCompliant (false)]
451                 public static readonly SignalHandler SIG_DFL = new SignalHandler (_DefaultHandler);
452                 [CLSCompliant (false)]
453                 public static readonly SignalHandler SIG_ERR = new SignalHandler (_ErrorHandler);
454                 [CLSCompliant (false)]
455                 public static readonly SignalHandler SIG_IGN = new SignalHandler (_IgnoreHandler);
456
457                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
458                                 SetLastError=true, EntryPoint="signal")]
459                 private static extern IntPtr sys_signal (int signum, SignalHandler handler);
460
461                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
462                                 SetLastError=true, EntryPoint="signal")]
463                 private static extern IntPtr sys_signal (int signum, IntPtr handler);
464
465                 [CLSCompliant (false)]
466                 [Obsolete ("This is not safe; " + 
467                                 "use Mono.Unix.UnixSignal for signal delivery or SetSignalAction()")]
468                 public static SignalHandler signal (Signum signum, SignalHandler handler)
469                 {
470                         int _sig = NativeConvert.FromSignum (signum);
471
472                         Delegate[] handlers = handler.GetInvocationList ();
473                         for (int i = 0; i < handlers.Length; ++i) {
474                                 Marshal.Prelink (handlers [i].Method);
475                         }
476
477                         IntPtr r;
478                         if (handler == SIG_DFL)
479                                 r = sys_signal (_sig, _SIG_DFL);
480                         else if (handler == SIG_ERR)
481                                 r = sys_signal (_sig, _SIG_ERR);
482                         else if (handler == SIG_IGN)
483                                 r = sys_signal (_sig, _SIG_IGN);
484                         else
485                                 r = sys_signal (_sig, handler);
486                         return TranslateHandler (r);
487                 }
488
489                 private static SignalHandler TranslateHandler (IntPtr handler)
490                 {
491                         if (handler == _SIG_DFL)
492                                 return SIG_DFL;
493                         if (handler == _SIG_ERR)
494                                 return SIG_ERR;
495                         if (handler == _SIG_IGN)
496                                 return SIG_IGN;
497                         return (SignalHandler) Marshal.GetDelegateForFunctionPointer (handler, typeof(SignalHandler));
498                 }
499
500                 public static int SetSignalAction (Signum signal, SignalAction action)
501                 {
502                         return SetSignalAction (NativeConvert.FromSignum (signal), action);
503                 }
504
505                 public static int SetSignalAction (RealTimeSignum rts, SignalAction action)
506                 {
507                         return SetSignalAction (NativeConvert.FromRealTimeSignum (rts), action);
508                 }
509                 
510                 private static int SetSignalAction (int signum, SignalAction action)
511                 {
512                         IntPtr handler = IntPtr.Zero;
513                         switch (action) {
514                                 case SignalAction.Default:
515                                         handler = _SIG_DFL;
516                                         break;
517                                 case SignalAction.Ignore:
518                                         handler = _SIG_IGN;
519                                         break;
520                                 case SignalAction.Error:
521                                         handler = _SIG_ERR;
522                                         break;
523                                 default:
524                                         throw new ArgumentException ("Invalid action value.", "action");
525                         }
526                         IntPtr r = sys_signal (signum, handler);
527                         if (r == _SIG_ERR)
528                                 return -1;
529                         return 0;
530                 }
531
532                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, EntryPoint="raise")]
533                 private static extern int sys_raise (int sig);
534
535                 [CLSCompliant (false)]
536                 public static int raise (Signum sig)
537                 {
538                         return sys_raise (NativeConvert.FromSignum (sig));
539                 }
540
541                 public static int raise (RealTimeSignum rts)
542                 {
543                         return sys_raise (NativeConvert.FromRealTimeSignum (rts));
544                 }
545
546                 //
547                 // <stdio.h> -- COMPLETE except for :
548                 //    - the scanf(3) family .
549                 //    - vararg functions.
550                 //    - Horribly unsafe functions (gets(3)).
551                 //
552                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
553                                 EntryPoint="Mono_Posix_Stdlib__IOFBF")]
554                 private static extern int GetFullyBuffered ();
555
556                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
557                                 EntryPoint="Mono_Posix_Stdlib__IOLBF")]
558                 private static extern int GetLineBuffered ();
559
560                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
561                                 EntryPoint="Mono_Posix_Stdlib__IONBF")]
562                 private static extern int GetNonBuffered ();
563
564                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
565                                 EntryPoint="Mono_Posix_Stdlib_BUFSIZ")]
566                 private static extern int GetBufferSize ();
567
568                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
569                                 EntryPoint="Mono_Posix_Stdlib_CreateFilePosition")]
570                 internal static extern IntPtr CreateFilePosition ();
571
572                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
573                                 EntryPoint="Mono_Posix_Stdlib_DumpFilePosition")]
574                 internal static extern int DumpFilePosition (StringBuilder buf, HandleRef handle, int len);
575
576                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
577                                 EntryPoint="Mono_Posix_Stdlib_EOF")]
578                 private static extern int GetEOF ();
579
580                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
581                                 EntryPoint="Mono_Posix_Stdlib_FILENAME_MAX")]
582                 private static extern int GetFilenameMax ();
583
584                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
585                                 EntryPoint="Mono_Posix_Stdlib_FOPEN_MAX")]
586                 private static extern int GetFopenMax ();
587
588                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
589                                 EntryPoint="Mono_Posix_Stdlib_L_tmpnam")]
590                 private static extern int GetTmpnamLength ();
591
592                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
593                                 EntryPoint="Mono_Posix_Stdlib_stdin")]
594                 private static extern IntPtr GetStandardInput ();
595
596                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
597                                 EntryPoint="Mono_Posix_Stdlib_stdout")]
598                 private static extern IntPtr GetStandardOutput ();
599
600                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
601                                 EntryPoint="Mono_Posix_Stdlib_stderr")]
602                 private static extern IntPtr GetStandardError ();
603
604                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
605                                 EntryPoint="Mono_Posix_Stdlib_TMP_MAX")]
606                 private static extern int GetTmpMax ();
607
608                 [CLSCompliant (false)]
609                 public static readonly int    _IOFBF       = GetFullyBuffered ();
610                 [CLSCompliant (false)]
611                 public static readonly int    _IOLBF       = GetLineBuffered ();
612                 [CLSCompliant (false)]
613                 public static readonly int    _IONBF       = GetNonBuffered ();
614                 [CLSCompliant (false)]
615                 public static readonly int    BUFSIZ       = GetBufferSize ();
616                 [CLSCompliant (false)]
617                 public static readonly int    EOF          = GetEOF ();
618                 [CLSCompliant (false)]
619                 public static readonly int    FOPEN_MAX    = GetFopenMax ();
620                 [CLSCompliant (false)]
621                 public static readonly int    FILENAME_MAX = GetFilenameMax ();
622                 [CLSCompliant (false)]
623                 public static readonly int    L_tmpnam     = GetTmpnamLength ();
624                 public static readonly IntPtr stderr       = GetStandardError ();
625                 public static readonly IntPtr stdin        = GetStandardInput ();
626                 public static readonly IntPtr stdout       = GetStandardOutput ();
627                 [CLSCompliant (false)]
628                 public static readonly int    TMP_MAX      = GetTmpMax ();
629
630                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
631                 public static extern int remove (
632                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
633                                 string filename);
634
635                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
636                 public static extern int rename (
637                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
638                                 string oldpath, 
639                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
640                                 string newpath);
641
642                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
643                 public static extern IntPtr tmpfile ();
644
645                 private static object tmpnam_lock = new object ();
646
647                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
648                                 SetLastError=true, EntryPoint="tmpnam")]
649                 private static extern IntPtr sys_tmpnam (StringBuilder s);
650
651                 [Obsolete ("Syscall.mkstemp() should be preferred.")]
652                 public static string tmpnam (StringBuilder s)
653                 {
654                         if (s != null && s.Capacity < L_tmpnam)
655                                 throw new ArgumentOutOfRangeException ("s", "s.Capacity < L_tmpnam");
656                         lock (tmpnam_lock) {
657                                 IntPtr r = sys_tmpnam (s);
658                                 return UnixMarshal.PtrToString (r);
659                         }
660                 }
661
662                 [Obsolete ("Syscall.mkstemp() should be preferred.")]
663                 public static string tmpnam ()
664                 {
665                         lock (tmpnam_lock) {
666                                 IntPtr r = sys_tmpnam (null);
667                                 return UnixMarshal.PtrToString (r);
668                         }
669                 }
670
671                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
672                 public static extern int fclose (IntPtr stream);
673
674                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
675                 public static extern int fflush (IntPtr stream);
676
677                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
678                 public static extern IntPtr fopen (
679                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
680                                 string path, string mode);
681
682                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
683                 public static extern IntPtr freopen (
684                                 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
685                                 string path, string mode, IntPtr stream);
686
687                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl, 
688                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_setbuf")]
689                 public static extern int setbuf (IntPtr stream, IntPtr buf);
690
691                 [CLSCompliant (false)]
692                 public static unsafe int setbuf (IntPtr stream, byte* buf)
693                 {
694                         return setbuf (stream, (IntPtr) buf);
695                 }
696
697                 [CLSCompliant (false)]
698                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
699                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_setvbuf")]
700                 public static extern int setvbuf (IntPtr stream, IntPtr buf, int mode, ulong size);
701
702                 [CLSCompliant (false)]
703                 public static unsafe int setvbuf (IntPtr stream, byte* buf, int mode, ulong size)
704                 {
705                         return setvbuf (stream, (IntPtr) buf, mode, size);
706                 }
707
708                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
709                                 EntryPoint="fprintf")]
710                 private static extern int sys_fprintf (IntPtr stream, string format, string message);
711
712                 public static int fprintf (IntPtr stream, string message)
713                 {
714                         return sys_fprintf (stream, "%s", message);
715                 }
716
717                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
718                                 "Use fprintf (IntPtr, string) instead.")]
719                 public static int fprintf (IntPtr stream, string format, params object[] parameters)
720                 {
721                         object[] _parameters = new object[checked(parameters.Length+2)];
722                         _parameters [0] = stream;
723                         _parameters [1] = format;
724                         Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
725                         return (int) XPrintfFunctions.fprintf (_parameters);
726                 }
727
728                 /* SKIP: fscanf(3) */
729
730                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
731                                 EntryPoint="printf")]
732                 private static extern int sys_printf (string format, string message);
733
734                 public static int printf (string message)
735                 {
736                         return sys_printf ("%s", message);
737                 }
738
739                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
740                                 "Use printf (string) instead.")]
741                 public static int printf (string format, params object[] parameters)
742                 {
743                         object[] _parameters = new object[checked(parameters.Length+1)];
744                         _parameters [0] = format;
745                         Array.Copy (parameters, 0, _parameters, 1, parameters.Length);
746                         return (int) XPrintfFunctions.printf (_parameters);
747                 }
748
749                 /* SKIP: scanf(3) */
750
751                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
752                                 EntryPoint="Mono_Posix_Stdlib_snprintf")]
753                 private static extern int sys_snprintf (StringBuilder s, ulong n, 
754                                 string format, string message);
755
756                 [CLSCompliant (false)]
757                 public static int snprintf (StringBuilder s, ulong n, string message)
758                 {
759                         if (n > (ulong) s.Capacity)
760                                 throw new ArgumentOutOfRangeException ("n", "n must be <= s.Capacity");
761                         return sys_snprintf (s, n, "%s", message);
762                 }
763
764                 public static int snprintf (StringBuilder s, string message)
765                 {
766                         return sys_snprintf (s, (ulong) s.Capacity, "%s", message);
767                 }
768
769                 [CLSCompliant (false)]
770                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
771                                 "Use snprintf (StringBuilder, string) instead.")]
772                 public static int snprintf (StringBuilder s, ulong n, 
773                                 string format, params object[] parameters)
774                 {
775                         if (n > (ulong) s.Capacity)
776                                 throw new ArgumentOutOfRangeException ("n", "n must be <= s.Capacity");
777
778                         object[] _parameters = new object[checked(parameters.Length+3)];
779                         _parameters [0] = s;
780                         _parameters [1] = n;
781                         _parameters [2] = format;
782                         Array.Copy (parameters, 0, _parameters, 3, parameters.Length);
783                         return (int) XPrintfFunctions.snprintf (_parameters);
784                 }
785
786                 [CLSCompliant (false)]
787                 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
788                                 "Use snprintf (StringBuilder, string) instead.")]
789                 public static int snprintf (StringBuilder s,
790                                 string format, params object[] parameters)
791                 {
792                         object[] _parameters = new object[checked(parameters.Length+3)];
793                         _parameters [0] = s;
794                         _parameters [1] = (ulong) s.Capacity;
795                         _parameters [2] = format;
796                         Array.Copy (parameters, 0, _parameters, 3, parameters.Length);
797                         return (int) XPrintfFunctions.snprintf (_parameters);
798                 }
799
800                 /*
801                  * SKIP:
802                  *    sprintf(3)
803                  *    sscanf(3)
804                  *    vfprintf(3)
805                  *    vfscanf(3)
806                  *    vprintf(3)
807                  *    vscanf(3)
808                  *    vsnprintf(3)
809                  *    vsprint(3)
810                  *    vsscanf(3)
811                  */
812
813                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
814                 public static extern int fgetc (IntPtr stream);
815
816                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
817                                 SetLastError=true, EntryPoint="fgets")]
818                 private static extern IntPtr sys_fgets (StringBuilder sb, int size, IntPtr stream);
819
820                 public static StringBuilder fgets (StringBuilder sb, int size, IntPtr stream)
821                 {
822                         IntPtr r = sys_fgets (sb, size, stream);
823                         if (r == IntPtr.Zero)
824                                 return null;
825                         return sb;
826                 }
827
828                 public static StringBuilder fgets (StringBuilder sb, IntPtr stream)
829                 {
830                         return fgets (sb, sb.Capacity, stream);
831                 }
832
833                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
834                 public static extern int fputc (int c, IntPtr stream);
835
836                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
837                 public static extern int fputs (string s, IntPtr stream);
838
839                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
840                 public static extern int getc (IntPtr stream);
841
842                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
843                 public static extern int getchar ();
844
845                 /* SKIP: gets(3) */
846
847                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
848                 public static extern int putc (int c, IntPtr stream);
849
850                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
851                 public static extern int putchar (int c);
852
853                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
854                 public static extern int puts (string s);
855
856                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
857                 public static extern int ungetc (int c, IntPtr stream);
858
859                 [CLSCompliant (false)]
860                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
861                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fread")]
862                 public static extern ulong fread (IntPtr ptr, ulong size, ulong nmemb, IntPtr stream);
863
864                 [CLSCompliant (false)]
865                 public static unsafe ulong fread (void* ptr, ulong size, ulong nmemb, IntPtr stream)
866                 {
867                         return fread ((IntPtr) ptr, size, nmemb, stream);
868                 }
869
870                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
871                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fread")]
872                 private static extern ulong sys_fread ([Out] byte[] ptr, 
873                                 ulong size, ulong nmemb, IntPtr stream);
874
875                 [CLSCompliant (false)]
876                 public static ulong fread (byte[] ptr, ulong size, ulong nmemb, IntPtr stream)
877                 {
878                         if ((size * nmemb) > (ulong) ptr.Length)
879                                 throw new ArgumentOutOfRangeException ("nmemb");
880                         return sys_fread (ptr, size, nmemb, stream);
881                 }
882
883                 [CLSCompliant (false)]
884                 public static ulong fread (byte[] ptr, IntPtr stream)
885                 {
886                         return fread (ptr, 1, (ulong) ptr.Length, stream);
887                 }
888
889                 [CLSCompliant (false)]
890                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
891                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fwrite")]
892                 public static extern ulong fwrite (IntPtr ptr, ulong size, ulong nmemb, IntPtr stream);
893
894                 [CLSCompliant (false)]
895                 public static unsafe ulong fwrite (void* ptr, ulong size, ulong nmemb, IntPtr stream)
896                 {
897                         return fwrite ((IntPtr) ptr, size, nmemb, stream);
898                 }
899
900                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
901                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fwrite")]
902                 private static extern ulong sys_fwrite (byte[] ptr, 
903                                 ulong size, ulong nmemb, IntPtr stream);
904
905                 [CLSCompliant (false)]
906                 public static ulong fwrite (byte[] ptr, ulong size, ulong nmemb, IntPtr stream)
907                 {
908                         if ((size * nmemb) > (ulong) ptr.Length)
909                                 throw new ArgumentOutOfRangeException ("nmemb");
910                         return sys_fwrite (ptr, size, nmemb, stream);
911                 }
912
913                 [CLSCompliant (false)]
914                 public static ulong fwrite (byte[] ptr, IntPtr stream)
915                 {
916                         return fwrite (ptr, 1, (ulong) ptr.Length, stream);
917                 }
918
919                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
920                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fgetpos")]
921                 private static extern int sys_fgetpos (IntPtr stream, HandleRef pos);
922
923                 public static int fgetpos (IntPtr stream, FilePosition pos)
924                 {
925                         return sys_fgetpos (stream, pos.Handle);
926                 }
927
928                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
929                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fseek")]
930                 private static extern int sys_fseek (IntPtr stream, long offset, int origin);
931
932                 [CLSCompliant (false)]
933                 public static int fseek (IntPtr stream, long offset, SeekFlags origin)
934                 {
935                         int _origin = NativeConvert.FromSeekFlags (origin);
936                         return sys_fseek (stream, offset, _origin);
937                 }
938
939                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
940                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fsetpos")]
941                 private static extern int sys_fsetpos (IntPtr stream, HandleRef pos);
942
943                 public static int fsetpos (IntPtr stream, FilePosition pos)
944                 {
945                         return sys_fsetpos (stream, pos.Handle);
946                 }
947
948                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
949                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_ftell")]
950                 public static extern long ftell (IntPtr stream);
951
952                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
953                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_rewind")]
954                 public static extern int rewind (IntPtr stream);
955
956                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
957                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_clearerr")]
958                 public static extern int clearerr (IntPtr stream);
959
960                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
961                 public static extern int feof (IntPtr stream);
962
963                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
964                 public static extern int ferror (IntPtr stream);
965
966                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl, 
967                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_perror")]
968                 private static extern int perror (string s, int err);
969
970                 public static int perror (string s)
971                 {
972                         return perror (s, Marshal.GetLastWin32Error ());
973                 }
974
975                 //
976                 // <stdlib.h>
977                 //
978                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
979                                 EntryPoint="Mono_Posix_Stdlib_EXIT_FAILURE")]
980                 private static extern int GetExitFailure();
981
982                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
983                                 EntryPoint="Mono_Posix_Stdlib_EXIT_SUCCESS")]
984                 private static extern int GetExitSuccess ();
985
986                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
987                                 EntryPoint="Mono_Posix_Stdlib_MB_CUR_MAX")]
988                 private static extern int GetMbCurMax ();
989
990                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
991                                 EntryPoint="Mono_Posix_Stdlib_RAND_MAX")]
992                 private static extern int GetRandMax ();
993
994                 [CLSCompliant (false)]
995                 public static readonly int  EXIT_FAILURE = GetExitFailure ();
996                 [CLSCompliant (false)]
997                 public static readonly int  EXIT_SUCCESS = GetExitSuccess ();
998                 [CLSCompliant (false)]
999                 public static readonly int  MB_CUR_MAX   = GetMbCurMax ();
1000                 [CLSCompliant (false)]
1001                 public static readonly int  RAND_MAX     = GetRandMax ();
1002
1003                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1004                 public static extern int rand ();
1005
1006                 [CLSCompliant (false)]
1007                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1008                 public static extern void srand (uint seed);
1009
1010                 // calloc(3):
1011                 //    void *calloc (size_t nmemb, size_t size);
1012                 [CLSCompliant (false)]
1013                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1014                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_calloc")]
1015                 public static extern IntPtr calloc (ulong nmemb, ulong size);
1016
1017                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1018                 public static extern void free (IntPtr ptr);
1019
1020                 // malloc(3):
1021                 //    void *malloc(size_t size);
1022                 [CLSCompliant (false)]
1023                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1024                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_malloc")]
1025                 public static extern IntPtr malloc (ulong size);
1026
1027                 // realloc(3):
1028                 //    void *realloc(void *ptr, size_t size);
1029                 [CLSCompliant (false)]
1030                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1031                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_realloc")]
1032                 public static extern IntPtr realloc (IntPtr ptr, ulong size);
1033
1034                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1035                 public static extern void abort ();
1036
1037                 /* SKIP: atexit(3) -- the GC should have collected most references by the
1038                  * time this runs, so no delegates should exist, making it pointless. */
1039
1040                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1041                 public static extern void exit (int status);
1042
1043                 [CLSCompliant (false)]
1044                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1045                 public static extern void _Exit (int status);
1046
1047                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, EntryPoint="getenv")]
1048                 private static extern IntPtr sys_getenv (string name);
1049
1050                 public static string getenv (string name)
1051                 {
1052                         IntPtr r = sys_getenv (name);
1053                         return UnixMarshal.PtrToString (r);
1054                 }
1055
1056                 [CLSCompliant (false)]
1057                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
1058                 public static extern int system (string @string);
1059
1060                 //
1061                 // <string.h>
1062                 //
1063
1064                 private static object strerror_lock = new object ();
1065
1066                 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
1067                                 SetLastError=true, EntryPoint="strerror")]
1068                 private static extern IntPtr sys_strerror (int errnum);
1069
1070                 [CLSCompliant (false)]
1071                 public static string strerror (Errno errnum)
1072                 {
1073                         int e = NativeConvert.FromErrno (errnum);
1074                         lock (strerror_lock) {
1075                                 IntPtr r = sys_strerror (e);
1076                                 return UnixMarshal.PtrToString (r);
1077                         }
1078                 }
1079
1080                 // strlen(3):
1081                 //    size_t strlen(const char *s);
1082                 [CLSCompliant (false)]
1083                 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1084                                 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_strlen")]
1085                 public static extern ulong strlen (IntPtr s);
1086         }
1087
1088         #endregion // Classes
1089 }
1090
1091 // vim: noexpandtab