[Mono.Unix] Fix crasher in StringToHeap (#5639)
[mono.git] / mcs / class / Mono.Posix / Mono.Unix / UnixMarshal.cs
index 9c23aa8a4cb5a5f533f373978c83e8ac5072143f..7d39fd4c43ffad92bcf2f284a542482b63f0c4eb 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //   Jonathan Pryor (jonpryor@vt.edu)
 //
-// (C) 2004 Jonathan Pryor
+// (C) 2004-2006 Jonathan Pryor
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -55,7 +55,7 @@ namespace Mono.Unix {
        //            be thread-safe between managed & unmanaged code.
        internal class ErrorMarshal
        {
-               internal delegate string ErrorTranslator (Error errno);
+               internal delegate string ErrorTranslator (Native.Errno errno);
 
                internal static readonly ErrorTranslator Translate;
 
@@ -63,26 +63,26 @@ namespace Mono.Unix {
                {
                        try {
                                Translate = new ErrorTranslator (strerror_r);
-                               Translate (Error.ERANGE);
+                               Translate (Native.Errno.ERANGE);
                        }
-                       catch (EntryPointNotFoundException e) {
+                       catch (EntryPointNotFoundException) {
                                Translate = new ErrorTranslator (strerror);
                        }
                }
 
-               private static string strerror (Error errno)
+               private static string strerror (Native.Errno errno)
                {
-                       return Stdlib.strerror (errno);
+                       return Native.Stdlib.strerror (errno);
                }
 
-               private static string strerror_r (Error errno)
+               private static string strerror_r (Native.Errno errno)
                {
                        StringBuilder buf = new StringBuilder (16);
                        int r = 0;
                        do {
                                buf.Capacity *= 2;
-                               r = Syscall.strerror_r (errno, buf);
-                       } while (r == -1 && Stdlib.GetLastError() == Error.ERANGE);
+                               r = Native.Syscall.strerror_r (errno, buf);
+                       } while (r == -1 && Native.Stdlib.GetLastError() == Native.Errno.ERANGE);
 
                        if (r == -1)
                                return "** Unknown error code: " + ((int) errno) + "**";
@@ -94,53 +94,38 @@ namespace Mono.Unix {
        {
                private UnixMarshal () {}
 
-               [Obsolete ("Use GetErrorDescription (Mono.Unix.Native.Errno)")]
-               public static string GetErrorDescription (Error errno)
-               {
-                       return ErrorMarshal.Translate (errno);
-               }
-
                [CLSCompliant (false)]
                public static string GetErrorDescription (Native.Errno errno)
                {
-                       return ErrorMarshal.Translate ((Error) (int) errno);
-               }
-
-               [Obsolete ("Use AllocHeap(long)")]
-               public static IntPtr Alloc (long size)
-               {
-                       return AllocHeap (size);
+                       return ErrorMarshal.Translate (errno);
                }
 
                public static IntPtr AllocHeap (long size)
                {
                        if (size < 0)
                                throw new ArgumentOutOfRangeException ("size", "< 0");
-                       return Stdlib.malloc ((ulong) size);
-               }
-
-               [Obsolete ("Use ReAllocHeap(long)")]
-               public static IntPtr ReAlloc (IntPtr ptr, long size)
-               {
-                       return ReAllocHeap (ptr, size);
+                       return Native.Stdlib.malloc ((ulong) size);
                }
 
                public static IntPtr ReAllocHeap (IntPtr ptr, long size)
                {
                        if (size < 0)
                                throw new ArgumentOutOfRangeException ("size", "< 0");
-                       return Stdlib.realloc (ptr, (ulong) size);
+                       return Native.Stdlib.realloc (ptr, (ulong) size);
                }
 
-               [Obsolete ("Use FreeHeap(IntPtr)")]
-               public static void Free (IntPtr ptr)
+               public static void FreeHeap (IntPtr ptr)
                {
-                       FreeHeap (ptr);
+                       Native.Stdlib.free (ptr);
                }
 
-               public static void FreeHeap (IntPtr ptr)
+               public static unsafe string PtrToStringUnix (IntPtr p)
                {
-                       Stdlib.free (ptr);
+                       if (p == IntPtr.Zero)
+                               return null;
+
+                       int len = checked ((int) Native.Stdlib.strlen (p));
+                       return new string ((sbyte*) p, 0, len, UnixEncoding.Instance);
                }
 
                public static string PtrToString (IntPtr p)
@@ -150,25 +135,28 @@ namespace Mono.Unix {
                        return PtrToString (p, UnixEncoding.Instance);
                }
 
-               public static string PtrToString (IntPtr p, Encoding encoding)
+               public static unsafe string PtrToString (IntPtr p, Encoding encoding)
                {
                        if (p == IntPtr.Zero)
                                return null;
 
+                       if (encoding == null)
+                               throw new ArgumentNullException ("encoding");
+
                        int len = GetStringByteLength (p, encoding);
-                       byte[] string_buf = new byte [len];
-                       Marshal.Copy (p, string_buf, 0, string_buf.Length);
 
                        // Due to variable-length encoding schemes, GetStringByteLength() may
                        // have returned multiple "null" characters.  (For example, when
                        // encoding a string into UTF-8 there will be 4 terminating nulls.)
                        // We don't want these null's to be in the returned string, so strip
                        // them off.
-                       char[] chars = encoding.GetChars (string_buf);
-                       len = chars.Length;
-                       while (len >= 0 && chars [--len] == 0)
-                               ;
-                       return new string (chars, 0, len+1);
+                       string s = new string ((sbyte*) p, 0, len, encoding);
+                       len = s.Length;
+                       while (len > 0 && s [len-1] == 0)
+                               --len;
+                       if (len == s.Length) 
+                               return s;
+                       return s.Substring (0, len);
                }
 
                private static int GetStringByteLength (IntPtr p, Encoding encoding)
@@ -177,7 +165,7 @@ namespace Mono.Unix {
 
                        int len = -1;
 
-                       // Encodings that will always end with a null byte
+                       // Encodings that will always end with a single null byte
                        if (typeof(UTF8Encoding).IsAssignableFrom (encodingType) ||
                                        typeof(UTF7Encoding).IsAssignableFrom (encodingType) ||
                                        typeof(UnixEncoding).IsAssignableFrom (encodingType) ||
@@ -188,6 +176,10 @@ namespace Mono.Unix {
                        else if (typeof(UnicodeEncoding).IsAssignableFrom (encodingType)) {
                                len = GetInt16BufferLength (p);
                        }
+                       // Encodings that will always end with a 0x00000000 32-bit word
+                       else if (typeof(UTF32Encoding).IsAssignableFrom (encodingType)) {
+                               len = GetInt32BufferLength (p);
+                       }
                        // Some non-public encoding, such as Latin1 or a DBCS charset.
                        // Look for a sequence of encoding.GetMaxByteCount() bytes that are all
                        // 0, which should be the terminating null.
@@ -296,6 +288,8 @@ namespace Mono.Unix {
                {
                        if (count < 0)
                                throw new ArgumentOutOfRangeException ("count", "< 0");
+                       if (encoding == null)
+                               throw new ArgumentNullException ("encoding");
                        if (stringArray == IntPtr.Zero)
                                return new string[count];
 
@@ -308,12 +302,6 @@ namespace Mono.Unix {
                        return members;
                }
 
-               [Obsolete ("Use StringToHeap(string)")]
-               public static IntPtr StringToAlloc (string s)
-               {
-                       return StringToHeap (s, UnixEncoding.Instance);
-               }
-
                public static IntPtr StringToHeap (string s)
                {
                        return StringToHeap (s, UnixEncoding.Instance);
@@ -321,6 +309,9 @@ namespace Mono.Unix {
 
                public static IntPtr StringToHeap (string s, Encoding encoding)
                {
+                       if (s == null)
+                               return IntPtr.Zero;
+
                        return StringToHeap (s, 0, s.Length, encoding);
                }
 
@@ -331,27 +322,48 @@ namespace Mono.Unix {
 
                public static IntPtr StringToHeap (string s, int index, int count, Encoding encoding)
                {
-                       int min_byte_count = encoding.GetMaxByteCount(1);
-                       char[] copy = s.ToCharArray (index, count);
-                       byte[] marshal = new byte [encoding.GetByteCount (copy) + min_byte_count];
+                       if (s == null)
+                               return IntPtr.Zero;
 
-                       int bytes_copied = encoding.GetBytes (copy, 0, copy.Length, marshal, 0);
+                       if (encoding == null)
+                               throw new ArgumentNullException ("encoding");
 
-                       if (bytes_copied != (marshal.Length-min_byte_count))
-                               throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
+                       if (index < 0 || count < 0)
+                               throw new ArgumentOutOfRangeException ((index < 0 ? "index" : "count"),
+                                        "Non - negative number required.");
 
-                       IntPtr mem = Alloc (marshal.Length);
-                       if (mem == IntPtr.Zero)
-                               throw new OutOfMemoryException ();
+                       if (s.Length - index < count)
+                               throw new ArgumentOutOfRangeException ("s", "Index and count must refer to a location within the string.");
 
-                       bool copied = false;
-                       try {
-                               Marshal.Copy (marshal, 0, mem, marshal.Length);
-                               copied = true;
-                       }
-                       finally {
-                               if (!copied)
-                                       Free (mem);
+                       int null_terminator_count = encoding.GetMaxByteCount (1);
+                       int length_without_null = encoding.GetByteCount (s);
+                       int marshalLength = checked (length_without_null + null_terminator_count);
+
+                       IntPtr mem = AllocHeap (marshalLength);
+                       if (mem == IntPtr.Zero)
+                               throw new UnixIOException (Native.Errno.ENOMEM);
+
+                       unsafe {
+                               fixed (char* p = s) {
+                                       byte* marshal = (byte*)mem;
+                                       int bytes_copied;
+
+                                       try {
+                                               bytes_copied = encoding.GetBytes (p + index, count, marshal, marshalLength);
+                                       } catch {
+                                               FreeHeap (mem);
+                                               throw;
+                                       }
+
+                                       if (bytes_copied != length_without_null) {
+                                               FreeHeap (mem);
+                                               throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
+                                       }
+
+                                       marshal += length_without_null;
+                                       for (int i = 0; i < null_terminator_count; ++i)
+                                               marshal[i] = 0;
+                               }
                        }
 
                        return mem;
@@ -359,25 +371,16 @@ namespace Mono.Unix {
 
                public static bool ShouldRetrySyscall (int r)
                {
-                       if (r == -1 && Stdlib.GetLastError () == Error.EINTR)
-                               return true;
-                       return false;
-               }
-
-               [Obsolete ("Use ShouldRetrySyscall (int, out Mono.Unix.Native.Errno")]
-               public static bool ShouldRetrySyscall (int r, out Error error)
-               {
-                       error = (Error) 0;
-                       if (r == -1 && (error = Stdlib.GetLastError ()) == Error.EINTR)
+                       if (r == -1 && Native.Stdlib.GetLastError () == Native.Errno.EINTR)
                                return true;
                        return false;
                }
 
                [CLSCompliant (false)]
-               public static bool ShouldRetrySyscall (int r, out Native.Errno error)
+               public static bool ShouldRetrySyscall (int r, out Native.Errno errno)
                {
-                       error = (Native.Errno) 0;
-                       if (r == -1 && (error = Native.Stdlib.GetLastError ()) == Native.Errno.EINTR)
+                       errno = (Native.Errno) 0;
+                       if (r == -1 && (errno = Native.Stdlib.GetLastError ()) == Native.Errno.EINTR)
                                return true;
                        return false;
                }
@@ -419,46 +422,41 @@ namespace Mono.Unix {
                        return false;
                }
 
-               [Obsolete ("Use CreateExceptionForError (Mono.Unix.Native.Errno)")]
-               internal static Exception CreateExceptionForError (Error errno)
-               {
-                       string message = GetErrorDescription (errno);
-                       UnixIOException p = new UnixIOException (errno);
-                       switch (errno) {
-                               case Error.EFAULT:        return new NullReferenceException (message, p);
-                               case Error.EINVAL:        return new ArgumentException (message, p);
-                               case Error.EIO:
-                                 case Error.ENOSPC:
-                                 case Error.EROFS:
-                                 case Error.ESPIPE:
-                                       return new IOException (message, p);
-                               case Error.ENAMETOOLONG:  return new PathTooLongException (message, p);
-                               case Error.ENOENT:        return new FileNotFoundException (message, p);
-                               case Error.ENOEXEC:       return new InvalidProgramException (message, p);
-                               case Error.EOVERFLOW:     return new OverflowException (message, p);
-                               case Error.ERANGE:        return new ArgumentOutOfRangeException (message);
-                               default: /* ignore */     break;
-                       }
-                       return p;
-               }
-
                internal static Exception CreateExceptionForError (Native.Errno errno)
                {
                        string message = GetErrorDescription (errno);
                        UnixIOException p = new UnixIOException (errno);
+
+                       // Ordering: Order alphabetically by exception first (right column),
+                       // then order alphabetically by Errno value (left column) for the given
+                       // exception.
                        switch (errno) {
-                               case Native.Errno.EFAULT:        return new NullReferenceException (message, p);
+                               case Native.Errno.EBADF:
                                case Native.Errno.EINVAL:        return new ArgumentException (message, p);
-                               case Native.Errno.EIO:
-                                 case Native.Errno.ENOSPC:
-                                 case Native.Errno.EROFS:
-                                 case Native.Errno.ESPIPE:
-                                       return new IOException (message, p);
-                               case Native.Errno.ENAMETOOLONG:  return new PathTooLongException (message, p);
+
+                               case Native.Errno.ERANGE:        return new ArgumentOutOfRangeException (message);
+                               case Native.Errno.ENOTDIR:       return new DirectoryNotFoundException (message, p);
                                case Native.Errno.ENOENT:        return new FileNotFoundException (message, p);
+
+                               case Native.Errno.EOPNOTSUPP:
+                               case Native.Errno.EPERM:         return new InvalidOperationException (message, p);
+
                                case Native.Errno.ENOEXEC:       return new InvalidProgramException (message, p);
+
+                               case Native.Errno.EIO:
+                               case Native.Errno.ENOSPC:
+                               case Native.Errno.ENOTEMPTY:
+                               case Native.Errno.ENXIO:
+                               case Native.Errno.EROFS:
+                               case Native.Errno.ESPIPE:        return new IOException (message, p);
+
+                               case Native.Errno.EFAULT:        return new NullReferenceException (message, p);
                                case Native.Errno.EOVERFLOW:     return new OverflowException (message, p);
-                               case Native.Errno.ERANGE:        return new ArgumentOutOfRangeException (message);
+                               case Native.Errno.ENAMETOOLONG:  return new PathTooLongException (message, p);
+
+                               case Native.Errno.EACCES:
+                               case Native.Errno.EISDIR:        return new UnauthorizedAccessException (message, p);
+
                                default: /* ignore */     break;
                        }
                        return p;
@@ -466,13 +464,7 @@ namespace Mono.Unix {
 
                internal static Exception CreateExceptionForLastError ()
                {
-                       return CreateExceptionForError (Stdlib.GetLastError());
-               }
-
-               [Obsolete ("Use ThrowExceptionForError (Mono.Unix.Native.Errno)")]
-               public static void ThrowExceptionForError (Error errno)
-               {
-                       throw CreateExceptionForError (errno);
+                       return CreateExceptionForError (Native.Stdlib.GetLastError());
                }
 
                [CLSCompliant (false)]
@@ -486,13 +478,6 @@ namespace Mono.Unix {
                        throw CreateExceptionForLastError ();
                }
 
-               [Obsolete ("Use ThrowExceptionForErrorIf (int, Mono.Unix.Native.Errno)")]
-               public static void ThrowExceptionForErrorIf (int retval, Error errno)
-               {
-                       if (retval == -1)
-                               ThrowExceptionForError (errno);
-               }
-
                [CLSCompliant (false)]
                public static void ThrowExceptionForErrorIf (int retval, Native.Errno errno)
                {