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