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