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