[runtime,IO] Filesystem entries can only be sought for in directories, not files.
[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         gint32 attributes;
334         
335         MONO_ARCH_SAVE_REGS;
336
337         *error = ERROR_SUCCESS;
338
339         domain = mono_domain_get ();
340         mask = convert_attrs (mask);
341         attributes = get_file_attributes (mono_string_chars (path));
342         if (attributes != -1) {
343                 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
344                         *error = ERROR_INVALID_NAME;
345                         return (NULL);
346                 }
347         } else {
348                 *error = GetLastError ();
349                 return (NULL);
350         }
351         
352         find_handle = FindFirstFile (mono_string_chars (path_with_pattern), &data);
353         if (find_handle == INVALID_HANDLE_VALUE) {
354                 gint32 find_error = GetLastError ();
355                 
356                 if (find_error == ERROR_FILE_NOT_FOUND || find_error == ERROR_NO_MORE_FILES) {
357                         /* No files, so just return an empty array */
358                         result = mono_array_new (domain,
359                                                  mono_defaults.string_class,
360                                                  0);
361
362                         return(result);
363                 }
364                 
365                 *error = find_error;
366                 return(NULL);
367         }
368
369         utf8_path = get_search_dir (path_with_pattern);
370         names = g_ptr_array_new ();
371
372         do {
373                 if ((data.cFileName[0] == '.' && data.cFileName[1] == 0) ||
374                     (data.cFileName[0] == '.' && data.cFileName[1] == '.' && data.cFileName[2] == 0)) {
375                         continue;
376                 }
377                 
378                 if ((data.dwFileAttributes & mask) == attrs) {
379                         utf8_result = g_utf16_to_utf8 (data.cFileName, -1, NULL, NULL, NULL);
380                         if (utf8_result == NULL) {
381                                 continue;
382                         }
383                         
384                         full_name = g_build_filename (utf8_path, utf8_result, NULL);
385                         g_ptr_array_add (names, full_name);
386
387                         g_free (utf8_result);
388                 }
389         } while(FindNextFile (find_handle, &data));
390
391         if (FindClose (find_handle) == FALSE) {
392                 *error = GetLastError ();
393                 result = NULL;
394         } else {
395                 result = mono_array_new (domain, mono_defaults.string_class, names->len);
396                 for (i = 0; i < names->len; i++) {
397                         mono_array_setref (result, i, mono_string_new (domain, g_ptr_array_index (names, i)));
398                 }
399         }
400
401         for (i = 0; i < names->len; i++) {
402                 g_free (g_ptr_array_index (names, i));
403         }
404         g_ptr_array_free (names, TRUE);
405         g_free (utf8_path);
406         
407         return result;
408 }
409
410 typedef struct {
411         MonoDomain *domain;
412         gchar *utf8_path;
413         HANDLE find_handle;
414 } IncrementalFind;
415         
416 static gboolean
417 incremental_find_check_match (IncrementalFind *handle, WIN32_FIND_DATA *data, MonoString **result)
418 {
419         gchar *utf8_result;
420         gchar *full_name;
421         
422         if ((data->cFileName[0] == '.' && data->cFileName[1] == 0) || (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0))
423                 return FALSE;
424
425         utf8_result = g_utf16_to_utf8 (data->cFileName, -1, NULL, NULL, NULL);
426         if (utf8_result == NULL) 
427                 return FALSE;
428         
429         full_name = g_build_filename (handle->utf8_path, utf8_result, NULL);
430         g_free (utf8_result);
431         *result = mono_string_new (mono_domain_get (), full_name);
432         g_free (full_name);
433         
434         return TRUE;
435 }
436
437 MonoString *
438 ves_icall_System_IO_MonoIO_FindFirst (MonoString *path,
439                                       MonoString *path_with_pattern,
440                                       gint32 *result_attr, gint32 *error,
441                                       gpointer *handle)
442 {
443         WIN32_FIND_DATA data;
444         HANDLE find_handle;
445         IncrementalFind *ifh;
446         MonoString *result;
447         
448         *error = ERROR_SUCCESS;
449         
450         find_handle = FindFirstFile (mono_string_chars (path_with_pattern), &data);
451         
452         if (find_handle == INVALID_HANDLE_VALUE) {
453                 gint32 find_error = GetLastError ();
454                 *handle = NULL;
455                 
456                 if (find_error == ERROR_FILE_NOT_FOUND) 
457                         return NULL;
458                 
459                 *error = find_error;
460                 return NULL;
461         }
462
463         ifh = g_new (IncrementalFind, 1);
464         ifh->find_handle = find_handle;
465         ifh->utf8_path = mono_string_to_utf8 (path);
466         ifh->domain = mono_domain_get ();
467         *handle = ifh;
468
469         while (incremental_find_check_match (ifh, &data, &result) == 0){
470                 if (FindNextFile (find_handle, &data) == FALSE){
471                         int e = GetLastError ();
472                         if (e != ERROR_NO_MORE_FILES)
473                                 *error = e;
474                         return NULL;
475                 }
476         }
477         *result_attr = data.dwFileAttributes;
478         
479         return result;
480 }
481
482 MonoString *
483 ves_icall_System_IO_MonoIO_FindNext (gpointer handle, gint32 *result_attr, gint32 *error)
484 {
485         IncrementalFind *ifh = handle;
486         WIN32_FIND_DATA data;
487         MonoString *result;
488
489         error = ERROR_SUCCESS;
490         do {
491                 if (FindNextFile (ifh->find_handle, &data) == FALSE){
492                         int e = GetLastError ();
493                         if (e != ERROR_NO_MORE_FILES)
494                                 *error = e;
495                         return NULL;
496                 }
497         } while (incremental_find_check_match (ifh, &data, &result) == 0);
498
499         *result_attr = data.dwFileAttributes;
500         return result;
501 }
502
503 int
504 ves_icall_System_IO_MonoIO_FindClose (gpointer handle)
505 {
506         IncrementalFind *ifh = handle;
507         gint32 error;
508         
509         if (FindClose (ifh->find_handle) == FALSE){
510                 error = GetLastError ();
511         } else
512                 error = ERROR_SUCCESS;
513         g_free (ifh->utf8_path);
514         g_free (ifh);
515
516         return error;
517 }
518
519 MonoString *
520 ves_icall_System_IO_MonoIO_GetCurrentDirectory (gint32 *error)
521 {
522         MonoString *result;
523         gunichar2 *buf;
524         int len, res_len;
525
526         MONO_ARCH_SAVE_REGS;
527
528         len = MAX_PATH + 1; /*FIXME this is too smal under most unix systems.*/
529         buf = g_new (gunichar2, len);
530         
531         *error=ERROR_SUCCESS;
532         result = NULL;
533
534         res_len = GetCurrentDirectory (len, buf);
535         if (res_len > len) { /*buf is too small.*/
536                 int old_res_len = res_len;
537                 g_free (buf);
538                 buf = g_new (gunichar2, res_len);
539                 res_len = GetCurrentDirectory (res_len, buf) == old_res_len;
540         }
541         
542         if (res_len) {
543                 len = 0;
544                 while (buf [len])
545                         ++ len;
546
547                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
548         } else {
549                 *error=GetLastError ();
550         }
551
552         g_free (buf);
553         return result;
554 }
555
556 MonoBoolean
557 ves_icall_System_IO_MonoIO_SetCurrentDirectory (MonoString *path,
558                                                 gint32 *error)
559 {
560         gboolean ret;
561         
562         MONO_ARCH_SAVE_REGS;
563
564         *error=ERROR_SUCCESS;
565         
566         ret=SetCurrentDirectory (mono_string_chars (path));
567         if(ret==FALSE) {
568                 *error=GetLastError ();
569         }
570         
571         return(ret);
572 }
573
574 MonoBoolean
575 ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest,
576                                      gint32 *error)
577 {
578         gboolean ret;
579         
580         MONO_ARCH_SAVE_REGS;
581
582         *error=ERROR_SUCCESS;
583         
584         ret=MoveFile (mono_string_chars (path), mono_string_chars (dest));
585         if(ret==FALSE) {
586                 *error=GetLastError ();
587         }
588         
589         return(ret);
590 }
591
592 MonoBoolean
593 ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *destinationFileName,
594                                         MonoString *destinationBackupFileName, MonoBoolean ignoreMetadataErrors,
595                                         gint32 *error)
596 {
597         gboolean ret;
598         gunichar2 *utf16_sourceFileName = NULL, *utf16_destinationFileName = NULL, *utf16_destinationBackupFileName = NULL;
599         guint32 replaceFlags = REPLACEFILE_WRITE_THROUGH;
600
601         MONO_ARCH_SAVE_REGS;
602
603         if (sourceFileName)
604                 utf16_sourceFileName = mono_string_chars (sourceFileName);
605         if (destinationFileName)
606                 utf16_destinationFileName = mono_string_chars (destinationFileName);
607         if (destinationBackupFileName)
608                 utf16_destinationBackupFileName = mono_string_chars (destinationBackupFileName);
609
610         *error = ERROR_SUCCESS;
611         if (ignoreMetadataErrors)
612                 replaceFlags |= REPLACEFILE_IGNORE_MERGE_ERRORS;
613
614         ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
615                          replaceFlags, NULL, NULL);
616         if (ret == FALSE)
617                 *error = GetLastError ();
618
619         return ret;
620 }
621
622 MonoBoolean
623 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
624                                      MonoBoolean overwrite, gint32 *error)
625 {
626         gboolean ret;
627         
628         MONO_ARCH_SAVE_REGS;
629
630         *error=ERROR_SUCCESS;
631         
632         ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
633         if(ret==FALSE) {
634                 *error=GetLastError ();
635         }
636         
637         return(ret);
638 }
639
640 MonoBoolean
641 ves_icall_System_IO_MonoIO_DeleteFile (MonoString *path, gint32 *error)
642 {
643         gboolean ret;
644         
645         MONO_ARCH_SAVE_REGS;
646
647         *error=ERROR_SUCCESS;
648         
649         ret=DeleteFile (mono_string_chars (path));
650         if(ret==FALSE) {
651                 *error=GetLastError ();
652         }
653         
654         return(ret);
655 }
656
657 gint32 
658 ves_icall_System_IO_MonoIO_GetFileAttributes (MonoString *path, gint32 *error)
659 {
660         gint32 ret;
661         
662         MONO_ARCH_SAVE_REGS;
663
664         *error=ERROR_SUCCESS;
665         
666         ret=get_file_attributes (mono_string_chars (path));
667
668         /* 
669          * The definition of INVALID_FILE_ATTRIBUTES in the cygwin win32
670          * headers is wrong, hence this temporary workaround.
671          * See
672          * http://cygwin.com/ml/cygwin/2003-09/msg01771.html
673          */
674         if (ret==-1) {
675           /* if(ret==INVALID_FILE_ATTRIBUTES) { */
676                 *error=GetLastError ();
677         }
678         
679         return(ret);
680 }
681
682 MonoBoolean
683 ves_icall_System_IO_MonoIO_SetFileAttributes (MonoString *path, gint32 attrs,
684                                               gint32 *error)
685 {
686         gboolean ret;
687         
688         MONO_ARCH_SAVE_REGS;
689
690         *error=ERROR_SUCCESS;
691         
692         ret=SetFileAttributes (mono_string_chars (path),
693                                convert_attrs (attrs));
694         if(ret==FALSE) {
695                 *error=GetLastError ();
696         }
697         
698         return(ret);
699 }
700
701 gint32
702 ves_icall_System_IO_MonoIO_GetFileType (HANDLE handle, gint32 *error)
703 {
704         gboolean ret;
705         
706         MONO_ARCH_SAVE_REGS;
707
708         *error=ERROR_SUCCESS;
709         
710         ret=GetFileType (handle);
711         if(ret==FILE_TYPE_UNKNOWN) {
712                 /* Not necessarily an error, but the caller will have
713                  * to decide based on the error value.
714                  */
715                 *error=GetLastError ();
716         }
717         
718         return(ret);
719 }
720
721 MonoBoolean
722 ves_icall_System_IO_MonoIO_GetFileStat (MonoString *path, MonoIOStat *stat,
723                                         gint32 *error)
724 {
725         gboolean result;
726         WIN32_FILE_ATTRIBUTE_DATA data;
727
728         MONO_ARCH_SAVE_REGS;
729
730         *error=ERROR_SUCCESS;
731         
732         result = get_file_attributes_ex (mono_string_chars (path), &data);
733
734         if (result) {
735                 convert_win32_file_attribute_data (&data,
736                                                    mono_string_chars (path),
737                                                    stat);
738         } else {
739                 *error=GetLastError ();
740                 memset (stat, 0, sizeof (MonoIOStat));
741         }
742
743         return result;
744 }
745
746 HANDLE 
747 ves_icall_System_IO_MonoIO_Open (MonoString *filename, gint32 mode,
748                                  gint32 access_mode, gint32 share, gint32 options,
749                                  gint32 *error)
750 {
751         HANDLE ret;
752         int attributes, attrs;
753         gunichar2 *chars = mono_string_chars (filename);
754         
755         MONO_ARCH_SAVE_REGS;
756
757         *error=ERROR_SUCCESS;
758
759         if (options != 0){
760                 if (options & FileOptions_Encrypted)
761                         attributes = FILE_ATTRIBUTE_ENCRYPTED;
762                 else
763                         attributes = FILE_ATTRIBUTE_NORMAL;
764                 if (options & FileOptions_DeleteOnClose)
765                         attributes |= FILE_FLAG_DELETE_ON_CLOSE;
766                 if (options & FileOptions_SequentialScan)
767                         attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
768                 if (options & FileOptions_RandomAccess)
769                         attributes |= FILE_FLAG_RANDOM_ACCESS;
770
771                 if (options & FileOptions_Temporary)
772                         attributes |= FILE_ATTRIBUTE_TEMPORARY;
773                 
774                 /* Not sure if we should set FILE_FLAG_OVERLAPPED, how does this mix with the "Async" bool here? */
775                 if (options & FileOptions_Asynchronous)
776                         attributes |= FILE_FLAG_OVERLAPPED;
777                 
778                 if (options & FileOptions_WriteThrough)
779                         attributes |= FILE_FLAG_WRITE_THROUGH;
780         } else
781                 attributes = FILE_ATTRIBUTE_NORMAL;
782
783         /* If we're opening a directory we need to set the extra flag
784          */
785         attrs = get_file_attributes (chars);
786         if (attrs != INVALID_FILE_ATTRIBUTES) {
787                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
788                         attributes |= FILE_FLAG_BACKUP_SEMANTICS;
789                 }
790         }
791         
792         ret=CreateFile (chars, convert_access (access_mode),
793                         convert_share (share), NULL, convert_mode (mode),
794                         attributes, NULL);
795         if(ret==INVALID_HANDLE_VALUE) {
796                 *error=GetLastError ();
797         } 
798         
799         return(ret);
800 }
801
802 MonoBoolean
803 ves_icall_System_IO_MonoIO_Close (HANDLE handle, gint32 *error)
804 {
805         gboolean ret;
806         
807         MONO_ARCH_SAVE_REGS;
808
809         *error=ERROR_SUCCESS;
810         
811         ret=CloseHandle (handle);
812         if(ret==FALSE) {
813                 *error=GetLastError ();
814         }
815         
816         return(ret);
817 }
818
819 gint32 
820 ves_icall_System_IO_MonoIO_Read (HANDLE handle, MonoArray *dest,
821                                  gint32 dest_offset, gint32 count,
822                                  gint32 *error)
823 {
824         guchar *buffer;
825         gboolean result;
826         guint32 n;
827
828         MONO_ARCH_SAVE_REGS;
829
830         *error=ERROR_SUCCESS;
831
832         MONO_CHECK_ARG_NULL (dest);
833         
834         if (dest_offset + count > mono_array_length (dest))
835                 return 0;
836
837         buffer = mono_array_addr (dest, guchar, dest_offset);
838         result = ReadFile (handle, buffer, count, &n, NULL);
839
840         if (!result) {
841                 *error=GetLastError ();
842                 return -1;
843         }
844
845         return (gint32)n;
846 }
847
848 gint32 
849 ves_icall_System_IO_MonoIO_Write (HANDLE handle, MonoArray *src,
850                                   gint32 src_offset, gint32 count,
851                                   gint32 *error)
852 {
853         guchar *buffer;
854         gboolean result;
855         guint32 n;
856
857         MONO_ARCH_SAVE_REGS;
858
859         *error=ERROR_SUCCESS;
860
861         MONO_CHECK_ARG_NULL (src);
862         
863         if (src_offset + count > mono_array_length (src))
864                 return 0;
865         
866         buffer = mono_array_addr (src, guchar, src_offset);
867         result = WriteFile (handle, buffer, count, &n, NULL);
868
869         if (!result) {
870                 *error=GetLastError ();
871                 return -1;
872         }
873
874         return (gint32)n;
875 }
876
877 gint64 
878 ves_icall_System_IO_MonoIO_Seek (HANDLE handle, gint64 offset, gint32 origin,
879                                  gint32 *error)
880 {
881         gint32 offset_hi;
882
883         MONO_ARCH_SAVE_REGS;
884
885         *error=ERROR_SUCCESS;
886         
887         offset_hi = offset >> 32;
888         offset = SetFilePointer (handle, (gint32) (offset & 0xFFFFFFFF), &offset_hi,
889                                  convert_seekorigin (origin));
890
891         if(offset==INVALID_SET_FILE_POINTER) {
892                 *error=GetLastError ();
893         }
894         
895         return offset | ((gint64)offset_hi << 32);
896 }
897
898 MonoBoolean
899 ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
900 {
901         gboolean ret;
902         
903         MONO_ARCH_SAVE_REGS;
904
905         *error=ERROR_SUCCESS;
906         
907         ret=FlushFileBuffers (handle);
908         if(ret==FALSE) {
909                 *error=GetLastError ();
910         }
911         
912         return(ret);
913 }
914
915 gint64 
916 ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
917 {
918         gint64 length;
919         guint32 length_hi;
920
921         MONO_ARCH_SAVE_REGS;
922
923         *error=ERROR_SUCCESS;
924         
925         length = GetFileSize (handle, &length_hi);
926         if(length==INVALID_FILE_SIZE) {
927                 *error=GetLastError ();
928         }
929         
930         return length | ((gint64)length_hi << 32);
931 }
932
933 MonoBoolean
934 ves_icall_System_IO_MonoIO_SetLength (HANDLE handle, gint64 length,
935                                       gint32 *error)
936 {
937         gint64 offset, offset_set;
938         gint32 offset_hi;
939         gint32 length_hi;
940         gboolean result;
941
942         MONO_ARCH_SAVE_REGS;
943
944         *error=ERROR_SUCCESS;
945         
946         /* save file pointer */
947
948         offset_hi = 0;
949         offset = SetFilePointer (handle, 0, &offset_hi, FILE_CURRENT);
950         if(offset==INVALID_SET_FILE_POINTER) {
951                 *error=GetLastError ();
952                 return(FALSE);
953         }
954
955         /* extend or truncate */
956
957         length_hi = length >> 32;
958         offset_set=SetFilePointer (handle, length & 0xFFFFFFFF, &length_hi,
959                                    FILE_BEGIN);
960         if(offset_set==INVALID_SET_FILE_POINTER) {
961                 *error=GetLastError ();
962                 return(FALSE);
963         }
964
965         result = SetEndOfFile (handle);
966         if(result==FALSE) {
967                 *error=GetLastError ();
968                 return(FALSE);
969         }
970
971         /* restore file pointer */
972
973         offset_set=SetFilePointer (handle, offset & 0xFFFFFFFF, &offset_hi,
974                                    FILE_BEGIN);
975         if(offset_set==INVALID_SET_FILE_POINTER) {
976                 *error=GetLastError ();
977                 return(FALSE);
978         }
979
980         return result;
981 }
982
983 MonoBoolean
984 ves_icall_System_IO_MonoIO_SetFileTime (HANDLE handle, gint64 creation_time,
985                                         gint64 last_access_time,
986                                         gint64 last_write_time, gint32 *error)
987 {
988         gboolean ret;
989         const FILETIME *creation_filetime;
990         const FILETIME *last_access_filetime;
991         const FILETIME *last_write_filetime;
992
993         MONO_ARCH_SAVE_REGS;
994
995         *error=ERROR_SUCCESS;
996         
997         if (creation_time < 0)
998                 creation_filetime = NULL;
999         else
1000                 creation_filetime = (FILETIME *)&creation_time;
1001
1002         if (last_access_time < 0)
1003                 last_access_filetime = NULL;
1004         else
1005                 last_access_filetime = (FILETIME *)&last_access_time;
1006
1007         if (last_write_time < 0)
1008                 last_write_filetime = NULL;
1009         else
1010                 last_write_filetime = (FILETIME *)&last_write_time;
1011
1012         ret=SetFileTime (handle, creation_filetime, last_access_filetime, last_write_filetime);
1013         if(ret==FALSE) {
1014                 *error=GetLastError ();
1015         }
1016         
1017         return(ret);
1018 }
1019
1020 HANDLE 
1021 ves_icall_System_IO_MonoIO_get_ConsoleOutput ()
1022 {
1023         MONO_ARCH_SAVE_REGS;
1024
1025         return GetStdHandle (STD_OUTPUT_HANDLE);
1026 }
1027
1028 HANDLE 
1029 ves_icall_System_IO_MonoIO_get_ConsoleInput ()
1030 {
1031         MONO_ARCH_SAVE_REGS;
1032
1033         return GetStdHandle (STD_INPUT_HANDLE);
1034 }
1035
1036 HANDLE 
1037 ves_icall_System_IO_MonoIO_get_ConsoleError ()
1038 {
1039         MONO_ARCH_SAVE_REGS;
1040
1041         return GetStdHandle (STD_ERROR_HANDLE);
1042 }
1043
1044 MonoBoolean
1045 ves_icall_System_IO_MonoIO_CreatePipe (HANDLE *read_handle,
1046                                        HANDLE *write_handle)
1047 {
1048         SECURITY_ATTRIBUTES attr;
1049         gboolean ret;
1050         
1051         MONO_ARCH_SAVE_REGS;
1052
1053         attr.nLength=sizeof(SECURITY_ATTRIBUTES);
1054         attr.bInheritHandle=TRUE;
1055         attr.lpSecurityDescriptor=NULL;
1056         
1057         ret=CreatePipe (read_handle, write_handle, &attr, 0);
1058         if(ret==FALSE) {
1059                 /* FIXME: throw an exception? */
1060                 return(FALSE);
1061         }
1062         
1063         return(TRUE);
1064 }
1065
1066 MonoBoolean ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, 
1067                                                 HANDLE source_handle, HANDLE target_process_handle, HANDLE *target_handle, 
1068                                                 gint32 access, gint32 inherit, gint32 options)
1069 {
1070         /* This is only used on Windows */
1071         gboolean ret;
1072         
1073         MONO_ARCH_SAVE_REGS;
1074         
1075         ret=DuplicateHandle (source_process_handle, source_handle, target_process_handle, target_handle, access, inherit, options);
1076         if(ret==FALSE) {
1077                 /* FIXME: throw an exception? */
1078                 return(FALSE);
1079         }
1080         
1081         return(TRUE);
1082 }
1083
1084 gunichar2 
1085 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
1086 {
1087 #if defined (TARGET_WIN32)
1088         return (gunichar2) ':'; /* colon */
1089 #else
1090         return (gunichar2) '/'; /* forward slash */
1091 #endif
1092 }
1093
1094 gunichar2 
1095 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
1096 {
1097 #if defined (TARGET_WIN32)
1098         return (gunichar2) '\\';        /* backslash */
1099 #else
1100         return (gunichar2) '/'; /* forward slash */
1101 #endif
1102 }
1103
1104 gunichar2 
1105 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
1106 {
1107 #if defined (TARGET_WIN32)
1108         return (gunichar2) '/'; /* forward slash */
1109 #else
1110         return (gunichar2) '/'; /* slash, same as DirectorySeparatorChar */
1111 #endif
1112 }
1113
1114 gunichar2 
1115 ves_icall_System_IO_MonoIO_get_PathSeparator ()
1116 {
1117 #if defined (TARGET_WIN32)
1118         return (gunichar2) ';'; /* semicolon */
1119 #else
1120         return (gunichar2) ':'; /* colon */
1121 #endif
1122 }
1123
1124 static const gunichar2
1125 invalid_path_chars [] = {
1126 #if defined (TARGET_WIN32)
1127         0x0022,                         /* double quote, which seems allowed in MS.NET but should be rejected */
1128         0x003c,                         /* less than */
1129         0x003e,                         /* greater than */
1130         0x007c,                         /* pipe */
1131         0x0008,
1132         0x0010,
1133         0x0011,
1134         0x0012,
1135         0x0014,
1136         0x0015,
1137         0x0016,
1138         0x0017,
1139         0x0018,
1140         0x0019,
1141 #endif
1142         0x0000                          /* null */
1143 };
1144
1145 MonoArray *
1146 ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
1147 {
1148         MonoArray *chars;
1149         MonoDomain *domain;
1150         int i, n;
1151
1152         MONO_ARCH_SAVE_REGS;
1153
1154         domain = mono_domain_get ();
1155         n = sizeof (invalid_path_chars) / sizeof (gunichar2);
1156         chars = mono_array_new (domain, mono_defaults.char_class, n);
1157
1158         for (i = 0; i < n; ++ i)
1159                 mono_array_set (chars, gunichar2, i, invalid_path_chars [i]);
1160         
1161         return chars;
1162 }
1163
1164 gint32
1165 ves_icall_System_IO_MonoIO_GetTempPath (MonoString **mono_name)
1166 {
1167         gunichar2 *name;
1168         int ret;
1169
1170         name=g_new0 (gunichar2, 256);
1171         
1172         ret=GetTempPath (256, name);
1173         if(ret>255) {
1174                 /* Buffer was too short. Try again... */
1175                 g_free (name);
1176                 name=g_new0 (gunichar2, ret+2); /* include the terminator */
1177                 ret=GetTempPath (ret, name);
1178         }
1179         
1180         if(ret>0) {
1181 #ifdef DEBUG
1182                 g_message ("%s: Temp path is [%s] (len %d)", __func__, name, ret);
1183 #endif
1184
1185                 mono_gc_wbarrier_generic_store ((gpointer) mono_name,
1186                                 (MonoObject*) mono_string_new_utf16 (mono_domain_get (), name, ret));
1187         }
1188
1189         g_free (name);
1190         
1191         return(ret);
1192 }
1193
1194 void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
1195                                       gint64 length, gint32 *error)
1196 {
1197         gboolean ret;
1198         
1199         *error=ERROR_SUCCESS;
1200         
1201         ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
1202                       length & 0xFFFFFFFF, length >> 32);
1203         if (ret == FALSE) {
1204                 *error = GetLastError ();
1205         }
1206 }
1207
1208 void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
1209                                         gint64 length, gint32 *error)
1210 {
1211         gboolean ret;
1212         
1213         *error=ERROR_SUCCESS;
1214         
1215         ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
1216                         length & 0xFFFFFFFF, length >> 32);
1217         if (ret == FALSE) {
1218                 *error = GetLastError ();
1219         }
1220 }
1221