Merge pull request #2819 from BrzVlad/fix-major-log
[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_PREPARE_BLOCKING;
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_FINISH_BLOCKING;
283         return(ret);
284 }
285
286 MonoBoolean
287 ves_icall_System_IO_MonoIO_RemoveDirectory (MonoString *path, gint32 *error)
288 {
289         gboolean ret;
290         MONO_PREPARE_BLOCKING;
291         
292         *error=ERROR_SUCCESS;
293         
294         ret=RemoveDirectory (mono_string_chars (path));
295         if(ret==FALSE) {
296                 *error=GetLastError ();
297         }
298
299         MONO_FINISH_BLOCKING;
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 *error)
398 {
399         MonoDomain *domain = mono_domain_get ();
400         MonoArray *result;
401         int i;
402         GPtrArray *names;
403         
404         *error = ERROR_SUCCESS;
405
406         MONO_PREPARE_BLOCKING;
407         names = get_filesystem_entries (mono_string_chars (path), mono_string_chars (path_with_pattern), attrs, mask, error);
408         MONO_FINISH_BLOCKING;
409
410         if (!names) {
411                 // If there's no array and no error, then return an empty array.
412                 if (*error == ERROR_SUCCESS)
413                         return mono_array_new (domain, mono_defaults.string_class, 0);
414                 return NULL;
415         }
416
417         result = mono_array_new (domain, mono_defaults.string_class, names->len);
418         for (i = 0; i < names->len; i++) {
419                 mono_array_setref (result, i, mono_string_new (domain, (const char *)g_ptr_array_index (names, i)));
420                 g_free (g_ptr_array_index (names, i));
421         }
422         g_ptr_array_free (names, TRUE);
423         return result;
424 }
425
426 typedef struct {
427         MonoDomain *domain;
428         gchar *utf8_path;
429         HANDLE find_handle;
430 } IncrementalFind;
431         
432 static gboolean
433 incremental_find_check_match (IncrementalFind *handle, WIN32_FIND_DATA *data, MonoString **result)
434 {
435         gchar *utf8_result;
436         gchar *full_name;
437         
438         if ((data->cFileName[0] == '.' && data->cFileName[1] == 0) || (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0))
439                 return FALSE;
440
441         utf8_result = g_utf16_to_utf8 (data->cFileName, -1, NULL, NULL, NULL);
442         if (utf8_result == NULL) 
443                 return FALSE;
444         
445         full_name = g_build_filename (handle->utf8_path, utf8_result, NULL);
446         g_free (utf8_result);
447         *result = mono_string_new (mono_domain_get (), full_name);
448         g_free (full_name);
449         
450         return TRUE;
451 }
452
453 /* FIXME make gc suspendable */
454 MonoString *
455 ves_icall_System_IO_MonoIO_FindFirst (MonoString *path,
456                                       MonoString *path_with_pattern,
457                                       gint32 *result_attr, gint32 *error,
458                                       gpointer *handle)
459 {
460         WIN32_FIND_DATA data;
461         HANDLE find_handle;
462         IncrementalFind *ifh;
463         MonoString *result;
464         
465         *error = ERROR_SUCCESS;
466         
467         find_handle = FindFirstFile (mono_string_chars (path_with_pattern), &data);
468         
469         if (find_handle == INVALID_HANDLE_VALUE) {
470                 gint32 find_error = GetLastError ();
471                 *handle = NULL;
472                 
473                 if (find_error == ERROR_FILE_NOT_FOUND) 
474                         return NULL;
475                 
476                 *error = find_error;
477                 return NULL;
478         }
479
480         ifh = g_new (IncrementalFind, 1);
481         ifh->find_handle = find_handle;
482         ifh->utf8_path = mono_string_to_utf8 (path);
483         ifh->domain = mono_domain_get ();
484         *handle = ifh;
485
486         while (incremental_find_check_match (ifh, &data, &result) == 0){
487                 if (FindNextFile (find_handle, &data) == FALSE){
488                         int e = GetLastError ();
489                         if (e != ERROR_NO_MORE_FILES)
490                                 *error = e;
491                         return NULL;
492                 }
493         }
494         *result_attr = data.dwFileAttributes;
495         
496         return result;
497 }
498
499 /* FIXME make gc suspendable */
500 MonoString *
501 ves_icall_System_IO_MonoIO_FindNext (gpointer handle, gint32 *result_attr, gint32 *error)
502 {
503         IncrementalFind *ifh = (IncrementalFind *)handle;
504         WIN32_FIND_DATA data;
505         MonoString *result;
506
507         *error = ERROR_SUCCESS;
508         do {
509                 if (FindNextFile (ifh->find_handle, &data) == FALSE){
510                         int e = GetLastError ();
511                         if (e != ERROR_NO_MORE_FILES)
512                                 *error = e;
513                         return NULL;
514                 }
515         } while (incremental_find_check_match (ifh, &data, &result) == 0);
516
517         *result_attr = data.dwFileAttributes;
518         return result;
519 }
520
521 int
522 ves_icall_System_IO_MonoIO_FindClose (gpointer handle)
523 {
524         IncrementalFind *ifh = (IncrementalFind *)handle;
525         gint32 error;
526
527         MONO_PREPARE_BLOCKING;
528         if (FindClose (ifh->find_handle) == FALSE){
529                 error = GetLastError ();
530         } else
531                 error = ERROR_SUCCESS;
532         g_free (ifh->utf8_path);
533         g_free (ifh);
534         MONO_FINISH_BLOCKING;
535
536         return error;
537 }
538
539 MonoString *
540 ves_icall_System_IO_MonoIO_GetCurrentDirectory (gint32 *io_error)
541 {
542         MonoError error;
543         MonoString *result;
544         gunichar2 *buf;
545         int len, res_len;
546
547         len = MAX_PATH + 1; /*FIXME this is too smal under most unix systems.*/
548         buf = g_new (gunichar2, len);
549         
550         mono_error_init (&error);
551         *io_error=ERROR_SUCCESS;
552         result = NULL;
553
554         res_len = GetCurrentDirectory (len, buf);
555         if (res_len > len) { /*buf is too small.*/
556                 int old_res_len = res_len;
557                 g_free (buf);
558                 buf = g_new (gunichar2, res_len);
559                 res_len = GetCurrentDirectory (res_len, buf) == old_res_len;
560         }
561         
562         if (res_len) {
563                 len = 0;
564                 while (buf [len])
565                         ++ len;
566
567                 result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
568         } else {
569                 *io_error=GetLastError ();
570         }
571
572         g_free (buf);
573         mono_error_set_pending_exception (&error);
574         return result;
575 }
576
577 MonoBoolean
578 ves_icall_System_IO_MonoIO_SetCurrentDirectory (MonoString *path,
579                                                 gint32 *error)
580 {
581         gboolean ret;
582         
583         *error=ERROR_SUCCESS;
584         
585         ret=SetCurrentDirectory (mono_string_chars (path));
586         if(ret==FALSE) {
587                 *error=GetLastError ();
588         }
589         
590         return(ret);
591 }
592
593 MonoBoolean
594 ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest,
595                                      gint32 *error)
596 {
597         gboolean ret;
598         MONO_PREPARE_BLOCKING;
599         
600         *error=ERROR_SUCCESS;
601
602         ret=MoveFile (mono_string_chars (path), mono_string_chars (dest));
603         if(ret==FALSE) {
604                 *error=GetLastError ();
605         }
606
607         MONO_FINISH_BLOCKING;
608         return(ret);
609 }
610
611 MonoBoolean
612 ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *destinationFileName,
613                                         MonoString *destinationBackupFileName, MonoBoolean ignoreMetadataErrors,
614                                         gint32 *error)
615 {
616         gboolean ret;
617         gunichar2 *utf16_sourceFileName = NULL, *utf16_destinationFileName = NULL, *utf16_destinationBackupFileName = NULL;
618         guint32 replaceFlags = REPLACEFILE_WRITE_THROUGH;
619         MONO_PREPARE_BLOCKING;
620
621         if (sourceFileName)
622                 utf16_sourceFileName = mono_string_chars (sourceFileName);
623         if (destinationFileName)
624                 utf16_destinationFileName = mono_string_chars (destinationFileName);
625         if (destinationBackupFileName)
626                 utf16_destinationBackupFileName = mono_string_chars (destinationBackupFileName);
627
628         *error = ERROR_SUCCESS;
629         if (ignoreMetadataErrors)
630                 replaceFlags |= REPLACEFILE_IGNORE_MERGE_ERRORS;
631
632         /* FIXME: source and destination file names must not be NULL, but apparently they might be! */
633         ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
634                          replaceFlags, NULL, NULL);
635         if (ret == FALSE)
636                 *error = GetLastError ();
637
638         MONO_FINISH_BLOCKING;
639         return ret;
640 }
641
642 MonoBoolean
643 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
644                                      MonoBoolean overwrite, gint32 *error)
645 {
646         gboolean ret;
647         MONO_PREPARE_BLOCKING;
648         
649         *error=ERROR_SUCCESS;
650         
651         ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
652         if(ret==FALSE) {
653                 *error=GetLastError ();
654         }
655         
656         MONO_FINISH_BLOCKING;
657         return(ret);
658 }
659
660 MonoBoolean
661 ves_icall_System_IO_MonoIO_DeleteFile (MonoString *path, gint32 *error)
662 {
663         gboolean ret;
664         MONO_PREPARE_BLOCKING;
665         
666         *error=ERROR_SUCCESS;
667         
668         ret=DeleteFile (mono_string_chars (path));
669         if(ret==FALSE) {
670                 *error=GetLastError ();
671         }
672         
673         MONO_FINISH_BLOCKING;
674         return(ret);
675 }
676
677 gint32 
678 ves_icall_System_IO_MonoIO_GetFileAttributes (MonoString *path, gint32 *error)
679 {
680         gint32 ret;
681         MONO_PREPARE_BLOCKING;
682
683         *error=ERROR_SUCCESS;
684         
685         ret=get_file_attributes (mono_string_chars (path));
686
687         /* 
688          * The definition of INVALID_FILE_ATTRIBUTES in the cygwin win32
689          * headers is wrong, hence this temporary workaround.
690          * See
691          * http://cygwin.com/ml/cygwin/2003-09/msg01771.html
692          */
693         if (ret==-1) {
694           /* if(ret==INVALID_FILE_ATTRIBUTES) { */
695                 *error=GetLastError ();
696         }
697         
698         MONO_FINISH_BLOCKING;
699         return(ret);
700 }
701
702 MonoBoolean
703 ves_icall_System_IO_MonoIO_SetFileAttributes (MonoString *path, gint32 attrs,
704                                               gint32 *error)
705 {
706         gboolean ret;
707         MONO_PREPARE_BLOCKING;
708         
709         *error=ERROR_SUCCESS;
710         
711         ret=SetFileAttributes (mono_string_chars (path),
712                 convert_attrs ((MonoFileAttributes)attrs));
713         if(ret==FALSE) {
714                 *error=GetLastError ();
715         }
716
717         MONO_FINISH_BLOCKING;
718         return(ret);
719 }
720
721 gint32
722 ves_icall_System_IO_MonoIO_GetFileType (HANDLE handle, gint32 *error)
723 {
724         gboolean ret;
725         MONO_PREPARE_BLOCKING;
726
727         *error=ERROR_SUCCESS;
728         
729         ret=GetFileType (handle);
730         if(ret==FILE_TYPE_UNKNOWN) {
731                 /* Not necessarily an error, but the caller will have
732                  * to decide based on the error value.
733                  */
734                 *error=GetLastError ();
735         }
736         
737         MONO_FINISH_BLOCKING;
738         return(ret);
739 }
740
741 MonoBoolean
742 ves_icall_System_IO_MonoIO_GetFileStat (MonoString *path, MonoIOStat *stat,
743                                         gint32 *error)
744 {
745         gboolean result;
746         WIN32_FILE_ATTRIBUTE_DATA data;
747         MONO_PREPARE_BLOCKING;
748
749         *error=ERROR_SUCCESS;
750         
751         result = get_file_attributes_ex (mono_string_chars (path), &data);
752
753         if (result) {
754                 convert_win32_file_attribute_data (&data, stat);
755         } else {
756                 *error=GetLastError ();
757                 memset (stat, 0, sizeof (MonoIOStat));
758         }
759
760         MONO_FINISH_BLOCKING;
761         return result;
762 }
763
764 HANDLE 
765 ves_icall_System_IO_MonoIO_Open (MonoString *filename, gint32 mode,
766                                  gint32 access_mode, gint32 share, gint32 options,
767                                  gint32 *error)
768 {
769         HANDLE ret;
770         int attributes, attrs;
771         gunichar2 *chars;
772         MONO_PREPARE_BLOCKING;
773
774         chars = mono_string_chars (filename);   
775         *error=ERROR_SUCCESS;
776
777         if (options != 0){
778                 if (options & FileOptions_Encrypted)
779                         attributes = FILE_ATTRIBUTE_ENCRYPTED;
780                 else
781                         attributes = FILE_ATTRIBUTE_NORMAL;
782                 if (options & FileOptions_DeleteOnClose)
783                         attributes |= FILE_FLAG_DELETE_ON_CLOSE;
784                 if (options & FileOptions_SequentialScan)
785                         attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
786                 if (options & FileOptions_RandomAccess)
787                         attributes |= FILE_FLAG_RANDOM_ACCESS;
788
789                 if (options & FileOptions_Temporary)
790                         attributes |= FILE_ATTRIBUTE_TEMPORARY;
791                 
792                 /* Not sure if we should set FILE_FLAG_OVERLAPPED, how does this mix with the "Async" bool here? */
793                 if (options & FileOptions_Asynchronous)
794                         attributes |= FILE_FLAG_OVERLAPPED;
795                 
796                 if (options & FileOptions_WriteThrough)
797                         attributes |= FILE_FLAG_WRITE_THROUGH;
798         } else
799                 attributes = FILE_ATTRIBUTE_NORMAL;
800
801         /* If we're opening a directory we need to set the extra flag
802          */
803         attrs = get_file_attributes (chars);
804         if (attrs != INVALID_FILE_ATTRIBUTES) {
805                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
806                         attributes |= FILE_FLAG_BACKUP_SEMANTICS;
807                 }
808         }
809         
810         ret=CreateFile (chars, convert_access ((MonoFileAccess)access_mode),
811                         convert_share ((MonoFileShare)share), NULL, convert_mode ((MonoFileMode)mode),
812                         attributes, NULL);
813         if(ret==INVALID_HANDLE_VALUE) {
814                 *error=GetLastError ();
815         } 
816         
817         MONO_FINISH_BLOCKING;
818         return(ret);
819 }
820
821 MonoBoolean
822 ves_icall_System_IO_MonoIO_Close (HANDLE handle, gint32 *error)
823 {
824         gboolean ret;
825         MONO_PREPARE_BLOCKING;
826
827         *error=ERROR_SUCCESS;
828         
829         ret=CloseHandle (handle);
830         if(ret==FALSE) {
831                 *error=GetLastError ();
832         }
833         
834         MONO_FINISH_BLOCKING;
835         return(ret);
836 }
837
838 gint32 
839 ves_icall_System_IO_MonoIO_Read (HANDLE handle, MonoArray *dest,
840                                  gint32 dest_offset, gint32 count,
841                                  gint32 *error)
842 {
843         guchar *buffer;
844         gboolean result;
845         guint32 n;
846
847         *error=ERROR_SUCCESS;
848
849         MONO_CHECK_ARG_NULL (dest, 0);
850
851         if (dest_offset > mono_array_length (dest) - count) {
852                 mono_set_pending_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
853                 return 0;
854         }
855
856         buffer = mono_array_addr (dest, guchar, dest_offset);
857
858         MONO_PREPARE_BLOCKING;
859         result = ReadFile (handle, buffer, count, &n, NULL);
860         MONO_FINISH_BLOCKING;
861
862         if (!result) {
863                 *error=GetLastError ();
864                 return -1;
865         }
866
867         return (gint32)n;
868 }
869
870 gint32 
871 ves_icall_System_IO_MonoIO_Write (HANDLE handle, MonoArray *src,
872                                   gint32 src_offset, gint32 count,
873                                   gint32 *error)
874 {
875         guchar *buffer;
876         gboolean result;
877         guint32 n;
878
879         *error=ERROR_SUCCESS;
880
881         MONO_CHECK_ARG_NULL (src, 0);
882         
883         if (src_offset > mono_array_length (src) - count) {
884                 mono_set_pending_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
885                 return 0;
886         }
887         
888         buffer = mono_array_addr (src, guchar, src_offset);
889         MONO_PREPARE_BLOCKING;
890         result = WriteFile (handle, buffer, count, &n, NULL);
891         MONO_FINISH_BLOCKING;
892
893         if (!result) {
894                 *error=GetLastError ();
895                 return -1;
896         }
897
898         return (gint32)n;
899 }
900
901 gint64 
902 ves_icall_System_IO_MonoIO_Seek (HANDLE handle, gint64 offset, gint32 origin,
903                                  gint32 *error)
904 {
905         gint32 offset_hi;
906         MONO_PREPARE_BLOCKING;
907
908         *error=ERROR_SUCCESS;
909         
910         offset_hi = offset >> 32;
911         offset = SetFilePointer (handle, (gint32) (offset & 0xFFFFFFFF), &offset_hi,
912                                  convert_seekorigin ((MonoSeekOrigin)origin));
913
914         if(offset==INVALID_SET_FILE_POINTER) {
915                 *error=GetLastError ();
916         }
917
918         MONO_FINISH_BLOCKING;
919         return offset | ((gint64)offset_hi << 32);
920 }
921
922 MonoBoolean
923 ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
924 {
925         gboolean ret;
926         MONO_PREPARE_BLOCKING;
927
928         *error=ERROR_SUCCESS;
929         
930         ret=FlushFileBuffers (handle);
931         if(ret==FALSE) {
932                 *error=GetLastError ();
933         }
934         
935         MONO_FINISH_BLOCKING;
936         return(ret);
937 }
938
939 gint64 
940 ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
941 {
942         gint64 length;
943         guint32 length_hi;
944         MONO_PREPARE_BLOCKING;
945
946         *error=ERROR_SUCCESS;
947         
948         length = GetFileSize (handle, &length_hi);
949         if(length==INVALID_FILE_SIZE) {
950                 *error=GetLastError ();
951         }
952         
953         MONO_FINISH_BLOCKING;
954         return length | ((gint64)length_hi << 32);
955 }
956
957 /* FIXME make gc suspendable */
958 MonoBoolean
959 ves_icall_System_IO_MonoIO_SetLength (HANDLE handle, gint64 length,
960                                       gint32 *error)
961 {
962         gint64 offset, offset_set;
963         gint32 offset_hi;
964         gint32 length_hi;
965         gboolean result;
966
967         *error=ERROR_SUCCESS;
968         
969         /* save file pointer */
970
971         offset_hi = 0;
972         offset = SetFilePointer (handle, 0, &offset_hi, FILE_CURRENT);
973         if(offset==INVALID_SET_FILE_POINTER) {
974                 *error=GetLastError ();
975                 return(FALSE);
976         }
977
978         /* extend or truncate */
979
980         length_hi = length >> 32;
981         offset_set=SetFilePointer (handle, length & 0xFFFFFFFF, &length_hi,
982                                    FILE_BEGIN);
983         if(offset_set==INVALID_SET_FILE_POINTER) {
984                 *error=GetLastError ();
985                 return(FALSE);
986         }
987
988         result = SetEndOfFile (handle);
989         if(result==FALSE) {
990                 *error=GetLastError ();
991                 return(FALSE);
992         }
993
994         /* restore file pointer */
995
996         offset_set=SetFilePointer (handle, offset & 0xFFFFFFFF, &offset_hi,
997                                    FILE_BEGIN);
998         if(offset_set==INVALID_SET_FILE_POINTER) {
999                 *error=GetLastError ();
1000                 return(FALSE);
1001         }
1002
1003         return result;
1004 }
1005
1006 MonoBoolean
1007 ves_icall_System_IO_MonoIO_SetFileTime (HANDLE handle, gint64 creation_time,
1008                                         gint64 last_access_time,
1009                                         gint64 last_write_time, gint32 *error)
1010 {
1011         gboolean ret;
1012         const FILETIME *creation_filetime;
1013         const FILETIME *last_access_filetime;
1014         const FILETIME *last_write_filetime;
1015         MONO_PREPARE_BLOCKING;
1016
1017         *error=ERROR_SUCCESS;
1018         
1019         if (creation_time < 0)
1020                 creation_filetime = NULL;
1021         else
1022                 creation_filetime = (FILETIME *)&creation_time;
1023
1024         if (last_access_time < 0)
1025                 last_access_filetime = NULL;
1026         else
1027                 last_access_filetime = (FILETIME *)&last_access_time;
1028
1029         if (last_write_time < 0)
1030                 last_write_filetime = NULL;
1031         else
1032                 last_write_filetime = (FILETIME *)&last_write_time;
1033
1034         ret=SetFileTime (handle, creation_filetime, last_access_filetime, last_write_filetime);
1035         if(ret==FALSE) {
1036                 *error=GetLastError ();
1037         }
1038
1039         MONO_FINISH_BLOCKING;
1040         return(ret);
1041 }
1042
1043 HANDLE 
1044 ves_icall_System_IO_MonoIO_get_ConsoleOutput ()
1045 {
1046         return GetStdHandle (STD_OUTPUT_HANDLE);
1047 }
1048
1049 HANDLE 
1050 ves_icall_System_IO_MonoIO_get_ConsoleInput ()
1051 {
1052         return GetStdHandle (STD_INPUT_HANDLE);
1053 }
1054
1055 HANDLE 
1056 ves_icall_System_IO_MonoIO_get_ConsoleError ()
1057 {
1058         return GetStdHandle (STD_ERROR_HANDLE);
1059 }
1060
1061 MonoBoolean
1062 ves_icall_System_IO_MonoIO_CreatePipe (HANDLE *read_handle, HANDLE *write_handle, gint32 *error)
1063 {
1064         SECURITY_ATTRIBUTES attr;
1065         gboolean ret;
1066         
1067         attr.nLength=sizeof(SECURITY_ATTRIBUTES);
1068         attr.bInheritHandle=TRUE;
1069         attr.lpSecurityDescriptor=NULL;
1070
1071         MONO_PREPARE_BLOCKING;
1072         ret=CreatePipe (read_handle, write_handle, &attr, 0);
1073         MONO_FINISH_BLOCKING;
1074
1075         if(ret==FALSE) {
1076                 *error = GetLastError ();
1077                 /* FIXME: throw an exception? */
1078                 return(FALSE);
1079         }
1080         
1081         return(TRUE);
1082 }
1083
1084 MonoBoolean
1085 ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, HANDLE source_handle,
1086                 HANDLE target_process_handle, HANDLE *target_handle, gint32 access, gint32 inherit, gint32 options, gint32 *error)
1087 {
1088         /* This is only used on Windows */
1089         gboolean ret;
1090         
1091         MONO_PREPARE_BLOCKING;
1092         ret=DuplicateHandle (source_process_handle, source_handle, target_process_handle, target_handle, access, inherit, options);
1093         MONO_FINISH_BLOCKING;
1094
1095         if(ret==FALSE) {
1096                 *error = GetLastError ();
1097                 /* FIXME: throw an exception? */
1098                 return(FALSE);
1099         }
1100         
1101         return(TRUE);
1102 }
1103
1104 gunichar2 
1105 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
1106 {
1107 #if defined (TARGET_WIN32)
1108         return (gunichar2) ':'; /* colon */
1109 #else
1110         return (gunichar2) '/'; /* forward slash */
1111 #endif
1112 }
1113
1114 gunichar2 
1115 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
1116 {
1117 #if defined (TARGET_WIN32)
1118         return (gunichar2) '\\';        /* backslash */
1119 #else
1120         return (gunichar2) '/'; /* forward slash */
1121 #endif
1122 }
1123
1124 gunichar2 
1125 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
1126 {
1127 #if defined (TARGET_WIN32)
1128         return (gunichar2) '/'; /* forward slash */
1129 #else
1130         if (IS_PORTABILITY_SET)
1131                 return (gunichar2) '\\';        /* backslash */
1132         else
1133                 return (gunichar2) '/'; /* forward slash */
1134 #endif
1135 }
1136
1137 gunichar2 
1138 ves_icall_System_IO_MonoIO_get_PathSeparator ()
1139 {
1140 #if defined (TARGET_WIN32)
1141         return (gunichar2) ';'; /* semicolon */
1142 #else
1143         return (gunichar2) ':'; /* colon */
1144 #endif
1145 }
1146
1147 static const gunichar2
1148 invalid_path_chars [] = {
1149 #if defined (TARGET_WIN32)
1150         0x0022,                         /* double quote, which seems allowed in MS.NET but should be rejected */
1151         0x003c,                         /* less than */
1152         0x003e,                         /* greater than */
1153         0x007c,                         /* pipe */
1154         0x0008,
1155         0x0010,
1156         0x0011,
1157         0x0012,
1158         0x0014,
1159         0x0015,
1160         0x0016,
1161         0x0017,
1162         0x0018,
1163         0x0019,
1164 #endif
1165         0x0000                          /* null */
1166 };
1167
1168 MonoArray *
1169 ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
1170 {
1171         MonoArray *chars;
1172         MonoDomain *domain;
1173         int i, n;
1174
1175         domain = mono_domain_get ();
1176         n = sizeof (invalid_path_chars) / sizeof (gunichar2);
1177         chars = mono_array_new (domain, mono_defaults.char_class, n);
1178
1179         for (i = 0; i < n; ++ i)
1180                 mono_array_set (chars, gunichar2, i, invalid_path_chars [i]);
1181         
1182         return chars;
1183 }
1184
1185 void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
1186                                       gint64 length, gint32 *error)
1187 {
1188         gboolean ret;
1189         MONO_PREPARE_BLOCKING;
1190         
1191         *error=ERROR_SUCCESS;
1192         
1193         ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
1194                       length & 0xFFFFFFFF, length >> 32);
1195         if (ret == FALSE) {
1196                 *error = GetLastError ();
1197         }
1198
1199         MONO_FINISH_BLOCKING;
1200 }
1201
1202 void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
1203                                         gint64 length, gint32 *error)
1204 {
1205         gboolean ret;
1206         MONO_PREPARE_BLOCKING;
1207         
1208         *error=ERROR_SUCCESS;
1209         
1210         ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
1211                         length & 0xFFFFFFFF, length >> 32);
1212         if (ret == FALSE) {
1213                 *error = GetLastError ();
1214         }
1215
1216         MONO_FINISH_BLOCKING;
1217 }
1218
1219 //Support for io-layer free mmap'd files.
1220
1221 #if defined (TARGET_IOS) || defined (TARGET_ANDROID)
1222
1223 gint64
1224 mono_filesize_from_path (MonoString *string)
1225 {
1226         struct stat buf;
1227         gint64 res;
1228         char *path = mono_string_to_utf8 (string);
1229
1230         MONO_PREPARE_BLOCKING;
1231         if (stat (path, &buf) == -1)
1232                 res = -1;
1233         else
1234                 res = (gint64)buf.st_size;
1235
1236         g_free (path);
1237
1238         MONO_FINISH_BLOCKING;
1239         return res;
1240 }
1241
1242 gint64
1243 mono_filesize_from_fd (int fd)
1244 {
1245         struct stat buf;
1246         int res;
1247
1248         MONO_PREPARE_BLOCKING;
1249         res = fstat (fd, &buf);
1250         MONO_FINISH_BLOCKING;
1251         
1252         if (res == -1)
1253                 return (gint64)-1;
1254
1255         return (gint64)buf.st_size;
1256 }
1257
1258 #endif
1259
1260 void _wapi_handle_dump (void);
1261
1262 void ves_icall_System_IO_MonoIO_DumpHandles (void)
1263 {
1264 #ifndef HOST_WIN32
1265         _wapi_handle_dump ();
1266 #endif
1267 }