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 // Encodings that will always end with a 0x00000000 32-bit word
180 else if (typeof(UTF32Encoding).IsAssignableFrom (encodingType)) {
181 len = GetInt32BufferLength (p);
183 // Some non-public encoding, such as Latin1 or a DBCS charset.
184 // Look for a sequence of encoding.GetMaxByteCount() bytes that are all
185 // 0, which should be the terminating null.
186 // This is "iffy", since it may fail for variable-width encodings; for
187 // example, UTF8Encoding.GetMaxByteCount(1) = 4, so this would read 3
188 // bytes past the end of the string, possibly into garbage memory
189 // (which is why we special case UTF above).
191 len = GetRandomBufferLength (p, encoding.GetMaxByteCount(1));
195 throw new NotSupportedException ("Unable to determine native string buffer length");
199 private static int GetInt16BufferLength (IntPtr p)
202 while (Marshal.ReadInt16 (p, len*2) != 0)
204 return checked(len*2);
207 private static int GetInt32BufferLength (IntPtr p)
210 while (Marshal.ReadInt32 (p, len*4) != 0)
212 return checked(len*4);
215 private static int GetRandomBufferLength (IntPtr p, int nullLength)
217 switch (nullLength) {
218 case 1: return checked ((int) Native.Stdlib.strlen (p));
219 case 2: return GetInt16BufferLength (p);
220 case 4: return GetInt32BufferLength (p);
224 int num_null_seen = 0;
227 byte b = Marshal.ReadByte (p, len++);
232 } while (num_null_seen != nullLength);
238 * Marshal a C `char **'. ANSI C `main' requirements are assumed:
240 * stringArray is an array of pointers to C strings
241 * stringArray has a terminating NULL string.
244 * stringArray[0] = "string 1";
245 * stringArray[1] = "string 2";
246 * stringArray[2] = NULL
248 * The terminating NULL is required so that we know when to stop looking
251 public static string[] PtrToStringArray (IntPtr stringArray)
253 return PtrToStringArray (stringArray, UnixEncoding.Instance);
256 public static string[] PtrToStringArray (IntPtr stringArray, Encoding encoding)
258 if (stringArray == IntPtr.Zero)
259 return new string[]{};
261 int argc = CountStrings (stringArray);
262 return PtrToStringArray (argc, stringArray, encoding);
265 private static int CountStrings (IntPtr stringArray)
268 while (Marshal.ReadIntPtr (stringArray, count*IntPtr.Size) != IntPtr.Zero)
274 * Like PtrToStringArray(IntPtr), but it allows the user to specify how
275 * many strings to look for in the array. As such, the requirement for a
276 * terminating NULL element is not required.
278 * Usage is similar to ANSI C `main': count is argc, stringArray is argv.
279 * stringArray[count] is NOT accessed (though ANSI C requires that
280 * argv[argc] = NULL, which PtrToStringArray(IntPtr) requires).
282 public static string[] PtrToStringArray (int count, IntPtr stringArray)
284 return PtrToStringArray (count, stringArray, UnixEncoding.Instance);
287 public static string[] PtrToStringArray (int count, IntPtr stringArray, Encoding encoding)
290 throw new ArgumentOutOfRangeException ("count", "< 0");
291 if (encoding == null)
292 throw new ArgumentNullException ("encoding");
293 if (stringArray == IntPtr.Zero)
294 return new string[count];
296 string[] members = new string[count];
297 for (int i = 0; i < count; ++i) {
298 IntPtr s = Marshal.ReadIntPtr (stringArray, i * IntPtr.Size);
299 members[i] = PtrToString (s, encoding);
305 public static IntPtr StringToHeap (string s)
307 return StringToHeap (s, UnixEncoding.Instance);
310 public static IntPtr StringToHeap (string s, Encoding encoding)
312 return StringToHeap (s, 0, s.Length, encoding);
315 public static IntPtr StringToHeap (string s, int index, int count)
317 return StringToHeap (s, index, count, UnixEncoding.Instance);
320 public static IntPtr StringToHeap (string s, int index, int count, Encoding encoding)
325 if (encoding == null)
326 throw new ArgumentNullException ("encoding");
328 if (index < 0 || count < 0)
329 throw new ArgumentOutOfRangeException ((index < 0 ? "index" : "count"),
330 "Non - negative number required.");
332 if (s.Length - index < count)
333 throw new ArgumentOutOfRangeException ("s", "Index and count must refer to a location within the string.");
335 int null_terminator_count = encoding.GetMaxByteCount (1);
336 int length_without_null = encoding.GetByteCount (s);
337 int marshalLength = checked (length_without_null + null_terminator_count);
339 IntPtr mem = AllocHeap (marshalLength);
340 if (mem == IntPtr.Zero)
341 throw new UnixIOException (Native.Errno.ENOMEM);
344 fixed (char* p = s) {
345 byte* marshal = (byte*)mem;
349 bytes_copied = encoding.GetBytes (p + index, count, marshal, marshalLength);
355 if (bytes_copied != length_without_null) {
357 throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
360 marshal += length_without_null;
361 for (int i = 0; i < null_terminator_count; ++i)
369 public static bool ShouldRetrySyscall (int r)
371 if (r == -1 && Native.Stdlib.GetLastError () == Native.Errno.EINTR)
376 [CLSCompliant (false)]
377 public static bool ShouldRetrySyscall (int r, out Native.Errno errno)
379 errno = (Native.Errno) 0;
380 if (r == -1 && (errno = 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 internal static Exception CreateExceptionForError (Native.Errno errno)
424 string message = GetErrorDescription (errno);
425 UnixIOException p = new UnixIOException (errno);
427 // Ordering: Order alphabetically by exception first (right column),
428 // then order alphabetically by Errno value (left column) for the given
431 case Native.Errno.EBADF:
432 case Native.Errno.EINVAL: return new ArgumentException (message, p);
434 case Native.Errno.ERANGE: return new ArgumentOutOfRangeException (message);
435 case Native.Errno.ENOTDIR: return new DirectoryNotFoundException (message, p);
436 case Native.Errno.ENOENT: return new FileNotFoundException (message, p);
438 case Native.Errno.EOPNOTSUPP:
439 case Native.Errno.EPERM: return new InvalidOperationException (message, p);
441 case Native.Errno.ENOEXEC: return new InvalidProgramException (message, p);
443 case Native.Errno.EIO:
444 case Native.Errno.ENOSPC:
445 case Native.Errno.ENOTEMPTY:
446 case Native.Errno.ENXIO:
447 case Native.Errno.EROFS:
448 case Native.Errno.ESPIPE: return new IOException (message, p);
450 case Native.Errno.EFAULT: return new NullReferenceException (message, p);
451 case Native.Errno.EOVERFLOW: return new OverflowException (message, p);
452 case Native.Errno.ENAMETOOLONG: return new PathTooLongException (message, p);
454 case Native.Errno.EACCES:
455 case Native.Errno.EISDIR: return new UnauthorizedAccessException (message, p);
457 default: /* ignore */ break;
462 internal static Exception CreateExceptionForLastError ()
464 return CreateExceptionForError (Native.Stdlib.GetLastError());
467 [CLSCompliant (false)]
468 public static void ThrowExceptionForError (Native.Errno errno)
470 throw CreateExceptionForError (errno);
473 public static void ThrowExceptionForLastError ()
475 throw CreateExceptionForLastError ();
478 [CLSCompliant (false)]
479 public static void ThrowExceptionForErrorIf (int retval, Native.Errno errno)
482 ThrowExceptionForError (errno);
485 public static void ThrowExceptionForLastErrorIf (int retval)
488 ThrowExceptionForLastError ();