2 // Mono.Unix/UnixMarshal.cs
5 // Jonathan Pryor (jonpryor@vt.edu)
7 // (C) 2004 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.
31 using System.Net.Sockets;
32 using System.Runtime.InteropServices;
33 using System.Runtime.Serialization;
39 // Scenario: We want to be able to translate an Error to a string.
40 // Problem: Thread-safety. Strerror(3) isn't thread safe (unless
41 // thread-local-variables are used, which is probably only
43 // Solution: Use strerror_r().
44 // Problem: strerror_r() isn't portable.
45 // (Apparently Solaris doesn't provide it.)
46 // Solution: Cry. Then introduce an intermediary, ErrorMarshal.
47 // ErrorMarshal exposes a single public delegate, Translator,
48 // which will convert an Error to a string. It's static
49 // constructor first tries using strerror_r(). If it works,
50 // great; use it in the future. If it doesn't work, fallback to
52 // This should be thread safe, since the check is done within the
53 // class constructor lock.
54 // Strerror(3) will be thread-safe from managed code, but won't
55 // be thread-safe between managed & unmanaged code.
56 internal class ErrorMarshal
58 internal delegate string ErrorTranslator (Error errno);
60 internal static readonly ErrorTranslator Translate;
62 static ErrorMarshal ()
65 Translate = new ErrorTranslator (strerror_r);
66 Translate (Error.ERANGE);
68 catch (EntryPointNotFoundException e) {
69 Translate = new ErrorTranslator (strerror);
73 private static string strerror (Error errno)
75 return Stdlib.strerror (errno);
78 private static string strerror_r (Error errno)
80 StringBuilder buf = new StringBuilder (16);
84 r = Syscall.strerror_r (errno, buf);
85 } while (r == -1 && Stdlib.GetLastError() == Error.ERANGE);
88 return "** Unknown error code: " + ((int) errno) + "**";
89 return buf.ToString();
93 public sealed /* static */ class UnixMarshal
95 private UnixMarshal () {}
97 [Obsolete ("Use GetErrorDescription (Mono.Unix.Native.Errno)")]
98 public static string GetErrorDescription (Error errno)
100 return ErrorMarshal.Translate (errno);
103 [CLSCompliant (false)]
104 public static string GetErrorDescription (Native.Errno errno)
106 return ErrorMarshal.Translate ((Error) (int) errno);
109 [Obsolete ("Use AllocHeap(long)")]
110 public static IntPtr Alloc (long size)
112 return AllocHeap (size);
115 public static IntPtr AllocHeap (long size)
118 throw new ArgumentOutOfRangeException ("size", "< 0");
119 return Stdlib.malloc ((ulong) size);
122 [Obsolete ("Use ReAllocHeap(long)")]
123 public static IntPtr ReAlloc (IntPtr ptr, long size)
125 return ReAllocHeap (ptr, size);
128 public static IntPtr ReAllocHeap (IntPtr ptr, long size)
131 throw new ArgumentOutOfRangeException ("size", "< 0");
132 return Stdlib.realloc (ptr, (ulong) size);
135 [Obsolete ("Use FreeHeap(IntPtr)")]
136 public static void Free (IntPtr ptr)
141 public static void FreeHeap (IntPtr ptr)
146 public static string PtrToString (IntPtr p)
148 if (p == IntPtr.Zero)
150 return PtrToString (p, UnixEncoding.Instance);
153 public static string PtrToString (IntPtr p, Encoding encoding)
155 if (p == IntPtr.Zero)
158 int len = GetStringByteLength (p, encoding);
159 byte[] string_buf = new byte [len];
160 Marshal.Copy (p, string_buf, 0, string_buf.Length);
162 // Due to variable-length encoding schemes, GetStringByteLength() may
163 // have returned multiple "null" characters. (For example, when
164 // encoding a string into UTF-8 there will be 4 terminating nulls.)
165 // We don't want these null's to be in the returned string, so strip
167 char[] chars = encoding.GetChars (string_buf);
169 while (len >= 0 && chars [--len] == 0)
171 return new string (chars, 0, len+1);
174 private static int GetStringByteLength (IntPtr p, Encoding encoding)
176 Type encodingType = encoding.GetType ();
180 // Encodings that will always end with a null byte
181 if (typeof(UTF8Encoding).IsAssignableFrom (encodingType) ||
182 typeof(UTF7Encoding).IsAssignableFrom (encodingType) ||
183 typeof(UnixEncoding).IsAssignableFrom (encodingType) ||
184 typeof(ASCIIEncoding).IsAssignableFrom (encodingType)) {
185 len = checked ((int) Native.Stdlib.strlen (p));
187 // Encodings that will always end with a 0x0000 16-bit word
188 else if (typeof(UnicodeEncoding).IsAssignableFrom (encodingType)) {
189 len = GetInt16BufferLength (p);
191 // Some non-public encoding, such as Latin1 or a DBCS charset.
192 // Look for a sequence of encoding.GetMaxByteCount() bytes that are all
193 // 0, which should be the terminating null.
194 // This is "iffy", since it may fail for variable-width encodings; for
195 // example, UTF8Encoding.GetMaxByteCount(1) = 4, so this would read 3
196 // bytes past the end of the string, possibly into garbage memory
197 // (which is why we special case UTF above).
199 len = GetRandomBufferLength (p, encoding.GetMaxByteCount(1));
203 throw new NotSupportedException ("Unable to determine native string buffer length");
207 private static int GetInt16BufferLength (IntPtr p)
210 while (Marshal.ReadInt16 (p, len*2) != 0)
212 return checked(len*2);
215 private static int GetInt32BufferLength (IntPtr p)
218 while (Marshal.ReadInt32 (p, len*4) != 0)
220 return checked(len*4);
223 private static int GetRandomBufferLength (IntPtr p, int nullLength)
225 switch (nullLength) {
226 case 1: return checked ((int) Native.Stdlib.strlen (p));
227 case 2: return GetInt16BufferLength (p);
228 case 4: return GetInt32BufferLength (p);
232 int num_null_seen = 0;
235 byte b = Marshal.ReadByte (p, len++);
240 } while (num_null_seen != nullLength);
246 * Marshal a C `char **'. ANSI C `main' requirements are assumed:
248 * stringArray is an array of pointers to C strings
249 * stringArray has a terminating NULL string.
252 * stringArray[0] = "string 1";
253 * stringArray[1] = "string 2";
254 * stringArray[2] = NULL
256 * The terminating NULL is required so that we know when to stop looking
259 public static string[] PtrToStringArray (IntPtr stringArray)
261 return PtrToStringArray (stringArray, UnixEncoding.Instance);
264 public static string[] PtrToStringArray (IntPtr stringArray, Encoding encoding)
266 if (stringArray == IntPtr.Zero)
267 return new string[]{};
269 int argc = CountStrings (stringArray);
270 return PtrToStringArray (argc, stringArray, encoding);
273 private static int CountStrings (IntPtr stringArray)
276 while (Marshal.ReadIntPtr (stringArray, count*IntPtr.Size) != IntPtr.Zero)
282 * Like PtrToStringArray(IntPtr), but it allows the user to specify how
283 * many strings to look for in the array. As such, the requirement for a
284 * terminating NULL element is not required.
286 * Usage is similar to ANSI C `main': count is argc, stringArray is argv.
287 * stringArray[count] is NOT accessed (though ANSI C requires that
288 * argv[argc] = NULL, which PtrToStringArray(IntPtr) requires).
290 public static string[] PtrToStringArray (int count, IntPtr stringArray)
292 return PtrToStringArray (count, stringArray, UnixEncoding.Instance);
295 public static string[] PtrToStringArray (int count, IntPtr stringArray, Encoding encoding)
298 throw new ArgumentOutOfRangeException ("count", "< 0");
299 if (stringArray == IntPtr.Zero)
300 return new string[count];
302 string[] members = new string[count];
303 for (int i = 0; i < count; ++i) {
304 IntPtr s = Marshal.ReadIntPtr (stringArray, i * IntPtr.Size);
305 members[i] = PtrToString (s, encoding);
311 [Obsolete ("Use StringToHeap(string)")]
312 public static IntPtr StringToAlloc (string s)
314 return StringToHeap (s, UnixEncoding.Instance);
317 public static IntPtr StringToHeap (string s)
319 return StringToHeap (s, UnixEncoding.Instance);
322 public static IntPtr StringToHeap (string s, Encoding encoding)
324 return StringToHeap (s, 0, s.Length, encoding);
327 public static IntPtr StringToHeap (string s, int index, int count)
329 return StringToHeap (s, index, count, UnixEncoding.Instance);
332 public static IntPtr StringToHeap (string s, int index, int count, Encoding encoding)
334 int min_byte_count = encoding.GetMaxByteCount(1);
335 char[] copy = s.ToCharArray (index, count);
336 byte[] marshal = new byte [encoding.GetByteCount (copy) + min_byte_count];
338 int bytes_copied = encoding.GetBytes (copy, 0, copy.Length, marshal, 0);
340 if (bytes_copied != (marshal.Length-min_byte_count))
341 throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
343 IntPtr mem = Alloc (marshal.Length);
344 if (mem == IntPtr.Zero)
345 throw new OutOfMemoryException ();
349 Marshal.Copy (marshal, 0, mem, marshal.Length);
360 public static bool ShouldRetrySyscall (int r)
362 if (r == -1 && Stdlib.GetLastError () == Error.EINTR)
367 [Obsolete ("Use ShouldRetrySyscall (int, out Mono.Unix.Native.Errno")]
368 public static bool ShouldRetrySyscall (int r, out Error error)
371 if (r == -1 && (error = Stdlib.GetLastError ()) == Error.EINTR)
376 [CLSCompliant (false)]
377 public static bool ShouldRetrySyscall (int r, out Native.Errno error)
379 error = (Native.Errno) 0;
380 if (r == -1 && (error = Native.Stdlib.GetLastError ()) == Native.Errno.EINTR)
385 // we can't permit any printf(3)-style formatting information, since that
386 // would kill the stack. However, replacing %% is silly, and some %* are
387 // permitted (such as %m in syslog to print strerror(errno)).
388 internal static string EscapeFormatString (string message,
393 StringBuilder sb = new StringBuilder (message.Length);
394 for (int i = 0; i < message.Length; ++i) {
395 char c = message [i];
397 if (c == '%' && (i+1) < message.Length) {
398 char n = message [i+1];
399 if (n == '%' || IsCharPresent (permitted, n))
402 sb.Append ('%').Append (n);
405 // invalid format string: % at EOS.
409 return sb.ToString ();
412 private static bool IsCharPresent (char[] array, char c)
416 for (int i = 0; i < array.Length; ++i)
422 [Obsolete ("Use CreateExceptionForError (Mono.Unix.Native.Errno)")]
423 internal static Exception CreateExceptionForError (Error errno)
425 string message = GetErrorDescription (errno);
426 UnixIOException p = new UnixIOException (errno);
428 case Error.EFAULT: return new NullReferenceException (message, p);
429 case Error.EINVAL: return new ArgumentException (message, p);
434 return new IOException (message, p);
435 case Error.ENAMETOOLONG: return new PathTooLongException (message, p);
436 case Error.ENOENT: return new FileNotFoundException (message, p);
437 case Error.ENOEXEC: return new InvalidProgramException (message, p);
438 case Error.EOVERFLOW: return new OverflowException (message, p);
439 case Error.ERANGE: return new ArgumentOutOfRangeException (message);
440 default: /* ignore */ break;
445 internal static Exception CreateExceptionForError (Native.Errno errno)
447 string message = GetErrorDescription (errno);
448 UnixIOException p = new UnixIOException (errno);
450 case Native.Errno.EFAULT: return new NullReferenceException (message, p);
451 case Native.Errno.EINVAL: return new ArgumentException (message, p);
452 case Native.Errno.EIO:
453 case Native.Errno.ENOSPC:
454 case Native.Errno.EROFS:
455 case Native.Errno.ESPIPE:
456 return new IOException (message, p);
457 case Native.Errno.ENAMETOOLONG: return new PathTooLongException (message, p);
458 case Native.Errno.ENOENT: return new FileNotFoundException (message, p);
459 case Native.Errno.ENOEXEC: return new InvalidProgramException (message, p);
460 case Native.Errno.EOVERFLOW: return new OverflowException (message, p);
461 case Native.Errno.ERANGE: return new ArgumentOutOfRangeException (message);
462 default: /* ignore */ break;
467 internal static Exception CreateExceptionForLastError ()
469 return CreateExceptionForError (Stdlib.GetLastError());
472 [Obsolete ("Use ThrowExceptionForError (Mono.Unix.Native.Errno)")]
473 public static void ThrowExceptionForError (Error errno)
475 throw CreateExceptionForError (errno);
478 [CLSCompliant (false)]
479 public static void ThrowExceptionForError (Native.Errno errno)
481 throw CreateExceptionForError (errno);
484 public static void ThrowExceptionForLastError ()
486 throw CreateExceptionForLastError ();
489 [Obsolete ("Use ThrowExceptionForErrorIf (int, Mono.Unix.Native.Errno)")]
490 public static void ThrowExceptionForErrorIf (int retval, Error errno)
493 ThrowExceptionForError (errno);
496 [CLSCompliant (false)]
497 public static void ThrowExceptionForErrorIf (int retval, Native.Errno errno)
500 ThrowExceptionForError (errno);
503 public static void ThrowExceptionForLastErrorIf (int retval)
506 ThrowExceptionForLastError ();