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