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