Merge pull request #1536 from esdrubal/noreuse
[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         /* FIXME: source and destination file names must not be NULL, but apparently they might be! */
611         ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
612                          replaceFlags, NULL, NULL);
613         if (ret == FALSE)
614                 *error = GetLastError ();
615
616         return ret;
617 }
618
619 MonoBoolean
620 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
621                                      MonoBoolean overwrite, gint32 *error)
622 {
623         gboolean ret;
624         
625         MONO_ARCH_SAVE_REGS;
626
627         *error=ERROR_SUCCESS;
628         
629         ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
630         if(ret==FALSE) {
631                 *error=GetLastError ();
632         }
633         
634         return(ret);
635 }
636
637 MonoBoolean
638 ves_icall_System_IO_MonoIO_DeleteFile (MonoString *path, gint32 *error)
639 {
640         gboolean ret;
641         
642         MONO_ARCH_SAVE_REGS;
643
644         *error=ERROR_SUCCESS;
645         
646         ret=DeleteFile (mono_string_chars (path));
647         if(ret==FALSE) {
648                 *error=GetLastError ();
649         }
650         
651         return(ret);
652 }
653
654 gint32 
655 ves_icall_System_IO_MonoIO_GetFileAttributes (MonoString *path, gint32 *error)
656 {
657         gint32 ret;
658         
659         MONO_ARCH_SAVE_REGS;
660
661         *error=ERROR_SUCCESS;
662         
663         ret=get_file_attributes (mono_string_chars (path));
664
665         /* 
666          * The definition of INVALID_FILE_ATTRIBUTES in the cygwin win32
667          * headers is wrong, hence this temporary workaround.
668          * See
669          * http://cygwin.com/ml/cygwin/2003-09/msg01771.html
670          */
671         if (ret==-1) {
672           /* if(ret==INVALID_FILE_ATTRIBUTES) { */
673                 *error=GetLastError ();
674         }
675         
676         return(ret);
677 }
678
679 MonoBoolean
680 ves_icall_System_IO_MonoIO_SetFileAttributes (MonoString *path, gint32 attrs,
681                                               gint32 *error)
682 {
683         gboolean ret;
684         
685         MONO_ARCH_SAVE_REGS;
686
687         *error=ERROR_SUCCESS;
688         
689         ret=SetFileAttributes (mono_string_chars (path),
690                                convert_attrs (attrs));
691         if(ret==FALSE) {
692                 *error=GetLastError ();
693         }
694         
695         return(ret);
696 }
697
698 gint32
699 ves_icall_System_IO_MonoIO_GetFileType (HANDLE handle, gint32 *error)
700 {
701         gboolean ret;
702         
703         MONO_ARCH_SAVE_REGS;
704
705         *error=ERROR_SUCCESS;
706         
707         ret=GetFileType (handle);
708         if(ret==FILE_TYPE_UNKNOWN) {
709                 /* Not necessarily an error, but the caller will have
710                  * to decide based on the error value.
711                  */
712                 *error=GetLastError ();
713         }
714         
715         return(ret);
716 }
717
718 MonoBoolean
719 ves_icall_System_IO_MonoIO_GetFileStat (MonoString *path, MonoIOStat *stat,
720                                         gint32 *error)
721 {
722         gboolean result;
723         WIN32_FILE_ATTRIBUTE_DATA data;
724
725         MONO_ARCH_SAVE_REGS;
726
727         *error=ERROR_SUCCESS;
728         
729         result = get_file_attributes_ex (mono_string_chars (path), &data);
730
731         if (result) {
732                 convert_win32_file_attribute_data (&data, stat);
733         } else {
734                 *error=GetLastError ();
735                 memset (stat, 0, sizeof (MonoIOStat));
736         }
737
738         return result;
739 }
740
741 HANDLE 
742 ves_icall_System_IO_MonoIO_Open (MonoString *filename, gint32 mode,
743                                  gint32 access_mode, gint32 share, gint32 options,
744                                  gint32 *error)
745 {
746         HANDLE ret;
747         int attributes, attrs;
748         gunichar2 *chars = mono_string_chars (filename);
749         
750         MONO_ARCH_SAVE_REGS;
751
752         *error=ERROR_SUCCESS;
753
754         if (options != 0){
755                 if (options & FileOptions_Encrypted)
756                         attributes = FILE_ATTRIBUTE_ENCRYPTED;
757                 else
758                         attributes = FILE_ATTRIBUTE_NORMAL;
759                 if (options & FileOptions_DeleteOnClose)
760                         attributes |= FILE_FLAG_DELETE_ON_CLOSE;
761                 if (options & FileOptions_SequentialScan)
762                         attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
763                 if (options & FileOptions_RandomAccess)
764                         attributes |= FILE_FLAG_RANDOM_ACCESS;
765
766                 if (options & FileOptions_Temporary)
767                         attributes |= FILE_ATTRIBUTE_TEMPORARY;
768                 
769                 /* Not sure if we should set FILE_FLAG_OVERLAPPED, how does this mix with the "Async" bool here? */
770                 if (options & FileOptions_Asynchronous)
771                         attributes |= FILE_FLAG_OVERLAPPED;
772                 
773                 if (options & FileOptions_WriteThrough)
774                         attributes |= FILE_FLAG_WRITE_THROUGH;
775         } else
776                 attributes = FILE_ATTRIBUTE_NORMAL;
777
778         /* If we're opening a directory we need to set the extra flag
779          */
780         attrs = get_file_attributes (chars);
781         if (attrs != INVALID_FILE_ATTRIBUTES) {
782                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
783                         attributes |= FILE_FLAG_BACKUP_SEMANTICS;
784                 }
785         }
786         
787         ret=CreateFile (chars, convert_access (access_mode),
788                         convert_share (share), NULL, convert_mode (mode),
789                         attributes, NULL);
790         if(ret==INVALID_HANDLE_VALUE) {
791                 *error=GetLastError ();
792         } 
793         
794         return(ret);
795 }
796
797 MonoBoolean
798 ves_icall_System_IO_MonoIO_Close (HANDLE handle, gint32 *error)
799 {
800         gboolean ret;
801         
802         MONO_ARCH_SAVE_REGS;
803
804         *error=ERROR_SUCCESS;
805         
806         ret=CloseHandle (handle);
807         if(ret==FALSE) {
808                 *error=GetLastError ();
809         }
810         
811         return(ret);
812 }
813
814 gint32 
815 ves_icall_System_IO_MonoIO_Read (HANDLE handle, MonoArray *dest,
816                                  gint32 dest_offset, gint32 count,
817                                  gint32 *error)
818 {
819         guchar *buffer;
820         gboolean result;
821         guint32 n;
822
823         MONO_ARCH_SAVE_REGS;
824
825         *error=ERROR_SUCCESS;
826
827         MONO_CHECK_ARG_NULL (dest);
828
829         if (dest_offset > mono_array_length (dest) - count)
830                 mono_raise_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
831
832         buffer = mono_array_addr (dest, guchar, dest_offset);
833         result = ReadFile (handle, buffer, count, &n, NULL);
834
835         if (!result) {
836                 *error=GetLastError ();
837                 return -1;
838         }
839
840         return (gint32)n;
841 }
842
843 gint32 
844 ves_icall_System_IO_MonoIO_Write (HANDLE handle, MonoArray *src,
845                                   gint32 src_offset, gint32 count,
846                                   gint32 *error)
847 {
848         guchar *buffer;
849         gboolean result;
850         guint32 n;
851
852         MONO_ARCH_SAVE_REGS;
853
854         *error=ERROR_SUCCESS;
855
856         MONO_CHECK_ARG_NULL (src);
857         
858         if (src_offset > mono_array_length (src) - count)
859                 mono_raise_exception (mono_get_exception_argument ("array", "array too small. numBytes/offset wrong."));
860         
861         buffer = mono_array_addr (src, guchar, src_offset);
862         result = WriteFile (handle, buffer, count, &n, NULL);
863
864         if (!result) {
865                 *error=GetLastError ();
866                 return -1;
867         }
868
869         return (gint32)n;
870 }
871
872 gint64 
873 ves_icall_System_IO_MonoIO_Seek (HANDLE handle, gint64 offset, gint32 origin,
874                                  gint32 *error)
875 {
876         gint32 offset_hi;
877
878         MONO_ARCH_SAVE_REGS;
879
880         *error=ERROR_SUCCESS;
881         
882         offset_hi = offset >> 32;
883         offset = SetFilePointer (handle, (gint32) (offset & 0xFFFFFFFF), &offset_hi,
884                                  convert_seekorigin (origin));
885
886         if(offset==INVALID_SET_FILE_POINTER) {
887                 *error=GetLastError ();
888         }
889         
890         return offset | ((gint64)offset_hi << 32);
891 }
892
893 MonoBoolean
894 ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
895 {
896         gboolean ret;
897         
898         MONO_ARCH_SAVE_REGS;
899
900         *error=ERROR_SUCCESS;
901         
902         ret=FlushFileBuffers (handle);
903         if(ret==FALSE) {
904                 *error=GetLastError ();
905         }
906         
907         return(ret);
908 }
909
910 gint64 
911 ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
912 {
913         gint64 length;
914         guint32 length_hi;
915
916         MONO_ARCH_SAVE_REGS;
917
918         *error=ERROR_SUCCESS;
919         
920         length = GetFileSize (handle, &length_hi);
921         if(length==INVALID_FILE_SIZE) {
922                 *error=GetLastError ();
923         }
924         
925         return length | ((gint64)length_hi << 32);
926 }
927
928 MonoBoolean
929 ves_icall_System_IO_MonoIO_SetLength (HANDLE handle, gint64 length,
930                                       gint32 *error)
931 {
932         gint64 offset, offset_set;
933         gint32 offset_hi;
934         gint32 length_hi;
935         gboolean result;
936
937         MONO_ARCH_SAVE_REGS;
938
939         *error=ERROR_SUCCESS;
940         
941         /* save file pointer */
942
943         offset_hi = 0;
944         offset = SetFilePointer (handle, 0, &offset_hi, FILE_CURRENT);
945         if(offset==INVALID_SET_FILE_POINTER) {
946                 *error=GetLastError ();
947                 return(FALSE);
948         }
949
950         /* extend or truncate */
951
952         length_hi = length >> 32;
953         offset_set=SetFilePointer (handle, length & 0xFFFFFFFF, &length_hi,
954                                    FILE_BEGIN);
955         if(offset_set==INVALID_SET_FILE_POINTER) {
956                 *error=GetLastError ();
957                 return(FALSE);
958         }
959
960         result = SetEndOfFile (handle);
961         if(result==FALSE) {
962                 *error=GetLastError ();
963                 return(FALSE);
964         }
965
966         /* restore file pointer */
967
968         offset_set=SetFilePointer (handle, offset & 0xFFFFFFFF, &offset_hi,
969                                    FILE_BEGIN);
970         if(offset_set==INVALID_SET_FILE_POINTER) {
971                 *error=GetLastError ();
972                 return(FALSE);
973         }
974
975         return result;
976 }
977
978 MonoBoolean
979 ves_icall_System_IO_MonoIO_SetFileTime (HANDLE handle, gint64 creation_time,
980                                         gint64 last_access_time,
981                                         gint64 last_write_time, gint32 *error)
982 {
983         gboolean ret;
984         const FILETIME *creation_filetime;
985         const FILETIME *last_access_filetime;
986         const FILETIME *last_write_filetime;
987
988         MONO_ARCH_SAVE_REGS;
989
990         *error=ERROR_SUCCESS;
991         
992         if (creation_time < 0)
993                 creation_filetime = NULL;
994         else
995                 creation_filetime = (FILETIME *)&creation_time;
996
997         if (last_access_time < 0)
998                 last_access_filetime = NULL;
999         else
1000                 last_access_filetime = (FILETIME *)&last_access_time;
1001
1002         if (last_write_time < 0)
1003                 last_write_filetime = NULL;
1004         else
1005                 last_write_filetime = (FILETIME *)&last_write_time;
1006
1007         ret=SetFileTime (handle, creation_filetime, last_access_filetime, last_write_filetime);
1008         if(ret==FALSE) {
1009                 *error=GetLastError ();
1010         }
1011         
1012         return(ret);
1013 }
1014
1015 HANDLE 
1016 ves_icall_System_IO_MonoIO_get_ConsoleOutput ()
1017 {
1018         MONO_ARCH_SAVE_REGS;
1019
1020         return GetStdHandle (STD_OUTPUT_HANDLE);
1021 }
1022
1023 HANDLE 
1024 ves_icall_System_IO_MonoIO_get_ConsoleInput ()
1025 {
1026         MONO_ARCH_SAVE_REGS;
1027
1028         return GetStdHandle (STD_INPUT_HANDLE);
1029 }
1030
1031 HANDLE 
1032 ves_icall_System_IO_MonoIO_get_ConsoleError ()
1033 {
1034         MONO_ARCH_SAVE_REGS;
1035
1036         return GetStdHandle (STD_ERROR_HANDLE);
1037 }
1038
1039 MonoBoolean
1040 ves_icall_System_IO_MonoIO_CreatePipe (HANDLE *read_handle,
1041                                        HANDLE *write_handle)
1042 {
1043         SECURITY_ATTRIBUTES attr;
1044         gboolean ret;
1045         
1046         MONO_ARCH_SAVE_REGS;
1047
1048         attr.nLength=sizeof(SECURITY_ATTRIBUTES);
1049         attr.bInheritHandle=TRUE;
1050         attr.lpSecurityDescriptor=NULL;
1051         
1052         ret=CreatePipe (read_handle, write_handle, &attr, 0);
1053         if(ret==FALSE) {
1054                 /* FIXME: throw an exception? */
1055                 return(FALSE);
1056         }
1057         
1058         return(TRUE);
1059 }
1060
1061 MonoBoolean ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, 
1062                                                 HANDLE source_handle, HANDLE target_process_handle, HANDLE *target_handle, 
1063                                                 gint32 access, gint32 inherit, gint32 options)
1064 {
1065         /* This is only used on Windows */
1066         gboolean ret;
1067         
1068         MONO_ARCH_SAVE_REGS;
1069         
1070         ret=DuplicateHandle (source_process_handle, source_handle, target_process_handle, target_handle, access, inherit, options);
1071         if(ret==FALSE) {
1072                 /* FIXME: throw an exception? */
1073                 return(FALSE);
1074         }
1075         
1076         return(TRUE);
1077 }
1078
1079 gunichar2 
1080 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
1081 {
1082 #if defined (TARGET_WIN32)
1083         return (gunichar2) ':'; /* colon */
1084 #else
1085         return (gunichar2) '/'; /* forward slash */
1086 #endif
1087 }
1088
1089 gunichar2 
1090 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
1091 {
1092 #if defined (TARGET_WIN32)
1093         return (gunichar2) '\\';        /* backslash */
1094 #else
1095         return (gunichar2) '/'; /* forward slash */
1096 #endif
1097 }
1098
1099 gunichar2 
1100 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
1101 {
1102 #if defined (TARGET_WIN32)
1103         return (gunichar2) '/'; /* forward slash */
1104 #else
1105         if (IS_PORTABILITY_SET)
1106                 return (gunichar2) '\\';        /* backslash */
1107         else
1108                 return (gunichar2) '/'; /* forward slash */
1109 #endif
1110 }
1111
1112 gunichar2 
1113 ves_icall_System_IO_MonoIO_get_PathSeparator ()
1114 {
1115 #if defined (TARGET_WIN32)
1116         return (gunichar2) ';'; /* semicolon */
1117 #else
1118         return (gunichar2) ':'; /* colon */
1119 #endif
1120 }
1121
1122 static const gunichar2
1123 invalid_path_chars [] = {
1124 #if defined (TARGET_WIN32)
1125         0x0022,                         /* double quote, which seems allowed in MS.NET but should be rejected */
1126         0x003c,                         /* less than */
1127         0x003e,                         /* greater than */
1128         0x007c,                         /* pipe */
1129         0x0008,
1130         0x0010,
1131         0x0011,
1132         0x0012,
1133         0x0014,
1134         0x0015,
1135         0x0016,
1136         0x0017,
1137         0x0018,
1138         0x0019,
1139 #endif
1140         0x0000                          /* null */
1141 };
1142
1143 MonoArray *
1144 ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
1145 {
1146         MonoArray *chars;
1147         MonoDomain *domain;
1148         int i, n;
1149
1150         MONO_ARCH_SAVE_REGS;
1151
1152         domain = mono_domain_get ();
1153         n = sizeof (invalid_path_chars) / sizeof (gunichar2);
1154         chars = mono_array_new (domain, mono_defaults.char_class, n);
1155
1156         for (i = 0; i < n; ++ i)
1157                 mono_array_set (chars, gunichar2, i, invalid_path_chars [i]);
1158         
1159         return chars;
1160 }
1161
1162 gint32
1163 ves_icall_System_IO_MonoIO_GetTempPath (MonoString **mono_name)
1164 {
1165         gunichar2 *name;
1166         int ret;
1167
1168         name=g_new0 (gunichar2, 256);
1169         
1170         ret=GetTempPath (256, name);
1171         if(ret>255) {
1172                 /* Buffer was too short. Try again... */
1173                 g_free (name);
1174                 name=g_new0 (gunichar2, ret+2); /* include the terminator */
1175                 ret=GetTempPath (ret, name);
1176         }
1177         
1178         if(ret>0) {
1179 #ifdef DEBUG
1180                 g_message ("%s: Temp path is [%s] (len %d)", __func__, name, ret);
1181 #endif
1182
1183                 mono_gc_wbarrier_generic_store ((gpointer) mono_name,
1184                                 (MonoObject*) mono_string_new_utf16 (mono_domain_get (), name, ret));
1185         }
1186
1187         g_free (name);
1188         
1189         return(ret);
1190 }
1191
1192 void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
1193                                       gint64 length, gint32 *error)
1194 {
1195         gboolean ret;
1196         
1197         *error=ERROR_SUCCESS;
1198         
1199         ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
1200                       length & 0xFFFFFFFF, length >> 32);
1201         if (ret == FALSE) {
1202                 *error = GetLastError ();
1203         }
1204 }
1205
1206 void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
1207                                         gint64 length, gint32 *error)
1208 {
1209         gboolean ret;
1210         
1211         *error=ERROR_SUCCESS;
1212         
1213         ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
1214                         length & 0xFFFFFFFF, length >> 32);
1215         if (ret == FALSE) {
1216                 *error = GetLastError ();
1217         }
1218 }
1219
1220 //Support for io-layer free mmap'd files.
1221
1222 #if defined (TARGET_IOS) || defined (TARGET_ANDROID)
1223
1224 gint64
1225 mono_filesize_from_path (MonoString *string)
1226 {
1227         struct stat buf;
1228         gint64 res;
1229         char *path = mono_string_to_utf8 (string);
1230         
1231         if (stat (path, &buf) == -1)
1232                 res = -1;
1233         else
1234                 res = (gint64)buf.st_size;
1235
1236         g_free (path);
1237         return res;
1238 }
1239
1240 gint64
1241 mono_filesize_from_fd (int fd)
1242 {
1243         struct stat buf;
1244
1245         if (fstat (fd, &buf) == -1)
1246                 return (gint64)-1;
1247
1248         return (gint64)buf.st_size;
1249 }
1250
1251 #endif