5 // Jonathan Pryor (jonpryor@vt.edu)
7 // (C) 2004-2006 Jonathan Pryor
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
30 using System.Collections;
32 using System.Runtime.InteropServices;
34 using Mono.Unix.Native;
36 namespace Mono.Unix.Native {
41 public enum Errno : int {
42 // errors & their values liberally copied from
43 // FC2 /usr/include/asm/errno.h
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
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
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
170 ENOMEDIUM = 123, // No medium found
171 EMEDIUMTYPE = 124, // Wrong medium type
180 ENOTRECOVERABLE = 131,
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
206 public sealed class FilePosition : MarshalByRefObject, IDisposable
207 , IEquatable <FilePosition>
210 private static readonly int FilePositionDumpSize =
211 Stdlib.DumpFilePosition (null, new HandleRef (null, IntPtr.Zero), 0);
213 private HandleRef pos;
215 public FilePosition ()
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);
223 internal HandleRef Handle {
227 public void Dispose ()
230 GC.SuppressFinalize (this);
233 private void Cleanup ()
235 if (pos.Handle != IntPtr.Zero) {
236 Stdlib.free (pos.Handle);
237 pos = new HandleRef (this, IntPtr.Zero);
241 public override string ToString ()
243 return "(" + base.ToString () + " " + GetDump () + ")";
246 private string GetDump ()
248 if (FilePositionDumpSize <= 0)
249 return "internal error";
251 StringBuilder buf = new StringBuilder (FilePositionDumpSize+1);
253 if (Stdlib.DumpFilePosition (buf, Handle, FilePositionDumpSize+1) <= 0)
254 return "internal error dumping fpos_t";
256 return buf.ToString ();
259 public override bool Equals (object obj)
261 FilePosition fp = obj as FilePosition;
262 if (obj == null || fp == null)
264 return ToString().Equals (obj.ToString());
267 public bool Equals (FilePosition value)
269 if (object.ReferenceEquals (this, value))
271 return ToString().Equals (value.ToString());
274 public override int GetHashCode ()
276 return ToString ().GetHashCode ();
284 public static bool operator== (FilePosition lhs, FilePosition rhs)
286 return Object.Equals (lhs, rhs);
289 public static bool operator!= (FilePosition lhs, FilePosition rhs)
291 return !Object.Equals (lhs, rhs);
296 public enum SignalAction {
303 // Right now using this attribute gives an assert because it
304 // isn't implemented.
306 #if UNMANAGED_FN_PTR_SUPPORT_FIXED
307 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
309 public delegate void SignalHandler (int signal);
312 internal class XPrintfFunctions
314 internal delegate object XPrintf (object[] parameters);
316 internal static XPrintf printf;
317 internal static XPrintf fprintf;
318 internal static XPrintf snprintf;
319 internal static XPrintf syslog;
321 static XPrintfFunctions ()
323 CdeclFunction _printf = new CdeclFunction (Stdlib.LIBC, "printf", typeof(int));
324 printf = new XPrintf (_printf.Invoke);
326 CdeclFunction _fprintf = new CdeclFunction (Stdlib.LIBC, "fprintf", typeof(int));
327 fprintf = new XPrintf (_fprintf.Invoke);
329 CdeclFunction _snprintf = new CdeclFunction (Stdlib.MPH,
330 "Mono_Posix_Stdlib_snprintf", typeof(int));
331 snprintf = new XPrintf (_snprintf.Invoke);
333 CdeclFunction _syslog = new CdeclFunction (Syscall.MPH,
334 "Mono_Posix_Stdlib_syslog2", typeof(int));
335 syslog = new XPrintf (_syslog.Invoke);
340 // Convention: Functions that are part of the C standard library go here.
342 // For example, the man page should say something similar to:
345 // ISO 9899 (''ANSI C'')
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.
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:
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.
381 internal const string LIBC = "msvcrt";
382 internal const string MPH = "MonoPosixHelper";
384 // It is possible for Mono.Posix and MonoPosixHelper to get out of sync,
385 // for example if NuGet does something weird. To mitigate this, anyone
386 // editing Mono.Posix needs to observe two rules:
387 // 1. When introducing C-interface changes to MonoPosixHelper, update
388 // the version strings in VersionCheck below and also
389 // Mono_Unix_VersionString in the C sources.
390 // 2. Any class which performs a DllImport on Stdlib.MPH needs to call
391 // Stdlib.VersionCheck in its static constructor.
393 [DllImport (Stdlib.MPH, CallingConvention=CallingConvention.Cdecl,
394 EntryPoint="Mono_Unix_VersionString")]
395 private static extern IntPtr VersionStringPtr ();
396 private static bool versionCheckPerformed = false;
397 internal static void VersionCheck ()
399 if (versionCheckPerformed)
402 // This string is arbitrary; it matters only that it is unique.
403 string assemblyVersion = "MonoProject-2015-12-1";
404 string nativeVersion = Marshal.PtrToStringAnsi (VersionStringPtr ());
405 if (assemblyVersion != nativeVersion)
407 throw new Exception ("Mono.Posix assembly loaded with a different version (\""
408 + assemblyVersion + "\") than MonoPosixHelper (\"" + nativeVersion
409 + "\"). You may need to reinstall Mono.Posix.");
412 versionCheckPerformed = true;
420 internal Stdlib () {}
422 #region <errno.h> Declarations
424 // <errno.h> -- COMPLETE
427 public static Errno GetLastError ()
429 if (Environment.OSVersion.Platform != PlatformID.Unix) {
430 // On Windows Marshal.GetLastWin32Error() doesn't take errno
431 // into account so we need to call Mono_Posix_Stdlib_GetLastError()
432 // which returns the value of errno in the C runtime
433 // libMonoPosixHelper.dll was linked against.
434 return (Errno) _GetLastError ();
436 return NativeConvert.ToErrno (Marshal.GetLastWin32Error ());
439 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
440 EntryPoint="Mono_Posix_Stdlib_GetLastError")]
441 private static extern int _GetLastError ();
443 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
444 EntryPoint="Mono_Posix_Stdlib_SetLastError")]
445 private static extern void SetLastError (int error);
447 protected static void SetLastError (Errno error)
449 int _error = NativeConvert.FromErrno (error);
450 SetLastError (_error);
458 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
459 EntryPoint="Mono_Posix_Stdlib_InvokeSignalHandler")]
460 internal static extern void InvokeSignalHandler (int signum, IntPtr handler);
462 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
463 EntryPoint="Mono_Posix_Stdlib_SIG_DFL")]
464 private static extern IntPtr GetDefaultSignal ();
466 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
467 EntryPoint="Mono_Posix_Stdlib_SIG_ERR")]
468 private static extern IntPtr GetErrorSignal ();
470 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
471 EntryPoint="Mono_Posix_Stdlib_SIG_IGN")]
472 private static extern IntPtr GetIgnoreSignal ();
474 private static readonly IntPtr _SIG_DFL = GetDefaultSignal ();
475 private static readonly IntPtr _SIG_ERR = GetErrorSignal ();
476 private static readonly IntPtr _SIG_IGN = GetIgnoreSignal ();
478 private static void _ErrorHandler (int signum)
480 Console.Error.WriteLine ("Error handler invoked for signum " +
481 signum + ". Don't do that.");
484 private static void _DefaultHandler (int signum)
486 Console.Error.WriteLine ("Default handler invoked for signum " +
487 signum + ". Don't do that.");
490 private static void _IgnoreHandler (int signum)
492 Console.Error.WriteLine ("Ignore handler invoked for signum " +
493 signum + ". Don't do that.");
496 [CLSCompliant (false)]
497 public static readonly SignalHandler SIG_DFL = new SignalHandler (_DefaultHandler);
498 [CLSCompliant (false)]
499 public static readonly SignalHandler SIG_ERR = new SignalHandler (_ErrorHandler);
500 [CLSCompliant (false)]
501 public static readonly SignalHandler SIG_IGN = new SignalHandler (_IgnoreHandler);
503 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
504 SetLastError=true, EntryPoint="signal")]
505 private static extern IntPtr sys_signal (int signum, SignalHandler handler);
507 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
508 SetLastError=true, EntryPoint="signal")]
509 private static extern IntPtr sys_signal (int signum, IntPtr handler);
511 [CLSCompliant (false)]
512 [Obsolete ("This is not safe; " +
513 "use Mono.Unix.UnixSignal for signal delivery or SetSignalAction()")]
514 public static SignalHandler signal (Signum signum, SignalHandler handler)
516 int _sig = NativeConvert.FromSignum (signum);
518 Delegate[] handlers = handler.GetInvocationList ();
519 for (int i = 0; i < handlers.Length; ++i) {
520 Marshal.Prelink (handlers [i].Method);
524 if (handler == SIG_DFL)
525 r = sys_signal (_sig, _SIG_DFL);
526 else if (handler == SIG_ERR)
527 r = sys_signal (_sig, _SIG_ERR);
528 else if (handler == SIG_IGN)
529 r = sys_signal (_sig, _SIG_IGN);
531 r = sys_signal (_sig, handler);
532 return TranslateHandler (r);
535 private static SignalHandler TranslateHandler (IntPtr handler)
537 if (handler == _SIG_DFL)
539 if (handler == _SIG_ERR)
541 if (handler == _SIG_IGN)
543 return (SignalHandler) Marshal.GetDelegateForFunctionPointer (handler, typeof(SignalHandler));
546 public static int SetSignalAction (Signum signal, SignalAction action)
548 return SetSignalAction (NativeConvert.FromSignum (signal), action);
551 public static int SetSignalAction (RealTimeSignum rts, SignalAction action)
553 return SetSignalAction (NativeConvert.FromRealTimeSignum (rts), action);
556 private static int SetSignalAction (int signum, SignalAction action)
558 IntPtr handler = IntPtr.Zero;
560 case SignalAction.Default:
563 case SignalAction.Ignore:
566 case SignalAction.Error:
570 throw new ArgumentException ("Invalid action value.", "action");
572 IntPtr r = sys_signal (signum, handler);
578 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, EntryPoint="raise")]
579 private static extern int sys_raise (int sig);
581 [CLSCompliant (false)]
582 public static int raise (Signum sig)
584 return sys_raise (NativeConvert.FromSignum (sig));
587 public static int raise (RealTimeSignum rts)
589 return sys_raise (NativeConvert.FromRealTimeSignum (rts));
593 // <stdio.h> -- COMPLETE except for :
594 // - the scanf(3) family .
595 // - vararg functions.
596 // - Horribly unsafe functions (gets(3)).
598 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
599 EntryPoint="Mono_Posix_Stdlib__IOFBF")]
600 private static extern int GetFullyBuffered ();
602 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
603 EntryPoint="Mono_Posix_Stdlib__IOLBF")]
604 private static extern int GetLineBuffered ();
606 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
607 EntryPoint="Mono_Posix_Stdlib__IONBF")]
608 private static extern int GetNonBuffered ();
610 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
611 EntryPoint="Mono_Posix_Stdlib_BUFSIZ")]
612 private static extern int GetBufferSize ();
614 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
615 EntryPoint="Mono_Posix_Stdlib_CreateFilePosition")]
616 internal static extern IntPtr CreateFilePosition ();
618 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
619 EntryPoint="Mono_Posix_Stdlib_DumpFilePosition")]
620 internal static extern int DumpFilePosition (StringBuilder buf, HandleRef handle, int len);
622 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
623 EntryPoint="Mono_Posix_Stdlib_EOF")]
624 private static extern int GetEOF ();
626 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
627 EntryPoint="Mono_Posix_Stdlib_FILENAME_MAX")]
628 private static extern int GetFilenameMax ();
630 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
631 EntryPoint="Mono_Posix_Stdlib_FOPEN_MAX")]
632 private static extern int GetFopenMax ();
634 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
635 EntryPoint="Mono_Posix_Stdlib_L_tmpnam")]
636 private static extern int GetTmpnamLength ();
638 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
639 EntryPoint="Mono_Posix_Stdlib_stdin")]
640 private static extern IntPtr GetStandardInput ();
642 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
643 EntryPoint="Mono_Posix_Stdlib_stdout")]
644 private static extern IntPtr GetStandardOutput ();
646 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
647 EntryPoint="Mono_Posix_Stdlib_stderr")]
648 private static extern IntPtr GetStandardError ();
650 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
651 EntryPoint="Mono_Posix_Stdlib_TMP_MAX")]
652 private static extern int GetTmpMax ();
654 [CLSCompliant (false)]
655 public static readonly int _IOFBF = GetFullyBuffered ();
656 [CLSCompliant (false)]
657 public static readonly int _IOLBF = GetLineBuffered ();
658 [CLSCompliant (false)]
659 public static readonly int _IONBF = GetNonBuffered ();
660 [CLSCompliant (false)]
661 public static readonly int BUFSIZ = GetBufferSize ();
662 [CLSCompliant (false)]
663 public static readonly int EOF = GetEOF ();
664 [CLSCompliant (false)]
665 public static readonly int FOPEN_MAX = GetFopenMax ();
666 [CLSCompliant (false)]
667 public static readonly int FILENAME_MAX = GetFilenameMax ();
668 [CLSCompliant (false)]
669 public static readonly int L_tmpnam = GetTmpnamLength ();
670 public static readonly IntPtr stderr = GetStandardError ();
671 public static readonly IntPtr stdin = GetStandardInput ();
672 public static readonly IntPtr stdout = GetStandardOutput ();
673 [CLSCompliant (false)]
674 public static readonly int TMP_MAX = GetTmpMax ();
676 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
677 public static extern int remove (
678 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
681 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
682 public static extern int rename (
683 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
685 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
688 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
689 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_tmpfile")]
690 public static extern IntPtr tmpfile ();
692 private static object tmpnam_lock = new object ();
694 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
695 SetLastError=true, EntryPoint="tmpnam")]
696 private static extern IntPtr sys_tmpnam (StringBuilder s);
698 [Obsolete ("Syscall.mkstemp() should be preferred.")]
699 public static string tmpnam (StringBuilder s)
701 if (s != null && s.Capacity < L_tmpnam)
702 throw new ArgumentOutOfRangeException ("s", "s.Capacity < L_tmpnam");
704 IntPtr r = sys_tmpnam (s);
705 return UnixMarshal.PtrToString (r);
709 [Obsolete ("Syscall.mkstemp() should be preferred.")]
710 public static string tmpnam ()
713 IntPtr r = sys_tmpnam (null);
714 return UnixMarshal.PtrToString (r);
718 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
719 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fclose")]
720 public static extern int fclose (IntPtr stream);
722 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
723 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fflush")]
724 public static extern int fflush (IntPtr stream);
726 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
727 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fopen")]
728 public static extern IntPtr fopen (
729 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
730 string path, string mode);
732 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
733 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_freopen")]
734 public static extern IntPtr freopen (
735 [MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(FileNameMarshaler))]
736 string path, string mode, IntPtr stream);
738 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
739 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_setbuf")]
740 public static extern int setbuf (IntPtr stream, IntPtr buf);
742 [CLSCompliant (false)]
743 public static unsafe int setbuf (IntPtr stream, byte* buf)
745 return setbuf (stream, (IntPtr) buf);
748 [CLSCompliant (false)]
749 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
750 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_setvbuf")]
751 public static extern int setvbuf (IntPtr stream, IntPtr buf, int mode, ulong size);
753 [CLSCompliant (false)]
754 public static unsafe int setvbuf (IntPtr stream, byte* buf, int mode, ulong size)
756 return setvbuf (stream, (IntPtr) buf, mode, size);
759 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
760 EntryPoint="Mono_Posix_Stdlib_fprintf")]
761 private static extern int sys_fprintf (IntPtr stream, string format, string message);
763 public static int fprintf (IntPtr stream, string message)
765 return sys_fprintf (stream, "%s", message);
768 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
769 "Use fprintf (IntPtr, string) instead.")]
770 public static int fprintf (IntPtr stream, string format, params object[] parameters)
772 object[] _parameters = new object[checked(parameters.Length+2)];
773 _parameters [0] = stream;
774 _parameters [1] = format;
775 Array.Copy (parameters, 0, _parameters, 2, parameters.Length);
776 return (int) XPrintfFunctions.fprintf (_parameters);
779 /* SKIP: fscanf(3) */
781 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
782 EntryPoint="printf")]
783 private static extern int sys_printf (string format, string message);
785 public static int printf (string message)
787 return sys_printf ("%s", message);
790 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
791 "Use printf (string) instead.")]
792 public static int printf (string format, params object[] parameters)
794 object[] _parameters = new object[checked(parameters.Length+1)];
795 _parameters [0] = format;
796 Array.Copy (parameters, 0, _parameters, 1, parameters.Length);
797 return (int) XPrintfFunctions.printf (_parameters);
802 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
803 EntryPoint="Mono_Posix_Stdlib_snprintf")]
804 private static extern int sys_snprintf (StringBuilder s, ulong n,
805 string format, string message);
807 [CLSCompliant (false)]
808 public static int snprintf (StringBuilder s, ulong n, string message)
810 if (n > (ulong) s.Capacity)
811 throw new ArgumentOutOfRangeException ("n", "n must be <= s.Capacity");
812 return sys_snprintf (s, n, "%s", message);
815 public static int snprintf (StringBuilder s, string message)
817 return sys_snprintf (s, (ulong) s.Capacity, "%s", message);
820 [CLSCompliant (false)]
821 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
822 "Use snprintf (StringBuilder, string) instead.")]
823 public static int snprintf (StringBuilder s, ulong n,
824 string format, params object[] parameters)
826 if (n > (ulong) s.Capacity)
827 throw new ArgumentOutOfRangeException ("n", "n must be <= s.Capacity");
829 object[] _parameters = new object[checked(parameters.Length+3)];
832 _parameters [2] = format;
833 Array.Copy (parameters, 0, _parameters, 3, parameters.Length);
834 return (int) XPrintfFunctions.snprintf (_parameters);
837 [CLSCompliant (false)]
838 [Obsolete ("Not necessarily portable due to cdecl restrictions.\n" +
839 "Use snprintf (StringBuilder, string) instead.")]
840 public static int snprintf (StringBuilder s,
841 string format, params object[] parameters)
843 object[] _parameters = new object[checked(parameters.Length+3)];
845 _parameters [1] = (ulong) s.Capacity;
846 _parameters [2] = format;
847 Array.Copy (parameters, 0, _parameters, 3, parameters.Length);
848 return (int) XPrintfFunctions.snprintf (_parameters);
864 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
865 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fgetc")]
866 public static extern int fgetc (IntPtr stream);
868 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
869 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fgets")]
870 private static extern IntPtr sys_fgets (StringBuilder sb, int size, IntPtr stream);
872 public static StringBuilder fgets (StringBuilder sb, int size, IntPtr stream)
874 IntPtr r = sys_fgets (sb, size, stream);
875 if (r == IntPtr.Zero)
880 public static StringBuilder fgets (StringBuilder sb, IntPtr stream)
882 return fgets (sb, sb.Capacity, stream);
885 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
886 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fputc")]
887 public static extern int fputc (int c, IntPtr stream);
889 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
890 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fputs")]
891 public static extern int fputs (string s, IntPtr stream);
893 public static int getc (IntPtr stream)
895 return fgetc (stream);
898 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
899 public static extern int getchar ();
903 public static int putc (int c, IntPtr stream)
905 return fputc (c, stream);
908 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
909 public static extern int putchar (int c);
911 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
912 public static extern int puts (string s);
914 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
915 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_ungetc")]
916 public static extern int ungetc (int c, IntPtr stream);
918 [CLSCompliant (false)]
919 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
920 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fread")]
921 public static extern ulong fread (IntPtr ptr, ulong size, ulong nmemb, IntPtr stream);
923 [CLSCompliant (false)]
924 public static unsafe ulong fread (void* ptr, ulong size, ulong nmemb, IntPtr stream)
926 return fread ((IntPtr) ptr, size, nmemb, stream);
929 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
930 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fread")]
931 private static extern ulong sys_fread ([Out] byte[] ptr,
932 ulong size, ulong nmemb, IntPtr stream);
934 [CLSCompliant (false)]
935 public static ulong fread (byte[] ptr, ulong size, ulong nmemb, IntPtr stream)
937 if ((size * nmemb) > (ulong) ptr.Length)
938 throw new ArgumentOutOfRangeException ("nmemb");
939 return sys_fread (ptr, size, nmemb, stream);
942 [CLSCompliant (false)]
943 public static ulong fread (byte[] ptr, IntPtr stream)
945 return fread (ptr, 1, (ulong) ptr.Length, stream);
948 [CLSCompliant (false)]
949 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
950 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fwrite")]
951 public static extern ulong fwrite (IntPtr ptr, ulong size, ulong nmemb, IntPtr stream);
953 [CLSCompliant (false)]
954 public static unsafe ulong fwrite (void* ptr, ulong size, ulong nmemb, IntPtr stream)
956 return fwrite ((IntPtr) ptr, size, nmemb, stream);
959 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
960 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fwrite")]
961 private static extern ulong sys_fwrite (byte[] ptr,
962 ulong size, ulong nmemb, IntPtr stream);
964 [CLSCompliant (false)]
965 public static ulong fwrite (byte[] ptr, ulong size, ulong nmemb, IntPtr stream)
967 if ((size * nmemb) > (ulong) ptr.Length)
968 throw new ArgumentOutOfRangeException ("nmemb");
969 return sys_fwrite (ptr, size, nmemb, stream);
972 [CLSCompliant (false)]
973 public static ulong fwrite (byte[] ptr, IntPtr stream)
975 return fwrite (ptr, 1, (ulong) ptr.Length, stream);
978 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
979 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fgetpos")]
980 private static extern int sys_fgetpos (IntPtr stream, HandleRef pos);
982 public static int fgetpos (IntPtr stream, FilePosition pos)
984 return sys_fgetpos (stream, pos.Handle);
987 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
988 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fseek")]
989 private static extern int sys_fseek (IntPtr stream, long offset, int origin);
991 [CLSCompliant (false)]
992 public static int fseek (IntPtr stream, long offset, SeekFlags origin)
994 int _origin = NativeConvert.FromSeekFlags (origin);
995 return sys_fseek (stream, offset, _origin);
998 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
999 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_fsetpos")]
1000 private static extern int sys_fsetpos (IntPtr stream, HandleRef pos);
1002 public static int fsetpos (IntPtr stream, FilePosition pos)
1004 return sys_fsetpos (stream, pos.Handle);
1007 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1008 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_ftell")]
1009 public static extern long ftell (IntPtr stream);
1011 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1012 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_rewind")]
1013 public static extern int rewind (IntPtr stream);
1015 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1016 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_clearerr")]
1017 public static extern int clearerr (IntPtr stream);
1019 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1020 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_feof")]
1021 public static extern int feof (IntPtr stream);
1023 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1024 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_ferror")]
1025 public static extern int ferror (IntPtr stream);
1027 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1028 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_perror")]
1029 private static extern int perror (string s, int err);
1031 public static int perror (string s)
1033 return perror (s, Marshal.GetLastWin32Error ());
1039 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1040 EntryPoint="Mono_Posix_Stdlib_EXIT_FAILURE")]
1041 private static extern int GetExitFailure();
1043 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1044 EntryPoint="Mono_Posix_Stdlib_EXIT_SUCCESS")]
1045 private static extern int GetExitSuccess ();
1047 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1048 EntryPoint="Mono_Posix_Stdlib_MB_CUR_MAX")]
1049 private static extern int GetMbCurMax ();
1051 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1052 EntryPoint="Mono_Posix_Stdlib_RAND_MAX")]
1053 private static extern int GetRandMax ();
1055 [CLSCompliant (false)]
1056 public static readonly int EXIT_FAILURE = GetExitFailure ();
1057 [CLSCompliant (false)]
1058 public static readonly int EXIT_SUCCESS = GetExitSuccess ();
1059 [CLSCompliant (false)]
1060 public static readonly int MB_CUR_MAX = GetMbCurMax ();
1061 [CLSCompliant (false)]
1062 public static readonly int RAND_MAX = GetRandMax ();
1064 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1065 public static extern int rand ();
1067 [CLSCompliant (false)]
1068 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1069 public static extern void srand (uint seed);
1072 // void *calloc (size_t nmemb, size_t size);
1073 [CLSCompliant (false)]
1074 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1075 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_calloc")]
1076 public static extern IntPtr calloc (ulong nmemb, ulong size);
1078 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1079 EntryPoint="Mono_Posix_Stdlib_free")]
1080 public static extern void free (IntPtr ptr);
1083 // void *malloc(size_t size);
1084 [CLSCompliant (false)]
1085 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1086 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_malloc")]
1087 public static extern IntPtr malloc (ulong size);
1090 // void *realloc(void *ptr, size_t size);
1091 [CLSCompliant (false)]
1092 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1093 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_realloc")]
1094 public static extern IntPtr realloc (IntPtr ptr, ulong size);
1096 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1097 public static extern void abort ();
1099 /* SKIP: atexit(3) -- the GC should have collected most references by the
1100 * time this runs, so no delegates should exist, making it pointless. */
1102 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1103 public static extern void exit (int status);
1105 [CLSCompliant (false)]
1106 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl)]
1107 public static extern void _Exit (int status);
1109 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, EntryPoint="getenv")]
1110 private static extern IntPtr sys_getenv (string name);
1112 public static string getenv (string name)
1114 IntPtr r = sys_getenv (name);
1115 return UnixMarshal.PtrToString (r);
1118 [CLSCompliant (false)]
1119 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl, SetLastError=true)]
1120 public static extern int system (string @string);
1126 private static object strerror_lock = new object ();
1128 [DllImport (LIBC, CallingConvention=CallingConvention.Cdecl,
1129 SetLastError=true, EntryPoint="strerror")]
1130 private static extern IntPtr sys_strerror (int errnum);
1132 [CLSCompliant (false)]
1133 public static string strerror (Errno errnum)
1135 int e = NativeConvert.FromErrno (errnum);
1136 lock (strerror_lock) {
1137 IntPtr r = sys_strerror (e);
1138 return UnixMarshal.PtrToString (r);
1143 // size_t strlen(const char *s);
1144 [CLSCompliant (false)]
1145 [DllImport (MPH, CallingConvention=CallingConvention.Cdecl,
1146 SetLastError=true, EntryPoint="Mono_Posix_Stdlib_strlen")]
1147 public static extern ulong strlen (IntPtr s);
1150 #endregion // Classes