2 // Mono.Unix/UnixMarshal.cs
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.
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 (Native.Errno errno);
60 internal static readonly ErrorTranslator Translate;
62 static ErrorMarshal ()
65 Translate = new ErrorTranslator (strerror_r);
66 Translate (Native.Errno.ERANGE);
68 catch (EntryPointNotFoundException) {
69 Translate = new ErrorTranslator (strerror);
73 private static string strerror (Native.Errno errno)
75 return Native.Stdlib.strerror (errno);
78 private static string strerror_r (Native.Errno errno)
80 StringBuilder buf = new StringBuilder (16);
84 r = Native.Syscall.strerror_r (errno, buf);
85 } while (r == -1 && Native.Stdlib.GetLastError() == Native.Errno.ERANGE);
88 return "** Unknown error code: " + ((int) errno) + "**";
89 return buf.ToString();
93 public sealed /* static */ class UnixMarshal
95 private UnixMarshal () {}
97 [CLSCompliant (false)]
98 public static string GetErrorDescription (Native.Errno errno)
100 return ErrorMarshal.Translate (errno);
103 public static IntPtr AllocHeap (long size)
106 throw new ArgumentOutOfRangeException ("size", "< 0");
107 return Native.Stdlib.malloc ((ulong) size);
110 public static IntPtr ReAllocHeap (IntPtr ptr, long size)
113 throw new ArgumentOutOfRangeException ("size", "< 0");
114 return Native.Stdlib.realloc (ptr, (ulong) size);
117 public static void FreeHeap (IntPtr ptr)
119 Native.Stdlib.free (ptr);
122 public static unsafe string PtrToStringUnix (IntPtr p)
124 if (p == IntPtr.Zero)
127 int len = checked ((int) Native.Stdlib.strlen (p));
128 return new string ((sbyte*) p, 0, len, UnixEncoding.Instance);
131 public static string PtrToString (IntPtr p)
133 if (p == IntPtr.Zero)
135 return PtrToString (p, UnixEncoding.Instance);
138 public static unsafe string PtrToString (IntPtr p, Encoding encoding)
140 if (p == IntPtr.Zero)
143 if (encoding == null)
144 throw new ArgumentNullException ("encoding");
146 int len = GetStringByteLength (p, encoding);
148 // Due to variable-length encoding schemes, GetStringByteLength() may
149 // have returned multiple "null" characters. (For example, when
150 // encoding a string into UTF-8 there will be 4 terminating nulls.)
151 // We don't want these null's to be in the returned string, so strip
153 string s = new string ((sbyte*) p, 0, len, encoding);
155 while (len > 0 && s [len-1] == 0)
159 return s.Substring (0, len);
162 private static int GetStringByteLength (IntPtr p, Encoding encoding)
164 Type encodingType = encoding.GetType ();
168 // Encodings that will always end with a single null byte
169 if (typeof(UTF8Encoding).IsAssignableFrom (encodingType) ||
170 typeof(UTF7Encoding).IsAssignableFrom (encodingType) ||
171 typeof(UnixEncoding).IsAssignableFrom (encodingType) ||
172 typeof(ASCIIEncoding).IsAssignableFrom (encodingType)) {
173 len = checked ((int) Native.Stdlib.strlen (p));
175 // Encodings that will always end with a 0x0000 16-bit word
176 else if (typeof(UnicodeEncoding).IsAssignableFrom (encodingType)) {
177 len = GetInt16BufferLength (p);
179 // Some non-public encoding, such as Latin1 or a DBCS charset.
180 // Look for a sequence of encoding.GetMaxByteCount() bytes that are all
181 // 0, which should be the terminating null.
182 // This is "iffy", since it may fail for variable-width encodings; for
183 // example, UTF8Encoding.GetMaxByteCount(1) = 4, so this would read 3
184 // bytes past the end of the string, possibly into garbage memory
185 // (which is why we special case UTF above).
187 len = GetRandomBufferLength (p, encoding.GetMaxByteCount(1));
191 throw new NotSupportedException ("Unable to determine native string buffer length");
195 private static int GetInt16BufferLength (IntPtr p)
198 while (Marshal.ReadInt16 (p, len*2) != 0)
200 return checked(len*2);
203 private static int GetInt32BufferLength (IntPtr p)
206 while (Marshal.ReadInt32 (p, len*4) != 0)
208 return checked(len*4);
211 private static int GetRandomBufferLength (IntPtr p, int nullLength)
213 switch (nullLength) {
214 case 1: return checked ((int) Native.Stdlib.strlen (p));
215 case 2: return GetInt16BufferLength (p);
216 case 4: return GetInt32BufferLength (p);
220 int num_null_seen = 0;
223 byte b = Marshal.ReadByte (p, len++);
228 } while (num_null_seen != nullLength);
234 * Marshal a C `char **'. ANSI C `main' requirements are assumed:
236 * stringArray is an array of pointers to C strings
237 * stringArray has a terminating NULL string.
240 * stringArray[0] = "string 1";
241 * stringArray[1] = "string 2";
242 * stringArray[2] = NULL
244 * The terminating NULL is required so that we know when to stop looking
247 public static string[] PtrToStringArray (IntPtr stringArray)
249 return PtrToStringArray (stringArray, UnixEncoding.Instance);
252 public static string[] PtrToStringArray (IntPtr stringArray, Encoding encoding)
254 if (stringArray == IntPtr.Zero)
255 return new string[]{};
257 int argc = CountStrings (stringArray);
258 return PtrToStringArray (argc, stringArray, encoding);
261 private static int CountStrings (IntPtr stringArray)
264 while (Marshal.ReadIntPtr (stringArray, count*IntPtr.Size) != IntPtr.Zero)
270 * Like PtrToStringArray(IntPtr), but it allows the user to specify how
271 * many strings to look for in the array. As such, the requirement for a
272 * terminating NULL element is not required.
274 * Usage is similar to ANSI C `main': count is argc, stringArray is argv.
275 * stringArray[count] is NOT accessed (though ANSI C requires that
276 * argv[argc] = NULL, which PtrToStringArray(IntPtr) requires).
278 public static string[] PtrToStringArray (int count, IntPtr stringArray)
280 return PtrToStringArray (count, stringArray, UnixEncoding.Instance);
283 public static string[] PtrToStringArray (int count, IntPtr stringArray, Encoding encoding)
286 throw new ArgumentOutOfRangeException ("count", "< 0");
287 if (encoding == null)
288 throw new ArgumentNullException ("encoding");
289 if (stringArray == IntPtr.Zero)
290 return new string[count];
292 string[] members = new string[count];
293 for (int i = 0; i < count; ++i) {
294 IntPtr s = Marshal.ReadIntPtr (stringArray, i * IntPtr.Size);
295 members[i] = PtrToString (s, encoding);
301 public static IntPtr StringToHeap (string s)
303 return StringToHeap (s, UnixEncoding.Instance);
306 public static IntPtr StringToHeap (string s, Encoding encoding)
308 return StringToHeap (s, 0, s.Length, encoding);
311 public static IntPtr StringToHeap (string s, int index, int count)
313 return StringToHeap (s, index, count, UnixEncoding.Instance);
316 public static IntPtr StringToHeap (string s, int index, int count, Encoding encoding)
321 if (encoding == null)
322 throw new ArgumentNullException ("encoding");
324 int min_byte_count = encoding.GetMaxByteCount(1);
325 char[] copy = s.ToCharArray (index, count);
326 byte[] marshal = new byte [encoding.GetByteCount (copy) + min_byte_count];
328 int bytes_copied = encoding.GetBytes (copy, 0, copy.Length, marshal, 0);
330 if (bytes_copied != (marshal.Length-min_byte_count))
331 throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
333 IntPtr mem = AllocHeap (marshal.Length);
334 if (mem == IntPtr.Zero)
335 throw new UnixIOException (Native.Errno.ENOMEM);
339 Marshal.Copy (marshal, 0, mem, marshal.Length);
350 public static bool ShouldRetrySyscall (int r)
352 if (r == -1 && Native.Stdlib.GetLastError () == Native.Errno.EINTR)
357 [CLSCompliant (false)]
358 public static bool ShouldRetrySyscall (int r, out Native.Errno errno)
360 errno = (Native.Errno) 0;
361 if (r == -1 && (errno = Native.Stdlib.GetLastError ()) == Native.Errno.EINTR)
366 // we can't permit any printf(3)-style formatting information, since that
367 // would kill the stack. However, replacing %% is silly, and some %* are
368 // permitted (such as %m in syslog to print strerror(errno)).
369 internal static string EscapeFormatString (string message,
374 StringBuilder sb = new StringBuilder (message.Length);
375 for (int i = 0; i < message.Length; ++i) {
376 char c = message [i];
378 if (c == '%' && (i+1) < message.Length) {
379 char n = message [i+1];
380 if (n == '%' || IsCharPresent (permitted, n))
383 sb.Append ('%').Append (n);
386 // invalid format string: % at EOS.
390 return sb.ToString ();
393 private static bool IsCharPresent (char[] array, char c)
397 for (int i = 0; i < array.Length; ++i)
403 internal static Exception CreateExceptionForError (Native.Errno errno)
405 string message = GetErrorDescription (errno);
406 UnixIOException p = new UnixIOException (errno);
408 // Ordering: Order alphabetically by exception first (right column),
409 // then order alphabetically by Errno value (left column) for the given
412 case Native.Errno.EBADF:
413 case Native.Errno.EINVAL: return new ArgumentException (message, p);
415 case Native.Errno.ERANGE: return new ArgumentOutOfRangeException (message);
416 case Native.Errno.ENOTDIR: return new DirectoryNotFoundException (message, p);
417 case Native.Errno.ENOENT: return new FileNotFoundException (message, p);
419 case Native.Errno.EOPNOTSUPP:
420 case Native.Errno.EPERM: return new InvalidOperationException (message, p);
422 case Native.Errno.ENOEXEC: return new InvalidProgramException (message, p);
424 case Native.Errno.EIO:
425 case Native.Errno.ENOSPC:
426 case Native.Errno.ENOTEMPTY:
427 case Native.Errno.ENXIO:
428 case Native.Errno.EROFS:
429 case Native.Errno.ESPIPE: return new IOException (message, p);
431 case Native.Errno.EFAULT: return new NullReferenceException (message, p);
432 case Native.Errno.EOVERFLOW: return new OverflowException (message, p);
433 case Native.Errno.ENAMETOOLONG: return new PathTooLongException (message, p);
435 case Native.Errno.EACCES:
436 case Native.Errno.EISDIR: return new UnauthorizedAccessException (message, p);
438 default: /* ignore */ break;
443 internal static Exception CreateExceptionForLastError ()
445 return CreateExceptionForError (Native.Stdlib.GetLastError());
448 [CLSCompliant (false)]
449 public static void ThrowExceptionForError (Native.Errno errno)
451 throw CreateExceptionForError (errno);
454 public static void ThrowExceptionForLastError ()
456 throw CreateExceptionForLastError ();
459 [CLSCompliant (false)]
460 public static void ThrowExceptionForErrorIf (int retval, Native.Errno errno)
463 ThrowExceptionForError (errno);
466 public static void ThrowExceptionForLastErrorIf (int retval)
469 ThrowExceptionForLastError ();