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