* UnixMarshal.cs (StringToHeap): Check for null arguments.
[mono.git] / mcs / class / Mono.Posix / Mono.Unix / UnixMarshal.cs
1 //
2 // Mono.Unix/UnixMarshal.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //
7 // (C) 2004-2006 Jonathan Pryor
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28
29 using System;
30 using System.IO;
31 using System.Net.Sockets;
32 using System.Runtime.InteropServices;
33 using System.Runtime.Serialization;
34 using System.Text;
35 using Mono.Unix;
36
37 namespace Mono.Unix {
38
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 
42         //            true on Windows).
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
51         //            using strerror(3).
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
57         {
58                 internal delegate string ErrorTranslator (Native.Errno errno);
59
60                 internal static readonly ErrorTranslator Translate;
61
62                 static ErrorMarshal ()
63                 {
64                         try {
65                                 Translate = new ErrorTranslator (strerror_r);
66                                 Translate (Native.Errno.ERANGE);
67                         }
68                         catch (EntryPointNotFoundException) {
69                                 Translate = new ErrorTranslator (strerror);
70                         }
71                 }
72
73                 private static string strerror (Native.Errno errno)
74                 {
75                         return Native.Stdlib.strerror (errno);
76                 }
77
78                 private static string strerror_r (Native.Errno errno)
79                 {
80                         StringBuilder buf = new StringBuilder (16);
81                         int r = 0;
82                         do {
83                                 buf.Capacity *= 2;
84                                 r = Native.Syscall.strerror_r (errno, buf);
85                         } while (r == -1 && Native.Stdlib.GetLastError() == Native.Errno.ERANGE);
86
87                         if (r == -1)
88                                 return "** Unknown error code: " + ((int) errno) + "**";
89                         return buf.ToString();
90                 }
91         }
92
93         public sealed /* static */ class UnixMarshal
94         {
95                 private UnixMarshal () {}
96
97                 [CLSCompliant (false)]
98                 public static string GetErrorDescription (Native.Errno errno)
99                 {
100                         return ErrorMarshal.Translate (errno);
101                 }
102
103                 public static IntPtr AllocHeap (long size)
104                 {
105                         if (size < 0)
106                                 throw new ArgumentOutOfRangeException ("size", "< 0");
107                         return Native.Stdlib.malloc ((ulong) size);
108                 }
109
110                 public static IntPtr ReAllocHeap (IntPtr ptr, long size)
111                 {
112                         if (size < 0)
113                                 throw new ArgumentOutOfRangeException ("size", "< 0");
114                         return Native.Stdlib.realloc (ptr, (ulong) size);
115                 }
116
117                 public static void FreeHeap (IntPtr ptr)
118                 {
119                         Native.Stdlib.free (ptr);
120                 }
121
122                 public static unsafe string PtrToStringUnix (IntPtr p)
123                 {
124                         if (p == IntPtr.Zero)
125                                 return null;
126
127                         int len = checked ((int) Native.Stdlib.strlen (p));
128                         return new string ((sbyte*) p, 0, len, UnixEncoding.Instance);
129                 }
130
131                 public static string PtrToString (IntPtr p)
132                 {
133                         if (p == IntPtr.Zero)
134                                 return null;
135                         return PtrToString (p, UnixEncoding.Instance);
136                 }
137
138                 public static unsafe string PtrToString (IntPtr p, Encoding encoding)
139                 {
140                         if (p == IntPtr.Zero)
141                                 return null;
142
143                         int len = GetStringByteLength (p, encoding);
144
145                         // Due to variable-length encoding schemes, GetStringByteLength() may
146                         // have returned multiple "null" characters.  (For example, when
147                         // encoding a string into UTF-8 there will be 4 terminating nulls.)
148                         // We don't want these null's to be in the returned string, so strip
149                         // them off.
150                         string s = new string ((sbyte*) p, 0, len, encoding);
151                         len = s.Length;
152                         while (len > 0 && s [len-1] == 0)
153                                 --len;
154                         if (len == s.Length) 
155                                 return s;
156                         return s.Substring (0, len);
157                 }
158
159                 private static int GetStringByteLength (IntPtr p, Encoding encoding)
160                 {
161                         Type encodingType = encoding.GetType ();
162
163                         int len = -1;
164
165                         // Encodings that will always end with a single null byte
166                         if (typeof(UTF8Encoding).IsAssignableFrom (encodingType) ||
167                                         typeof(UTF7Encoding).IsAssignableFrom (encodingType) ||
168                                         typeof(UnixEncoding).IsAssignableFrom (encodingType) ||
169                                         typeof(ASCIIEncoding).IsAssignableFrom (encodingType)) {
170                                 len = checked ((int) Native.Stdlib.strlen (p));
171                         }
172                         // Encodings that will always end with a 0x0000 16-bit word
173                         else if (typeof(UnicodeEncoding).IsAssignableFrom (encodingType)) {
174                                 len = GetInt16BufferLength (p);
175                         }
176                         // Some non-public encoding, such as Latin1 or a DBCS charset.
177                         // Look for a sequence of encoding.GetMaxByteCount() bytes that are all
178                         // 0, which should be the terminating null.
179                         // This is "iffy", since it may fail for variable-width encodings; for
180                         // example, UTF8Encoding.GetMaxByteCount(1) = 4, so this would read 3
181                         // bytes past the end of the string, possibly into garbage memory
182                         // (which is why we special case UTF above).
183                         else {
184                                 len = GetRandomBufferLength (p, encoding.GetMaxByteCount(1));
185                         }
186
187                         if (len == -1)
188                                 throw new NotSupportedException ("Unable to determine native string buffer length");
189                         return len;
190                 }
191
192                 private static int GetInt16BufferLength (IntPtr p)
193                 {
194                         int len = 0;
195                         while (Marshal.ReadInt16 (p, len*2) != 0)
196                                 checked {++len;}
197                         return checked(len*2);
198                 }
199
200                 private static int GetInt32BufferLength (IntPtr p)
201                 {
202                         int len = 0;
203                         while (Marshal.ReadInt32 (p, len*4) != 0)
204                                 checked {++len;}
205                         return checked(len*4);
206                 }
207
208                 private static int GetRandomBufferLength (IntPtr p, int nullLength)
209                 {
210                         switch (nullLength) {
211                                 case 1: return checked ((int) Native.Stdlib.strlen (p));
212                                 case 2: return GetInt16BufferLength (p);
213                                 case 4: return GetInt32BufferLength (p);
214                         }
215
216                         int len = 0;
217                         int num_null_seen = 0;
218
219                         do {
220                                 byte b = Marshal.ReadByte (p, len++);
221                                 if (b == 0)
222                                         ++num_null_seen;
223                                 else
224                                         num_null_seen = 0;
225                         } while (num_null_seen != nullLength);
226
227                         return len;
228                 }
229
230                 /*
231                  * Marshal a C `char **'.  ANSI C `main' requirements are assumed:
232                  *
233                  *   stringArray is an array of pointers to C strings
234                  *   stringArray has a terminating NULL string.
235                  *
236                  * For example:
237                  *   stringArray[0] = "string 1";
238                  *   stringArray[1] = "string 2";
239                  *   stringArray[2] = NULL
240                  *
241                  * The terminating NULL is required so that we know when to stop looking
242                  * for strings.
243                  */
244                 public static string[] PtrToStringArray (IntPtr stringArray)
245                 {
246                         return PtrToStringArray (stringArray, UnixEncoding.Instance);
247                 }
248
249                 public static string[] PtrToStringArray (IntPtr stringArray, Encoding encoding)
250                 {
251                         if (stringArray == IntPtr.Zero)
252                                 return new string[]{};
253
254                         int argc = CountStrings (stringArray);
255                         return PtrToStringArray (argc, stringArray, encoding);
256                 }
257
258                 private static int CountStrings (IntPtr stringArray)
259                 {
260                         int count = 0;
261                         while (Marshal.ReadIntPtr (stringArray, count*IntPtr.Size) != IntPtr.Zero)
262                                 ++count;
263                         return count;
264                 }
265
266                 /*
267                  * Like PtrToStringArray(IntPtr), but it allows the user to specify how
268                  * many strings to look for in the array.  As such, the requirement for a
269                  * terminating NULL element is not required.
270                  *
271                  * Usage is similar to ANSI C `main': count is argc, stringArray is argv.
272                  * stringArray[count] is NOT accessed (though ANSI C requires that 
273                  * argv[argc] = NULL, which PtrToStringArray(IntPtr) requires).
274                  */
275                 public static string[] PtrToStringArray (int count, IntPtr stringArray)
276                 {
277                         return PtrToStringArray (count, stringArray, UnixEncoding.Instance);
278                 }
279
280                 public static string[] PtrToStringArray (int count, IntPtr stringArray, Encoding encoding)
281                 {
282                         if (count < 0)
283                                 throw new ArgumentOutOfRangeException ("count", "< 0");
284                         if (stringArray == IntPtr.Zero)
285                                 return new string[count];
286
287                         string[] members = new string[count];
288                         for (int i = 0; i < count; ++i) {
289                                 IntPtr s = Marshal.ReadIntPtr (stringArray, i * IntPtr.Size);
290                                 members[i] = PtrToString (s, encoding);
291                         }
292
293                         return members;
294                 }
295
296                 public static IntPtr StringToHeap (string s)
297                 {
298                         return StringToHeap (s, UnixEncoding.Instance);
299                 }
300
301                 public static IntPtr StringToHeap (string s, Encoding encoding)
302                 {
303                         return StringToHeap (s, 0, s.Length, encoding);
304                 }
305
306                 public static IntPtr StringToHeap (string s, int index, int count)
307                 {
308                         return StringToHeap (s, index, count, UnixEncoding.Instance);
309                 }
310
311                 public static IntPtr StringToHeap (string s, int index, int count, Encoding encoding)
312                 {
313                         if (s == null)
314                                 throw new ArgumentNullException ("s");
315                         if (encoding == null)
316                                 throw new ArgumentNullException ("encoding");
317
318                         int min_byte_count = encoding.GetMaxByteCount(1);
319                         char[] copy = s.ToCharArray (index, count);
320                         byte[] marshal = new byte [encoding.GetByteCount (copy) + min_byte_count];
321
322                         int bytes_copied = encoding.GetBytes (copy, 0, copy.Length, marshal, 0);
323
324                         if (bytes_copied != (marshal.Length-min_byte_count))
325                                 throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
326
327                         IntPtr mem = AllocHeap (marshal.Length);
328                         if (mem == IntPtr.Zero)
329                                 throw new UnixIOException (Native.Errno.ENOMEM);
330
331                         bool copied = false;
332                         try {
333                                 Marshal.Copy (marshal, 0, mem, marshal.Length);
334                                 copied = true;
335                         }
336                         finally {
337                                 if (!copied)
338                                         FreeHeap (mem);
339                         }
340
341                         return mem;
342                 }
343
344                 public static bool ShouldRetrySyscall (int r)
345                 {
346                         if (r == -1 && Native.Stdlib.GetLastError () == Native.Errno.EINTR)
347                                 return true;
348                         return false;
349                 }
350
351                 [CLSCompliant (false)]
352                 public static bool ShouldRetrySyscall (int r, out Native.Errno errno)
353                 {
354                         errno = (Native.Errno) 0;
355                         if (r == -1 && (errno = Native.Stdlib.GetLastError ()) == Native.Errno.EINTR)
356                                 return true;
357                         return false;
358                 }
359
360                 // we can't permit any printf(3)-style formatting information, since that
361                 // would kill the stack.  However, replacing %% is silly, and some %* are
362                 // permitted (such as %m in syslog to print strerror(errno)).
363                 internal static string EscapeFormatString (string message, 
364                                 char [] permitted)
365                 {
366                         if (message == null)
367                                 return "";
368                         StringBuilder sb = new StringBuilder (message.Length);
369                         for (int i = 0; i < message.Length; ++i) {
370                                 char c = message [i];
371                                 sb.Append (c);
372                                 if (c == '%' && (i+1) < message.Length) {
373                                         char n = message [i+1];
374                                         if (n == '%' || IsCharPresent (permitted, n))
375                                                 sb.Append (n);
376                                         else
377                                                 sb.Append ('%').Append (n);
378                                         ++i;
379                                 }
380                                 // invalid format string: % at EOS.
381                                 else if (c == '%')
382                                         sb.Append ('%');
383                         }
384                         return sb.ToString ();
385                 }
386
387                 private static bool IsCharPresent (char[] array, char c)
388                 {
389                         if (array == null)
390                                 return false;
391                         for (int i = 0; i < array.Length; ++i)
392                                 if (array [i] == c)
393                                         return true;
394                         return false;
395                 }
396
397                 internal static Exception CreateExceptionForError (Native.Errno errno)
398                 {
399                         string message = GetErrorDescription (errno);
400                         UnixIOException p = new UnixIOException (errno);
401
402                         // Ordering: Order alphabetically by exception first (right column),
403                         // then order alphabetically by Errno value (left column) for the given
404                         // exception.
405                         switch (errno) {
406                                 case Native.Errno.EBADF:
407                                 case Native.Errno.EINVAL:        return new ArgumentException (message, p);
408
409                                 case Native.Errno.ERANGE:        return new ArgumentOutOfRangeException (message);
410                                 case Native.Errno.ENOTDIR:       return new DirectoryNotFoundException (message, p);
411                                 case Native.Errno.ENOENT:        return new FileNotFoundException (message, p);
412
413                                 case Native.Errno.EOPNOTSUPP:
414                                 case Native.Errno.EPERM:         return new InvalidOperationException (message, p);
415
416                                 case Native.Errno.ENOEXEC:       return new InvalidProgramException (message, p);
417
418                                 case Native.Errno.EIO:
419                                 case Native.Errno.ENOSPC:
420                                 case Native.Errno.ENOTEMPTY:
421                                 case Native.Errno.ENXIO:
422                                 case Native.Errno.EROFS:
423                                 case Native.Errno.ESPIPE:        return new IOException (message, p);
424
425                                 case Native.Errno.EFAULT:        return new NullReferenceException (message, p);
426                                 case Native.Errno.EOVERFLOW:     return new OverflowException (message, p);
427                                 case Native.Errno.ENAMETOOLONG:  return new PathTooLongException (message, p);
428
429                                 case Native.Errno.EACCES:
430                                 case Native.Errno.EISDIR:        return new UnauthorizedAccessException (message, p);
431
432                                 default: /* ignore */     break;
433                         }
434                         return p;
435                 }
436
437                 internal static Exception CreateExceptionForLastError ()
438                 {
439                         return CreateExceptionForError (Native.Stdlib.GetLastError());
440                 }
441
442                 [CLSCompliant (false)]
443                 public static void ThrowExceptionForError (Native.Errno errno)
444                 {
445                         throw CreateExceptionForError (errno);
446                 }
447
448                 public static void ThrowExceptionForLastError ()
449                 {
450                         throw CreateExceptionForLastError ();
451                 }
452
453                 [CLSCompliant (false)]
454                 public static void ThrowExceptionForErrorIf (int retval, Native.Errno errno)
455                 {
456                         if (retval == -1)
457                                 ThrowExceptionForError (errno);
458                 }
459
460                 public static void ThrowExceptionForLastErrorIf (int retval)
461                 {
462                         if (retval == -1)
463                                 ThrowExceptionForLastError ();
464                 }
465         }
466 }
467
468 // vim: noexpandtab