[corlib] ParseNumber.StringToInt now check for overflows.
[mono.git] / mono / metadata / file-io.c
1 /*
2  * file-io.c: File IO internal calls
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10  * Copyright 2012 Xamarin Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14
15 #include <glib.h>
16 #include <string.h>
17 #include <errno.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27
28 #include <mono/metadata/object.h>
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/metadata/file-io.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/appdomain.h>
33 #include <mono/metadata/marshal.h>
34 #include <mono/utils/strenc.h>
35 #include <utils/mono-io-portability.h>
36
37 #undef DEBUG
38
39 /* conversion functions */
40
41 static guint32 convert_mode(MonoFileMode mono_mode)
42 {
43         guint32 mode;
44
45         switch(mono_mode) {
46         case FileMode_CreateNew:
47                 mode=CREATE_NEW;
48                 break;
49         case FileMode_Create:
50                 mode=CREATE_ALWAYS;
51                 break;
52         case FileMode_Open:
53                 mode=OPEN_EXISTING;
54                 break;
55         case FileMode_OpenOrCreate:
56                 mode=OPEN_ALWAYS;
57                 break;
58         case FileMode_Truncate:
59                 mode=TRUNCATE_EXISTING;
60                 break;
61         case FileMode_Append:
62                 mode=OPEN_ALWAYS;
63                 break;
64         default:
65                 g_warning("System.IO.FileMode has unknown value 0x%x",
66                           mono_mode);
67                 /* Safe fallback */
68                 mode=OPEN_EXISTING;
69         }
70         
71         return(mode);
72 }
73
74 static guint32 convert_access(MonoFileAccess mono_access)
75 {
76         guint32 access;
77         
78         switch(mono_access) {
79         case FileAccess_Read:
80                 access=GENERIC_READ;
81                 break;
82         case FileAccess_Write:
83                 access=GENERIC_WRITE;
84                 break;
85         case FileAccess_ReadWrite:
86                 access=GENERIC_READ|GENERIC_WRITE;
87                 break;
88         default:
89                 g_warning("System.IO.FileAccess has unknown value 0x%x",
90                           mono_access);
91                 /* Safe fallback */
92                 access=GENERIC_READ;
93         }
94         
95         return(access);
96 }
97
98 static guint32 convert_share(MonoFileShare mono_share)
99 {
100         guint32 share = 0;
101         
102         if (mono_share & FileShare_Read) {
103                 share |= FILE_SHARE_READ;
104         }
105         if (mono_share & FileShare_Write) {
106                 share |= FILE_SHARE_WRITE;
107         }
108         if (mono_share & FileShare_Delete) {
109                 share |= FILE_SHARE_DELETE;
110         }
111         
112         if (mono_share & ~(FileShare_Read|FileShare_Write|FileShare_Delete)) {
113                 g_warning("System.IO.FileShare has unknown value 0x%x",
114                           mono_share);
115                 /* Safe fallback */
116                 share=0;
117         }
118
119         return(share);
120 }
121
122 #if 0
123 static guint32 convert_stdhandle(guint32 fd)
124 {
125         guint32 stdhandle;
126         
127         switch(fd) {
128         case 0:
129                 stdhandle=STD_INPUT_HANDLE;
130                 break;
131         case 1:
132                 stdhandle=STD_OUTPUT_HANDLE;
133                 break;
134         case 2:
135                 stdhandle=STD_ERROR_HANDLE;
136                 break;
137         default:
138                 g_warning("unknown standard file descriptor %d", fd);
139                 stdhandle=STD_INPUT_HANDLE;
140         }
141         
142         return(stdhandle);
143 }
144 #endif
145
146 static guint32 convert_seekorigin(MonoSeekOrigin origin)
147 {
148         guint32 w32origin;
149         
150         switch(origin) {
151         case SeekOrigin_Begin:
152                 w32origin=FILE_BEGIN;
153                 break;
154         case SeekOrigin_Current:
155                 w32origin=FILE_CURRENT;
156                 break;
157         case SeekOrigin_End:
158                 w32origin=FILE_END;
159                 break;
160         default:
161                 g_warning("System.IO.SeekOrigin has unknown value 0x%x",
162                           origin);
163                 /* Safe fallback */
164                 w32origin=FILE_CURRENT;
165         }
166         
167         return(w32origin);
168 }
169
170 static gint64 convert_filetime (const FILETIME *filetime)
171 {
172         guint64 ticks = filetime->dwHighDateTime;
173         ticks <<= 32;
174         ticks += filetime->dwLowDateTime;
175         return (gint64)ticks;
176 }
177
178 static void convert_win32_file_attribute_data (const WIN32_FILE_ATTRIBUTE_DATA *data, MonoIOStat *stat)
179 {
180         stat->attributes = data->dwFileAttributes;
181         stat->creation_time = convert_filetime (&data->ftCreationTime);
182         stat->last_access_time = convert_filetime (&data->ftLastAccessTime);
183         stat->last_write_time = convert_filetime (&data->ftLastWriteTime);
184         stat->length = ((gint64)data->nFileSizeHigh << 32) | data->nFileSizeLow;
185 }
186
187 /* Managed file attributes have nearly but not quite the same values
188  * as the w32 equivalents.
189  */
190 static guint32 convert_attrs(MonoFileAttributes attrs)
191 {
192         if(attrs & FileAttributes_Encrypted) {
193                 attrs |= FILE_ATTRIBUTE_ENCRYPTED;
194         }
195         
196         return(attrs);
197 }
198
199 /*
200  * On Win32, GetFileAttributes|Ex () seems to try opening the file,
201  * which might lead to sharing violation errors, whereas FindFirstFile
202  * always succeeds. These 2 wrappers resort to FindFirstFile if
203  * GetFileAttributes|Ex () has failed.
204  */
205 static guint32
206 get_file_attributes (const gunichar2 *path)
207 {
208         guint32 res;
209         WIN32_FIND_DATA find_data;
210         HANDLE find_handle;
211         gint32 error;
212
213         res = GetFileAttributes (path);
214         if (res != -1)
215                 return res;
216
217         error = GetLastError ();
218
219         if (error != ERROR_SHARING_VIOLATION)
220                 return res;
221
222         find_handle = FindFirstFile (path, &find_data);
223
224         if (find_handle == INVALID_HANDLE_VALUE)
225                 return res;
226
227         FindClose (find_handle);
228
229         return find_data.dwFileAttributes;
230 }
231
232 static gboolean
233 get_file_attributes_ex (const gunichar2 *path, WIN32_FILE_ATTRIBUTE_DATA *data)
234 {
235         gboolean res;
236         WIN32_FIND_DATA find_data;
237         HANDLE find_handle;
238         gint32 error;
239
240         res = GetFileAttributesEx (path, GetFileExInfoStandard, data);
241         if (res)
242                 return TRUE;
243
244         error = GetLastError ();
245
246         if (error != ERROR_SHARING_VIOLATION)
247                 return FALSE;
248
249         find_handle = FindFirstFile (path, &find_data);
250
251         if (find_handle == INVALID_HANDLE_VALUE)
252                 return FALSE;
253
254         FindClose (find_handle);
255
256         data->dwFileAttributes = find_data.dwFileAttributes;
257         data->ftCreationTime = find_data.ftCreationTime;
258         data->ftLastAccessTime = find_data.ftLastAccessTime;
259         data->ftLastWriteTime = find_data.ftLastWriteTime;
260         data->nFileSizeHigh = find_data.nFileSizeHigh;
261         data->nFileSizeLow = find_data.nFileSizeLow;
262         
263         return TRUE;
264 }
265
266 /* System.IO.MonoIO internal calls */
267
268 MonoBoolean
269 ves_icall_System_IO_MonoIO_CreateDirectory (MonoString *path, gint32 *error)
270 {
271         gboolean ret;
272         
273         *error=ERROR_SUCCESS;
274         
275         ret=CreateDirectory (mono_string_chars (path), NULL);
276         if(ret==FALSE) {
277                 *error=GetLastError ();
278         }
279         
280         return(ret);
281 }
282
283 MonoBoolean
284 ves_icall_System_IO_MonoIO_RemoveDirectory (MonoString *path, gint32 *error)
285 {
286         gboolean ret;
287         
288         *error=ERROR_SUCCESS;
289         
290         ret=RemoveDirectory (mono_string_chars (path));
291         if(ret==FALSE) {
292                 *error=GetLastError ();
293         }
294         
295         return(ret);
296 }
297
298 static gchar *
299 get_search_dir (MonoString *pattern)
300 {
301         gchar *p;
302         gchar *result;
303
304         p = mono_string_to_utf8 (pattern);
305         result = g_path_get_dirname (p);
306         g_free (p);
307         return result;
308 }
309
310 MonoArray *
311 ves_icall_System_IO_MonoIO_GetFileSystemEntries (MonoString *path,
312                                                  MonoString *path_with_pattern,
313                                                  gint attrs, gint mask,
314                                                  gint32 *error)
315 {
316         MonoDomain *domain;
317         MonoArray *result;
318         int i;
319         WIN32_FIND_DATA data;
320         HANDLE find_handle;
321         GPtrArray *names;
322         gchar *utf8_path, *utf8_result, *full_name;
323         gint32 attributes;
324         
325         result = NULL;
326         *error = ERROR_SUCCESS;
327
328         domain = mono_domain_get ();
329         mask = convert_attrs (mask);
330         attributes = get_file_attributes (mono_string_chars (path));
331         if (attributes != -1) {
332                 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
333                         *error = ERROR_INVALID_NAME;
334                         goto leave;
335                 }
336         } else {
337                 *error = GetLastError ();
338                 goto leave;
339         }
340         
341         find_handle = FindFirstFile (mono_string_chars (path_with_pattern), &data);
342         if (find_handle == INVALID_HANDLE_VALUE) {
343                 gint32 find_error = GetLastError ();
344                 
345                 if (find_error == ERROR_FILE_NOT_FOUND || find_error == ERROR_NO_MORE_FILES) {
346                         /* No files, so just return an empty array */
347                         goto leave;
348                 }
349                 
350                 *error = find_error;
351                 goto leave;
352         }
353
354         utf8_path = get_search_dir (path_with_pattern);
355         names = g_ptr_array_new ();
356
357         do {
358                 if ((data.cFileName[0] == '.' && data.cFileName[1] == 0) ||
359                     (data.cFileName[0] == '.' && data.cFileName[1] == '.' && data.cFileName[2] == 0)) {
360                         continue;
361                 }
362                 
363                 if ((data.dwFileAttributes & mask) == attrs) {
364                         utf8_result = g_utf16_to_utf8 (data.cFileName, -1, NULL, NULL, NULL);
365                         if (utf8_result == NULL) {
366                                 continue;
367                         }
368                         
369                         full_name = g_build_filename (utf8_path, utf8_result, NULL);
370                         g_ptr_array_add (names, full_name);
371
372                         g_free (utf8_result);
373                 }
374         } while(FindNextFile (find_handle, &data));
375
376         if (FindClose (find_handle) == FALSE) {
377                 *error = GetLastError ();
378                 result = NULL;
379         } else {
380                 result = mono_array_new (domain, mono_defaults.string_class, names->len);
381                 for (i = 0; i < names->len; i++) {
382                         mono_array_setref (result, i, mono_string_new (domain, g_ptr_array_index (names, i)));
383                 }
384         }
385
386         for (i = 0; i < names->len; i++) {
387                 g_free (g_ptr_array_index (names, i));
388         }
389         g_ptr_array_free (names, TRUE);
390         g_free (utf8_path);
391
392 leave:
393         // If there's no array and no error, then return an empty array.
394         if (result == NULL && *error == ERROR_SUCCESS)
395                 result = mono_array_new (domain, mono_defaults.string_class, 0);
396
397         return result;
398 }
399
400 typedef struct {
401         MonoDomain *domain;
402         gchar *utf8_path;
403         HANDLE find_handle;
404 } IncrementalFind;
405         
406 static gboolean
407 incremental_find_check_match (IncrementalFind *handle, WIN32_FIND_DATA *data, MonoString **result)
408 {
409         gchar *utf8_result;
410         gchar *full_name;
411         
412         if ((data->cFileName[0] == '.' && data->cFileName[1] == 0) || (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0))
413                 return FALSE;
414
415         utf8_result = g_utf16_to_utf8 (data->cFileName, -1, NULL, NULL, NULL);
416         if (utf8_result == NULL) 
417                 return FALSE;
418         
419         full_name = g_build_filename (handle->utf8_path, utf8_result, NULL);
420         g_free (utf8_result);
421         *result = mono_string_new (mono_domain_get (), full_name);
422         g_free (full_name);
423         
424         return TRUE;
425 }
426
427 MonoString *
428 ves_icall_System_IO_MonoIO_FindFirst (MonoString *path,
429                                       MonoString *path_with_pattern,
430                                       gint32 *result_attr, gint32 *error,
431                                       gpointer *handle)
432 {
433         WIN32_FIND_DATA data;
434         HANDLE find_handle;
435         IncrementalFind *ifh;
436         MonoString *result;
437         
438         *error = ERROR_SUCCESS;
439         
440         find_handle = FindFirstFile (mono_string_chars (path_with_pattern), &data);
441         
442         if (find_handle == INVALID_HANDLE_VALUE) {
443                 gint32 find_error = GetLastError ();
444                 *handle = NULL;
445                 
446                 if (find_error == ERROR_FILE_NOT_FOUND) 
447                         return NULL;
448                 
449                 *error = find_error;
450                 return NULL;
451         }
452
453         ifh = g_new (IncrementalFind, 1);
454         ifh->find_handle = find_handle;
455         ifh->utf8_path = mono_string_to_utf8 (path);
456         ifh->domain = mono_domain_get ();
457         *handle = ifh;
458
459         while (incremental_find_check_match (ifh, &data, &result) == 0){
460                 if (FindNextFile (find_handle, &data) == FALSE){
461                         int e = GetLastError ();
462                         if (e != ERROR_NO_MORE_FILES)
463                                 *error = e;
464                         return NULL;
465                 }
466         }
467         *result_attr = data.dwFileAttributes;
468         
469         return result;
470 }
471
472 MonoString *
473 ves_icall_System_IO_MonoIO_FindNext (gpointer handle, gint32 *result_attr, gint32 *error)
474 {
475         IncrementalFind *ifh = handle;
476         WIN32_FIND_DATA data;
477         MonoString *result;
478
479         *error = ERROR_SUCCESS;
480         do {
481                 if (FindNextFile (ifh->find_handle, &data) == FALSE){
482                         int e = GetLastError ();
483                         if (e != ERROR_NO_MORE_FILES)
484                                 *error = e;
485                         return NULL;
486                 }
487         } while (incremental_find_check_match (ifh, &data, &result) == 0);
488
489         *result_attr = data.dwFileAttributes;
490         return result;
491 }
492
493 int
494 ves_icall_System_IO_MonoIO_FindClose (gpointer handle)
495 {
496         IncrementalFind *ifh = handle;
497         gint32 error;
498         
499         if (FindClose (ifh->find_handle) == FALSE){
500                 error = GetLastError ();
501         } else
502                 error = ERROR_SUCCESS;
503         g_free (ifh->utf8_path);
504         g_free (ifh);
505
506         return error;
507 }
508
509 MonoString *
510 ves_icall_System_IO_MonoIO_GetCurrentDirectory (gint32 *error)
511 {
512         MonoString *result;
513         gunichar2 *buf;
514         int len, res_len;
515
516         len = MAX_PATH + 1; /*FIXME this is too smal under most unix systems.*/
517         buf = g_new (gunichar2, len);
518         
519         *error=ERROR_SUCCESS;
520         result = NULL;
521
522         res_len = GetCurrentDirectory (len, buf);
523         if (res_len > len) { /*buf is too small.*/
524                 int old_res_len = res_len;
525                 g_free (buf);
526                 buf = g_new (gunichar2, res_len);
527                 res_len = GetCurrentDirectory (res_len, buf) == old_res_len;
528         }
529         
530         if (res_len) {
531                 len = 0;
532                 while (buf [len])
533                         ++ len;
534
535                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
536         } else {
537                 *error=GetLastError ();
538         }
539
540         g_free (buf);
541         return result;
542 }
543
544 MonoBoolean
545 ves_icall_System_IO_MonoIO_SetCurrentDirectory (MonoString *path,
546                                                 gint32 *error)
547 {
548         gboolean ret;
549         
550         *error=ERROR_SUCCESS;
551         
552         ret=SetCurrentDirectory (mono_string_chars (path));
553         if(ret==FALSE) {
554                 *error=GetLastError ();
555         }
556         
557         return(ret);
558 }
559
560 MonoBoolean
561 ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest,
562                                      gint32 *error)
563 {
564         gboolean ret;
565         
566         *error=ERROR_SUCCESS;
567         
568         ret=MoveFile (mono_string_chars (path), mono_string_chars (dest));
569         if(ret==FALSE) {
570                 *error=GetLastError ();
571         }
572         
573         return(ret);
574 }
575
576 MonoBoolean
577 ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *destinationFileName,
578                                         MonoString *destinationBackupFileName, MonoBoolean ignoreMetadataErrors,
579                                         gint32 *error)
580 {
581         gboolean ret;
582         gunichar2 *utf16_sourceFileName = NULL, *utf16_destinationFileName = NULL, *utf16_destinationBackupFileName = NULL;
583         guint32 replaceFlags = REPLACEFILE_WRITE_THROUGH;
584
585         if (sourceFileName)
586                 utf16_sourceFileName = mono_string_chars (sourceFileName);
587         if (destinationFileName)
588                 utf16_destinationFileName = mono_string_chars (destinationFileName);
589         if (destinationBackupFileName)
590                 utf16_destinationBackupFileName = mono_string_chars (destinationBackupFileName);
591
592         *error = ERROR_SUCCESS;
593         if (ignoreMetadataErrors)
594                 replaceFlags |= REPLACEFILE_IGNORE_MERGE_ERRORS;
595
596         /* FIXME: source and destination file names must not be NULL, but apparently they might be! */
597         ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
598                          replaceFlags, NULL, NULL);
599         if (ret == FALSE)
600                 *error = GetLastError ();
601
602         return ret;
603 }
604
605 MonoBoolean
606 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
607                                      MonoBoolean overwrite, gint32 *error)
608 {
609         gboolean ret;
610         
611         *error=ERROR_SUCCESS;
612         
613         ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
614         if(ret==FALSE) {
615                 *error=GetLastError ();
616         }
617         
618         return(ret);
619 }
620
621 MonoBoolean
622 ves_icall_System_IO_MonoIO_DeleteFile (MonoString *path, gint32 *error)
623 {
624         gboolean ret;
625         
626         *error=ERROR_SUCCESS;
627         
628         ret=DeleteFile (mono_string_chars (path));
629         if(ret==FALSE) {
630                 *error=GetLastError ();
631         }
632         
633         return(ret);
634 }
635
636 gint32 
637 ves_icall_System_IO_MonoIO_GetFileAttributes (MonoString *path, gint32 *error)
638 {
639         gint32 ret;
640         
641         *error=ERROR_SUCCESS;
642         
643         ret=get_file_attributes (mono_string_chars (path));
644
645         /* 
646          * The definition of INVALID_FILE_ATTRIBUTES in the cygwin win32
647          * headers is wrong, hence this temporary workaround.
648          * See
649          * http://cygwin.com/ml/cygwin/2003-09/msg01771.html
650          */
651         if (ret==-1) {
652           /* if(ret==INVALID_FILE_ATTRIBUTES) { */
653                 *error=GetLastError ();
654         }
655         
656         return(ret);
657 }
658
659 MonoBoolean
660 ves_icall_System_IO_MonoIO_SetFileAttributes (MonoString *path, gint32 attrs,
661                                               gint32 *error)
662 {
663         gboolean ret;
664         
665         *error=ERROR_SUCCESS;
666         
667         ret=SetFileAttributes (mono_string_chars (path),
668                                convert_attrs (attrs));
669         if(ret==FALSE) {
670                 *error=GetLastError ();
671         }
672         
673         return(ret);
674 }
675
676 gint32
677 ves_icall_System_IO_MonoIO_GetFileType (HANDLE handle, gint32 *error)
678 {
679         gboolean ret;
680         
681         *error=ERROR_SUCCESS;
682         
683         ret=GetFileType (handle);
684         if(ret==FILE_TYPE_UNKNOWN) {
685                 /* Not necessarily an error, but the caller will have
686                  * to decide based on the error value.
687                  */
688                 *error=GetLastError ();
689         }
690         
691         return(ret);
692 }
693
694 MonoBoolean
695 ves_icall_System_IO_MonoIO_GetFileStat (MonoString *path, MonoIOStat *stat,
696                                         gint32 *error)
697 {
698         gboolean result;
699         WIN32_FILE_ATTRIBUTE_DATA data;
700
701         *error=ERROR_SUCCESS;
702         
703         result = get_file_attributes_ex (mono_string_chars (path), &data);
704
705         if (result) {
706                 convert_win32_file_attribute_data (&data, stat);
707         } else {
708                 *error=GetLastError ();
709                 memset (stat, 0, sizeof (MonoIOStat));
710         }
711
712         return result;
713 }
714
715 HANDLE 
716 ves_icall_System_IO_MonoIO_Open (MonoString *filename, gint32 mode,
717                                  gint32 access_mode, gint32 share, gint32 options,
718                                  gint32 *error)
719 {
720         HANDLE ret;
721         int attributes, attrs;
722         gunichar2 *chars = mono_string_chars (filename);
723         
724         *error=ERROR_SUCCESS;
725
726         if (options != 0){
727                 if (options & FileOptions_Encrypted)
728                         attributes = FILE_ATTRIBUTE_ENCRYPTED;
729                 else
730                         attributes = FILE_ATTRIBUTE_NORMAL;
731                 if (options & FileOptions_DeleteOnClose)
732                         attributes |= FILE_FLAG_DELETE_ON_CLOSE;
733                 if (options & FileOptions_SequentialScan)
734                         attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
735                 if (options & FileOptions_RandomAccess)
736                         attributes |= FILE_FLAG_RANDOM_ACCESS;
737
738                 if (options & FileOptions_Temporary)
739                         attributes |= FILE_ATTRIBUTE_TEMPORARY;
740                 
741                 /* Not sure if we should set FILE_FLAG_OVERLAPPED, how does this mix with the "Async" bool here? */
742                 if (options & FileOptions_Asynchronous)
743                         attributes |= FILE_FLAG_OVERLAPPED;
744                 
745                 if (options & FileOptions_WriteThrough)
746                         attributes |= FILE_FLAG_WRITE_THROUGH;
747         } else
748                 attributes = FILE_ATTRIBUTE_NORMAL;
749
750         /* If we're opening a directory we need to set the extra flag
751          */
752         attrs = get_file_attributes (chars);
753         if (attrs != INVALID_FILE_ATTRIBUTES) {
754                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
755                         attributes |= FILE_FLAG_BACKUP_SEMANTICS;
756                 }
757         }
758         
759         ret=CreateFile (chars, convert_access (access_mode),
760                         convert_share (share), NULL, convert_mode (mode),
761                         attributes, NULL);
762         if(ret==INVALID_HANDLE_VALUE) {
763                 *error=GetLastError ();
764         } 
765         
766         return(ret);
767 }
768
769 MonoBoolean
770 ves_icall_System_IO_MonoIO_Close (HANDLE handle, gint32 *error)
771 {
772         gboolean ret;
773         
774         *error=ERROR_SUCCESS;
775         
776         ret=CloseHandle (handle);
777         if(ret==FALSE) {
778                 *error=GetLastError ();
779         }
780         
781         return(ret);
782 }
783
784 gint32 
785 ves_icall_System_IO_MonoIO_Read (HANDLE handle, MonoArray *dest,
786                                  gint32 dest_offset, gint32 count,
787                                  gint32 *error)
788 {
789         guchar *buffer;
790         gboolean result;
791         guint32 n;
792
793         *error=ERROR_SUCCESS;
794
795         MONO_CHECK_ARG_NULL (dest, 0);
796
797         if (dest_offset > mono_array_length (dest) - count) {
798                 mono_set_pending_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
799                 return 0;
800         }
801
802         buffer = mono_array_addr (dest, guchar, dest_offset);
803         result = ReadFile (handle, buffer, count, &n, NULL);
804
805         if (!result) {
806                 *error=GetLastError ();
807                 return -1;
808         }
809
810         return (gint32)n;
811 }
812
813 gint32 
814 ves_icall_System_IO_MonoIO_Write (HANDLE handle, MonoArray *src,
815                                   gint32 src_offset, gint32 count,
816                                   gint32 *error)
817 {
818         guchar *buffer;
819         gboolean result;
820         guint32 n;
821
822         *error=ERROR_SUCCESS;
823
824         MONO_CHECK_ARG_NULL (src, 0);
825         
826         if (src_offset > mono_array_length (src) - count) {
827                 mono_set_pending_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
828                 return 0;
829         }
830         
831         buffer = mono_array_addr (src, guchar, src_offset);
832         result = WriteFile (handle, buffer, count, &n, NULL);
833
834         if (!result) {
835                 *error=GetLastError ();
836                 return -1;
837         }
838
839         return (gint32)n;
840 }
841
842 gint64 
843 ves_icall_System_IO_MonoIO_Seek (HANDLE handle, gint64 offset, gint32 origin,
844                                  gint32 *error)
845 {
846         gint32 offset_hi;
847
848         *error=ERROR_SUCCESS;
849         
850         offset_hi = offset >> 32;
851         offset = SetFilePointer (handle, (gint32) (offset & 0xFFFFFFFF), &offset_hi,
852                                  convert_seekorigin (origin));
853
854         if(offset==INVALID_SET_FILE_POINTER) {
855                 *error=GetLastError ();
856         }
857         
858         return offset | ((gint64)offset_hi << 32);
859 }
860
861 MonoBoolean
862 ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
863 {
864         gboolean ret;
865         
866         *error=ERROR_SUCCESS;
867         
868         ret=FlushFileBuffers (handle);
869         if(ret==FALSE) {
870                 *error=GetLastError ();
871         }
872         
873         return(ret);
874 }
875
876 gint64 
877 ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
878 {
879         gint64 length;
880         guint32 length_hi;
881
882         *error=ERROR_SUCCESS;
883         
884         length = GetFileSize (handle, &length_hi);
885         if(length==INVALID_FILE_SIZE) {
886                 *error=GetLastError ();
887         }
888         
889         return length | ((gint64)length_hi << 32);
890 }
891
892 MonoBoolean
893 ves_icall_System_IO_MonoIO_SetLength (HANDLE handle, gint64 length,
894                                       gint32 *error)
895 {
896         gint64 offset, offset_set;
897         gint32 offset_hi;
898         gint32 length_hi;
899         gboolean result;
900
901         *error=ERROR_SUCCESS;
902         
903         /* save file pointer */
904
905         offset_hi = 0;
906         offset = SetFilePointer (handle, 0, &offset_hi, FILE_CURRENT);
907         if(offset==INVALID_SET_FILE_POINTER) {
908                 *error=GetLastError ();
909                 return(FALSE);
910         }
911
912         /* extend or truncate */
913
914         length_hi = length >> 32;
915         offset_set=SetFilePointer (handle, length & 0xFFFFFFFF, &length_hi,
916                                    FILE_BEGIN);
917         if(offset_set==INVALID_SET_FILE_POINTER) {
918                 *error=GetLastError ();
919                 return(FALSE);
920         }
921
922         result = SetEndOfFile (handle);
923         if(result==FALSE) {
924                 *error=GetLastError ();
925                 return(FALSE);
926         }
927
928         /* restore file pointer */
929
930         offset_set=SetFilePointer (handle, offset & 0xFFFFFFFF, &offset_hi,
931                                    FILE_BEGIN);
932         if(offset_set==INVALID_SET_FILE_POINTER) {
933                 *error=GetLastError ();
934                 return(FALSE);
935         }
936
937         return result;
938 }
939
940 MonoBoolean
941 ves_icall_System_IO_MonoIO_SetFileTime (HANDLE handle, gint64 creation_time,
942                                         gint64 last_access_time,
943                                         gint64 last_write_time, gint32 *error)
944 {
945         gboolean ret;
946         const FILETIME *creation_filetime;
947         const FILETIME *last_access_filetime;
948         const FILETIME *last_write_filetime;
949
950         *error=ERROR_SUCCESS;
951         
952         if (creation_time < 0)
953                 creation_filetime = NULL;
954         else
955                 creation_filetime = (FILETIME *)&creation_time;
956
957         if (last_access_time < 0)
958                 last_access_filetime = NULL;
959         else
960                 last_access_filetime = (FILETIME *)&last_access_time;
961
962         if (last_write_time < 0)
963                 last_write_filetime = NULL;
964         else
965                 last_write_filetime = (FILETIME *)&last_write_time;
966
967         ret=SetFileTime (handle, creation_filetime, last_access_filetime, last_write_filetime);
968         if(ret==FALSE) {
969                 *error=GetLastError ();
970         }
971         
972         return(ret);
973 }
974
975 HANDLE 
976 ves_icall_System_IO_MonoIO_get_ConsoleOutput ()
977 {
978         return GetStdHandle (STD_OUTPUT_HANDLE);
979 }
980
981 HANDLE 
982 ves_icall_System_IO_MonoIO_get_ConsoleInput ()
983 {
984         return GetStdHandle (STD_INPUT_HANDLE);
985 }
986
987 HANDLE 
988 ves_icall_System_IO_MonoIO_get_ConsoleError ()
989 {
990         return GetStdHandle (STD_ERROR_HANDLE);
991 }
992
993 MonoBoolean
994 ves_icall_System_IO_MonoIO_CreatePipe (HANDLE *read_handle,
995                                        HANDLE *write_handle)
996 {
997         SECURITY_ATTRIBUTES attr;
998         gboolean ret;
999         
1000         attr.nLength=sizeof(SECURITY_ATTRIBUTES);
1001         attr.bInheritHandle=TRUE;
1002         attr.lpSecurityDescriptor=NULL;
1003         
1004         ret=CreatePipe (read_handle, write_handle, &attr, 0);
1005         if(ret==FALSE) {
1006                 /* FIXME: throw an exception? */
1007                 return(FALSE);
1008         }
1009         
1010         return(TRUE);
1011 }
1012
1013 MonoBoolean ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, 
1014                                                 HANDLE source_handle, HANDLE target_process_handle, HANDLE *target_handle, 
1015                                                 gint32 access, gint32 inherit, gint32 options)
1016 {
1017         /* This is only used on Windows */
1018         gboolean ret;
1019         
1020         ret=DuplicateHandle (source_process_handle, source_handle, target_process_handle, target_handle, access, inherit, options);
1021         if(ret==FALSE) {
1022                 /* FIXME: throw an exception? */
1023                 return(FALSE);
1024         }
1025         
1026         return(TRUE);
1027 }
1028
1029 gunichar2 
1030 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
1031 {
1032 #if defined (TARGET_WIN32)
1033         return (gunichar2) ':'; /* colon */
1034 #else
1035         return (gunichar2) '/'; /* forward slash */
1036 #endif
1037 }
1038
1039 gunichar2 
1040 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
1041 {
1042 #if defined (TARGET_WIN32)
1043         return (gunichar2) '\\';        /* backslash */
1044 #else
1045         return (gunichar2) '/'; /* forward slash */
1046 #endif
1047 }
1048
1049 gunichar2 
1050 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
1051 {
1052 #if defined (TARGET_WIN32)
1053         return (gunichar2) '/'; /* forward slash */
1054 #else
1055         if (IS_PORTABILITY_SET)
1056                 return (gunichar2) '\\';        /* backslash */
1057         else
1058                 return (gunichar2) '/'; /* forward slash */
1059 #endif
1060 }
1061
1062 gunichar2 
1063 ves_icall_System_IO_MonoIO_get_PathSeparator ()
1064 {
1065 #if defined (TARGET_WIN32)
1066         return (gunichar2) ';'; /* semicolon */
1067 #else
1068         return (gunichar2) ':'; /* colon */
1069 #endif
1070 }
1071
1072 static const gunichar2
1073 invalid_path_chars [] = {
1074 #if defined (TARGET_WIN32)
1075         0x0022,                         /* double quote, which seems allowed in MS.NET but should be rejected */
1076         0x003c,                         /* less than */
1077         0x003e,                         /* greater than */
1078         0x007c,                         /* pipe */
1079         0x0008,
1080         0x0010,
1081         0x0011,
1082         0x0012,
1083         0x0014,
1084         0x0015,
1085         0x0016,
1086         0x0017,
1087         0x0018,
1088         0x0019,
1089 #endif
1090         0x0000                          /* null */
1091 };
1092
1093 MonoArray *
1094 ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
1095 {
1096         MonoArray *chars;
1097         MonoDomain *domain;
1098         int i, n;
1099
1100         domain = mono_domain_get ();
1101         n = sizeof (invalid_path_chars) / sizeof (gunichar2);
1102         chars = mono_array_new (domain, mono_defaults.char_class, n);
1103
1104         for (i = 0; i < n; ++ i)
1105                 mono_array_set (chars, gunichar2, i, invalid_path_chars [i]);
1106         
1107         return chars;
1108 }
1109
1110 gint32
1111 ves_icall_System_IO_MonoIO_GetTempPath (MonoString **mono_name)
1112 {
1113         gunichar2 *name;
1114         int ret;
1115
1116         name=g_new0 (gunichar2, 256);
1117         
1118         ret=GetTempPath (256, name);
1119         if(ret>255) {
1120                 /* Buffer was too short. Try again... */
1121                 g_free (name);
1122                 name=g_new0 (gunichar2, ret+2); /* include the terminator */
1123                 ret=GetTempPath (ret, name);
1124         }
1125         
1126         if(ret>0) {
1127 #ifdef DEBUG
1128                 g_message ("%s: Temp path is [%s] (len %d)", __func__, name, ret);
1129 #endif
1130
1131                 mono_gc_wbarrier_generic_store ((gpointer) mono_name,
1132                                 (MonoObject*) mono_string_new_utf16 (mono_domain_get (), name, ret));
1133         }
1134
1135         g_free (name);
1136         
1137         return(ret);
1138 }
1139
1140 void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
1141                                       gint64 length, gint32 *error)
1142 {
1143         gboolean ret;
1144         
1145         *error=ERROR_SUCCESS;
1146         
1147         ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
1148                       length & 0xFFFFFFFF, length >> 32);
1149         if (ret == FALSE) {
1150                 *error = GetLastError ();
1151         }
1152 }
1153
1154 void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
1155                                         gint64 length, gint32 *error)
1156 {
1157         gboolean ret;
1158         
1159         *error=ERROR_SUCCESS;
1160         
1161         ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
1162                         length & 0xFFFFFFFF, length >> 32);
1163         if (ret == FALSE) {
1164                 *error = GetLastError ();
1165         }
1166 }
1167
1168 //Support for io-layer free mmap'd files.
1169
1170 #if defined (TARGET_IOS) || defined (TARGET_ANDROID)
1171
1172 gint64
1173 mono_filesize_from_path (MonoString *string)
1174 {
1175         struct stat buf;
1176         gint64 res;
1177         char *path = mono_string_to_utf8 (string);
1178         
1179         if (stat (path, &buf) == -1)
1180                 res = -1;
1181         else
1182                 res = (gint64)buf.st_size;
1183
1184         g_free (path);
1185         return res;
1186 }
1187
1188 gint64
1189 mono_filesize_from_fd (int fd)
1190 {
1191         struct stat buf;
1192
1193         if (fstat (fd, &buf) == -1)
1194                 return (gint64)-1;
1195
1196         return (gint64)buf.st_size;
1197 }
1198
1199 #endif