64e46c2d588487defd3ac2979aab5cdfc51d5396
[mono.git] / mono / metadata / w32file-unix.c
1 /**
2  * \file
3  */
4
5 #include <config.h>
6 #include <glib.h>
7
8 #include <stdlib.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <string.h>
13 #include <sys/stat.h>
14 #ifdef HAVE_SYS_STATVFS_H
15 #include <sys/statvfs.h>
16 #endif
17 #if defined(HAVE_SYS_STATFS_H)
18 #include <sys/statfs.h>
19 #endif
20 #if defined(HAVE_SYS_PARAM_H) && defined(HAVE_SYS_MOUNT_H)
21 #include <sys/param.h>
22 #include <sys/mount.h>
23 #endif
24 #include <sys/types.h>
25 #include <stdio.h>
26 #include <utime.h>
27 #ifdef __linux__
28 #include <sys/ioctl.h>
29 #include <linux/fs.h>
30 #include <mono/utils/linux_magic.h>
31 #endif
32 #include <sys/time.h>
33 #ifdef HAVE_DIRENT_H
34 # include <dirent.h>
35 #endif
36
37 #include "w32file.h"
38 #include "w32file-internals.h"
39
40 #include "w32file-unix-glob.h"
41 #include "w32handle.h"
42 #include "w32error.h"
43 #include "utils/mono-io-portability.h"
44 #include "utils/mono-logger-internals.h"
45 #include "utils/mono-os-mutex.h"
46 #include "utils/mono-threads.h"
47 #include "utils/mono-threads-api.h"
48 #include "utils/strenc.h"
49
50 typedef struct {
51         guint64 device;
52         guint64 inode;
53         guint32 sharemode;
54         guint32 access;
55         guint32 handle_refs;
56         guint32 timestamp;
57 } FileShare;
58
59 /* Currently used for both FILE, CONSOLE and PIPE handle types.
60  * This may have to change in future. */
61 typedef struct {
62         gchar *filename;
63         FileShare *share_info;  /* Pointer into shared mem */
64         gint fd;
65         guint32 security_attributes;
66         guint32 fileaccess;
67         guint32 sharemode;
68         guint32 attrs;
69 } MonoW32HandleFile;
70
71 typedef struct {
72         gchar **namelist;
73         gchar *dir_part;
74         gint num;
75         gsize count;
76 } MonoW32HandleFind;
77
78 /*
79  * If SHM is disabled, this will point to a hash of FileShare structures, otherwise
80  * it will be NULL. We use this instead of _wapi_fileshare_layout to avoid allocating a
81  * 4MB array.
82  */
83 static GHashTable *file_share_table;
84 static MonoCoopMutex file_share_mutex;
85
86 static void
87 time_t_to_filetime (time_t timeval, FILETIME *filetime)
88 {
89         guint64 ticks;
90         
91         ticks = ((guint64)timeval * 10000000) + 116444736000000000ULL;
92         filetime->dwLowDateTime = ticks & 0xFFFFFFFF;
93         filetime->dwHighDateTime = ticks >> 32;
94 }
95
96 static void
97 file_share_release (FileShare *share_info)
98 {
99         /* Prevent new entries racing with us */
100         mono_coop_mutex_lock (&file_share_mutex);
101
102         g_assert (share_info->handle_refs > 0);
103         share_info->handle_refs -= 1;
104
105         if (share_info->handle_refs == 0)
106                 g_hash_table_remove (file_share_table, share_info);
107
108         mono_coop_mutex_unlock (&file_share_mutex);
109 }
110
111 static gint
112 file_share_equal (gconstpointer ka, gconstpointer kb)
113 {
114         const FileShare *s1 = (const FileShare *)ka;
115         const FileShare *s2 = (const FileShare *)kb;
116
117         return (s1->device == s2->device && s1->inode == s2->inode) ? 1 : 0;
118 }
119
120 static guint
121 file_share_hash (gconstpointer data)
122 {
123         const FileShare *s = (const FileShare *)data;
124
125         return s->inode;
126 }
127
128 static gboolean
129 file_share_get (guint64 device, guint64 inode, guint32 new_sharemode, guint32 new_access,
130         guint32 *old_sharemode, guint32 *old_access, FileShare **share_info)
131 {
132         FileShare *file_share;
133         gboolean exists = FALSE;
134
135         /* Prevent new entries racing with us */
136         mono_coop_mutex_lock (&file_share_mutex);
137
138         FileShare tmp;
139
140         /*
141          * Instead of allocating a 4MB array, we use a hash table to keep track of this
142          * info. This is needed even if SHM is disabled, to track sharing inside
143          * the current process.
144          */
145         if (!file_share_table)
146                 file_share_table = g_hash_table_new_full (file_share_hash, file_share_equal, NULL, g_free);
147
148         tmp.device = device;
149         tmp.inode = inode;
150
151         file_share = (FileShare *)g_hash_table_lookup (file_share_table, &tmp);
152         if (file_share) {
153                 *old_sharemode = file_share->sharemode;
154                 *old_access = file_share->access;
155                 *share_info = file_share;
156
157                 g_assert (file_share->handle_refs > 0);
158                 file_share->handle_refs += 1;
159
160                 exists = TRUE;
161         } else {
162                 file_share = g_new0 (FileShare, 1);
163
164                 file_share->device = device;
165                 file_share->inode = inode;
166                 file_share->sharemode = new_sharemode;
167                 file_share->access = new_access;
168                 file_share->handle_refs = 1;
169                 *share_info = file_share;
170
171                 g_hash_table_insert (file_share_table, file_share, file_share);
172         }
173
174         mono_coop_mutex_unlock (&file_share_mutex);
175
176         return(exists);
177 }
178
179 static gint
180 _wapi_open (const gchar *pathname, gint flags, mode_t mode)
181 {
182         gint fd;
183         gchar *located_filename;
184
185         if (flags & O_CREAT) {
186                 located_filename = mono_portability_find_file (pathname, FALSE);
187                 if (located_filename == NULL) {
188                         MONO_ENTER_GC_SAFE;
189                         fd = open (pathname, flags, mode);
190                         MONO_EXIT_GC_SAFE;
191                 } else {
192                         MONO_ENTER_GC_SAFE;
193                         fd = open (located_filename, flags, mode);
194                         MONO_EXIT_GC_SAFE;
195                         g_free (located_filename);
196                 }
197         } else {
198                 MONO_ENTER_GC_SAFE;
199                 fd = open (pathname, flags, mode);
200                 MONO_EXIT_GC_SAFE;
201                 if (fd == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
202                         gint saved_errno = errno;
203                         located_filename = mono_portability_find_file (pathname, TRUE);
204
205                         if (located_filename == NULL) {
206                                 errno = saved_errno;
207                                 return -1;
208                         }
209
210                         MONO_ENTER_GC_SAFE;
211                         fd = open (located_filename, flags, mode);
212                         MONO_EXIT_GC_SAFE;
213                         g_free (located_filename);
214                 }
215         }
216
217         return(fd);
218 }
219
220 static gint
221 _wapi_access (const gchar *pathname, gint mode)
222 {
223         gint ret;
224
225         MONO_ENTER_GC_SAFE;
226         ret = access (pathname, mode);
227         MONO_EXIT_GC_SAFE;
228         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
229                 gint saved_errno = errno;
230                 gchar *located_filename = mono_portability_find_file (pathname, TRUE);
231
232                 if (located_filename == NULL) {
233                         errno = saved_errno;
234                         return -1;
235                 }
236
237                 MONO_ENTER_GC_SAFE;
238                 ret = access (located_filename, mode);
239                 MONO_EXIT_GC_SAFE;
240                 g_free (located_filename);
241         }
242
243         return ret;
244 }
245
246 static gint
247 _wapi_chmod (const gchar *pathname, mode_t mode)
248 {
249         gint ret;
250
251         MONO_ENTER_GC_SAFE;
252         ret = chmod (pathname, mode);
253         MONO_EXIT_GC_SAFE;
254         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
255                 gint saved_errno = errno;
256                 gchar *located_filename = mono_portability_find_file (pathname, TRUE);
257
258                 if (located_filename == NULL) {
259                         errno = saved_errno;
260                         return -1;
261                 }
262
263                 MONO_ENTER_GC_SAFE;
264                 ret = chmod (located_filename, mode);
265                 MONO_EXIT_GC_SAFE;
266                 g_free (located_filename);
267         }
268
269         return ret;
270 }
271
272 static gint
273 _wapi_utime (const gchar *filename, const struct utimbuf *buf)
274 {
275         gint ret;
276
277         MONO_ENTER_GC_SAFE;
278         ret = utime (filename, buf);
279         MONO_EXIT_GC_SAFE;
280         if (ret == -1 && errno == ENOENT && IS_PORTABILITY_SET) {
281                 gint saved_errno = errno;
282                 gchar *located_filename = mono_portability_find_file (filename, TRUE);
283
284                 if (located_filename == NULL) {
285                         errno = saved_errno;
286                         return -1;
287                 }
288
289                 MONO_ENTER_GC_SAFE;
290                 ret = utime (located_filename, buf);
291                 MONO_EXIT_GC_SAFE;
292                 g_free (located_filename);
293         }
294
295         return ret;
296 }
297
298 static gint
299 _wapi_unlink (const gchar *pathname)
300 {
301         gint ret;
302
303         MONO_ENTER_GC_SAFE;
304         ret = unlink (pathname);
305         MONO_EXIT_GC_SAFE;
306         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR || errno == EISDIR) && IS_PORTABILITY_SET) {
307                 gint saved_errno = errno;
308                 gchar *located_filename = mono_portability_find_file (pathname, TRUE);
309
310                 if (located_filename == NULL) {
311                         errno = saved_errno;
312                         return -1;
313                 }
314
315                 MONO_ENTER_GC_SAFE;
316                 ret = unlink (located_filename);
317                 MONO_EXIT_GC_SAFE;
318                 g_free (located_filename);
319         }
320
321         return ret;
322 }
323
324 static gint
325 _wapi_rename (const gchar *oldpath, const gchar *newpath)
326 {
327         gint ret;
328         gchar *located_newpath = mono_portability_find_file (newpath, FALSE);
329
330         if (located_newpath == NULL) {
331                 MONO_ENTER_GC_SAFE;
332                 ret = rename (oldpath, newpath);
333                 MONO_EXIT_GC_SAFE;
334         } else {
335                 MONO_ENTER_GC_SAFE;
336                 ret = rename (oldpath, located_newpath);
337                 MONO_EXIT_GC_SAFE;
338
339                 if (ret == -1 && (errno == EISDIR || errno == ENAMETOOLONG || errno == ENOENT || errno == ENOTDIR || errno == EXDEV) && IS_PORTABILITY_SET) {
340                         gint saved_errno = errno;
341                         gchar *located_oldpath = mono_portability_find_file (oldpath, TRUE);
342
343                         if (located_oldpath == NULL) {
344                                 g_free (located_oldpath);
345                                 g_free (located_newpath);
346
347                                 errno = saved_errno;
348                                 return -1;
349                         }
350
351                         MONO_ENTER_GC_SAFE;
352                         ret = rename (located_oldpath, located_newpath);
353                         MONO_EXIT_GC_SAFE;
354                         g_free (located_oldpath);
355                 }
356                 g_free (located_newpath);
357         }
358
359         return ret;
360 }
361
362 static gint
363 _wapi_stat (const gchar *path, struct stat *buf)
364 {
365         gint ret;
366
367         MONO_ENTER_GC_SAFE;
368         ret = stat (path, buf);
369         MONO_EXIT_GC_SAFE;
370         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
371                 gint saved_errno = errno;
372                 gchar *located_filename = mono_portability_find_file (path, TRUE);
373
374                 if (located_filename == NULL) {
375                         errno = saved_errno;
376                         return -1;
377                 }
378
379                 MONO_ENTER_GC_SAFE;
380                 ret = stat (located_filename, buf);
381                 MONO_EXIT_GC_SAFE;
382                 g_free (located_filename);
383         }
384
385         return ret;
386 }
387
388 static gint
389 _wapi_lstat (const gchar *path, struct stat *buf)
390 {
391         gint ret;
392
393         MONO_ENTER_GC_SAFE;
394         ret = lstat (path, buf);
395         MONO_EXIT_GC_SAFE;
396         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR) && IS_PORTABILITY_SET) {
397                 gint saved_errno = errno;
398                 gchar *located_filename = mono_portability_find_file (path, TRUE);
399
400                 if (located_filename == NULL) {
401                         errno = saved_errno;
402                         return -1;
403                 }
404
405                 ret = lstat (located_filename, buf);
406                 g_free (located_filename);
407         }
408
409         return ret;
410 }
411
412 static gint
413 _wapi_mkdir (const gchar *pathname, mode_t mode)
414 {
415         gint ret;
416         gchar *located_filename = mono_portability_find_file (pathname, FALSE);
417
418         if (located_filename == NULL) {
419                 MONO_ENTER_GC_SAFE;
420                 ret = mkdir (pathname, mode);
421                 MONO_EXIT_GC_SAFE;
422         } else {
423                 MONO_ENTER_GC_SAFE;
424                 ret = mkdir (located_filename, mode);
425                 MONO_EXIT_GC_SAFE;
426                 g_free (located_filename);
427         }
428
429         return ret;
430 }
431
432 static gint
433 _wapi_rmdir (const gchar *pathname)
434 {
435         gint ret;
436
437         MONO_ENTER_GC_SAFE;
438         ret = rmdir (pathname);
439         MONO_EXIT_GC_SAFE;
440         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG) && IS_PORTABILITY_SET) {
441                 gint saved_errno = errno;
442                 gchar *located_filename = mono_portability_find_file (pathname, TRUE);
443
444                 if (located_filename == NULL) {
445                         errno = saved_errno;
446                         return -1;
447                 }
448
449                 MONO_ENTER_GC_SAFE;
450                 ret = rmdir (located_filename);
451                 MONO_EXIT_GC_SAFE;
452                 g_free (located_filename);
453         }
454
455         return ret;
456 }
457
458 static gint
459 _wapi_chdir (const gchar *path)
460 {
461         gint ret;
462
463         MONO_ENTER_GC_SAFE;
464         ret = chdir (path);
465         MONO_EXIT_GC_SAFE;
466         if (ret == -1 && (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG) && IS_PORTABILITY_SET) {
467                 gint saved_errno = errno;
468                 gchar *located_filename = mono_portability_find_file (path, TRUE);
469
470                 if (located_filename == NULL) {
471                         errno = saved_errno;
472                         return -1;
473                 }
474
475                 MONO_ENTER_GC_SAFE;
476                 ret = chdir (located_filename);
477                 MONO_EXIT_GC_SAFE;
478                 g_free (located_filename);
479         }
480
481         return ret;
482 }
483
484 static gchar*
485 _wapi_basename (const gchar *filename)
486 {
487         gchar *new_filename = g_strdup (filename), *ret;
488
489         if (IS_PORTABILITY_SET) {
490                 g_strdelimit (new_filename, "\\", '/');
491         }
492
493         if (IS_PORTABILITY_DRIVE && g_ascii_isalpha (new_filename[0]) && (new_filename[1] == ':')) {
494                 gint len = strlen (new_filename);
495
496                 g_memmove (new_filename, new_filename + 2, len - 2);
497                 new_filename[len - 2] = '\0';
498         }
499
500         ret = g_path_get_basename (new_filename);
501         g_free (new_filename);
502
503         return ret;
504 }
505
506 static gchar*
507 _wapi_dirname (const gchar *filename)
508 {
509         gchar *new_filename = g_strdup (filename), *ret;
510
511         if (IS_PORTABILITY_SET) {
512                 g_strdelimit (new_filename, "\\", '/');
513         }
514
515         if (IS_PORTABILITY_DRIVE && g_ascii_isalpha (new_filename[0]) && (new_filename[1] == ':')) {
516                 gint len = strlen (new_filename);
517
518                 g_memmove (new_filename, new_filename + 2, len - 2);
519                 new_filename[len - 2] = '\0';
520         }
521
522         ret = g_path_get_dirname (new_filename);
523         g_free (new_filename);
524
525         return ret;
526 }
527
528 static GDir*
529 _wapi_g_dir_open (const gchar *path, guint flags, GError **error)
530 {
531         GDir *ret;
532
533         MONO_ENTER_GC_SAFE;
534         ret = g_dir_open (path, flags, error);
535         MONO_EXIT_GC_SAFE;
536         if (ret == NULL && ((*error)->code == G_FILE_ERROR_NOENT || (*error)->code == G_FILE_ERROR_NOTDIR || (*error)->code == G_FILE_ERROR_NAMETOOLONG) && IS_PORTABILITY_SET) {
537                 gchar *located_filename = mono_portability_find_file (path, TRUE);
538                 GError *tmp_error = NULL;
539
540                 if (located_filename == NULL) {
541                         return(NULL);
542                 }
543
544                 MONO_ENTER_GC_SAFE;
545                 ret = g_dir_open (located_filename, flags, &tmp_error);
546                 MONO_EXIT_GC_SAFE;
547                 g_free (located_filename);
548                 if (tmp_error == NULL) {
549                         g_clear_error (error);
550                 }
551         }
552
553         return ret;
554 }
555
556 static gint
557 get_errno_from_g_file_error (gint error)
558 {
559         switch (error) {
560 #ifdef EACCES
561         case G_FILE_ERROR_ACCES: return EACCES;
562 #endif
563 #ifdef ENAMETOOLONG
564         case G_FILE_ERROR_NAMETOOLONG: return ENAMETOOLONG;
565 #endif
566 #ifdef ENOENT
567         case G_FILE_ERROR_NOENT: return ENOENT;
568 #endif
569 #ifdef ENOTDIR
570         case G_FILE_ERROR_NOTDIR: return ENOTDIR;
571 #endif
572 #ifdef ENXIO
573         case G_FILE_ERROR_NXIO: return ENXIO;
574 #endif
575 #ifdef ENODEV
576         case G_FILE_ERROR_NODEV: return ENODEV;
577 #endif
578 #ifdef EROFS
579         case G_FILE_ERROR_ROFS: return EROFS;
580 #endif
581 #ifdef ETXTBSY
582         case G_FILE_ERROR_TXTBSY: return ETXTBSY;
583 #endif
584 #ifdef EFAULT
585         case G_FILE_ERROR_FAULT: return EFAULT;
586 #endif
587 #ifdef ELOOP
588         case G_FILE_ERROR_LOOP: return ELOOP;
589 #endif
590 #ifdef ENOSPC
591         case G_FILE_ERROR_NOSPC: return ENOSPC;
592 #endif
593 #ifdef ENOMEM
594         case G_FILE_ERROR_NOMEM: return ENOMEM;
595 #endif
596 #ifdef EMFILE
597         case G_FILE_ERROR_MFILE: return EMFILE;
598 #endif
599 #ifdef ENFILE
600         case G_FILE_ERROR_NFILE: return ENFILE;
601 #endif
602 #ifdef EBADF
603         case G_FILE_ERROR_BADF: return EBADF;
604 #endif
605 #ifdef EINVAL
606         case G_FILE_ERROR_INVAL: return EINVAL;
607 #endif
608 #ifdef EPIPE
609         case G_FILE_ERROR_PIPE: return EPIPE;
610 #endif
611 #ifdef EAGAIN
612         case G_FILE_ERROR_AGAIN: return EAGAIN;
613 #endif
614 #ifdef EINTR
615         case G_FILE_ERROR_INTR: return EINTR;
616 #endif
617 #ifdef EIO
618         case G_FILE_ERROR_IO: return EIO;
619 #endif
620 #ifdef EPERM
621         case G_FILE_ERROR_PERM: return EPERM;
622 #endif
623         case G_FILE_ERROR_FAILED: return ERROR_INVALID_PARAMETER;
624         default:
625                 g_assert_not_reached ();
626         }
627 }
628
629 static gint
630 file_compare (gconstpointer a, gconstpointer b)
631 {
632         gchar *astr = *(gchar **) a;
633         gchar *bstr = *(gchar **) b;
634
635         return strcmp (astr, bstr);
636 }
637
638 /* scandir using glib */
639 static gint
640 _wapi_io_scandir (const gchar *dirname, const gchar *pattern, gchar ***namelist)
641 {
642         GError *error = NULL;
643         GDir *dir;
644         GPtrArray *names;
645         gint result;
646         mono_w32file_unix_glob_t glob_buf;
647         gint flags = 0, i;
648
649         dir = _wapi_g_dir_open (dirname, 0, &error);
650         if (dir == NULL) {
651                 /* g_dir_open returns ENOENT on directories on which we don't
652                  * have read/x permission */
653                 gint errnum = get_errno_from_g_file_error (error->code);
654                 g_error_free (error);
655                 if (errnum == ENOENT &&
656                     !_wapi_access (dirname, F_OK) &&
657                     _wapi_access (dirname, R_OK|X_OK)) {
658                         errnum = EACCES;
659                 }
660
661                 errno = errnum;
662                 return -1;
663         }
664
665         if (IS_PORTABILITY_CASE) {
666                 flags = W32FILE_UNIX_GLOB_IGNORECASE;
667         }
668
669         result = mono_w32file_unix_glob (dir, pattern, flags, &glob_buf);
670         if (g_str_has_suffix (pattern, ".*")) {
671                 /* Special-case the patterns ending in '.*', as
672                  * windows also matches entries with no extension with
673                  * this pattern.
674                  *
675                  * TODO: should this be a MONO_IOMAP option?
676                  */
677                 gchar *pattern2 = g_strndup (pattern, strlen (pattern) - 2);
678                 gint result2;
679
680                 MONO_ENTER_GC_SAFE;
681                 g_dir_rewind (dir);
682                 MONO_EXIT_GC_SAFE;
683                 result2 = mono_w32file_unix_glob (dir, pattern2, flags | W32FILE_UNIX_GLOB_APPEND | W32FILE_UNIX_GLOB_UNIQUE, &glob_buf);
684
685                 g_free (pattern2);
686
687                 if (result != 0) {
688                         result = result2;
689                 }
690         }
691
692         MONO_ENTER_GC_SAFE;
693         g_dir_close (dir);
694         MONO_EXIT_GC_SAFE;
695         if (glob_buf.gl_pathc == 0) {
696                 return(0);
697         } else if (result != 0) {
698                 return -1;
699         }
700
701         names = g_ptr_array_new ();
702         for (i = 0; i < glob_buf.gl_pathc; i++) {
703                 g_ptr_array_add (names, g_strdup (glob_buf.gl_pathv[i]));
704         }
705
706         mono_w32file_unix_globfree (&glob_buf);
707
708         result = names->len;
709         if (result > 0) {
710                 g_ptr_array_sort (names, file_compare);
711                 g_ptr_array_set_size (names, result + 1);
712
713                 *namelist = (gchar **) g_ptr_array_free (names, FALSE);
714         } else {
715                 g_ptr_array_free (names, TRUE);
716         }
717
718         return result;
719 }
720
721 static gboolean
722 _wapi_lock_file_region (gint fd, off_t offset, off_t length)
723 {
724         struct flock lock_data;
725         gint ret;
726
727         if (offset < 0 || length < 0) {
728                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
729                 return FALSE;
730         }
731
732         lock_data.l_type = F_WRLCK;
733         lock_data.l_whence = SEEK_SET;
734         lock_data.l_start = offset;
735         lock_data.l_len = length;
736
737         do {
738                 ret = fcntl (fd, F_SETLK, &lock_data);
739         } while(ret == -1 && errno == EINTR);
740
741         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fcntl returns %d", __func__, ret);
742
743         if (ret == -1) {
744                 /*
745                  * if locks are not available (NFS for example),
746                  * ignore the error
747                  */
748                 if (errno == ENOLCK
749 #ifdef EOPNOTSUPP
750                     || errno == EOPNOTSUPP
751 #endif
752 #ifdef ENOTSUP
753                     || errno == ENOTSUP
754 #endif
755                    ) {
756                         return TRUE;
757                 }
758
759                 mono_w32error_set_last (ERROR_LOCK_VIOLATION);
760                 return FALSE;
761         }
762
763         return TRUE;
764 }
765
766 static gboolean
767 _wapi_unlock_file_region (gint fd, off_t offset, off_t length)
768 {
769         struct flock lock_data;
770         gint ret;
771
772         lock_data.l_type = F_UNLCK;
773         lock_data.l_whence = SEEK_SET;
774         lock_data.l_start = offset;
775         lock_data.l_len = length;
776
777         do {
778                 ret = fcntl (fd, F_SETLK, &lock_data);
779         } while(ret == -1 && errno == EINTR);
780
781         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fcntl returns %d", __func__, ret);
782
783         if (ret == -1) {
784                 /*
785                  * if locks are not available (NFS for example),
786                  * ignore the error
787                  */
788                 if (errno == ENOLCK
789 #ifdef EOPNOTSUPP
790                     || errno == EOPNOTSUPP
791 #endif
792 #ifdef ENOTSUP
793                     || errno == ENOTSUP
794 #endif
795                    ) {
796                         return TRUE;
797                 }
798
799                 mono_w32error_set_last (ERROR_LOCK_VIOLATION);
800                 return FALSE;
801         }
802
803         return TRUE;
804 }
805
806 static void file_close (gpointer handle, gpointer data);
807 static void file_details (gpointer data);
808 static const gchar* file_typename (void);
809 static gsize file_typesize (void);
810 static gint file_getfiletype(void);
811 static gboolean file_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread);
812 static gboolean file_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten);
813 static gboolean file_flush(gpointer handle);
814 static guint32 file_seek(gpointer handle, gint32 movedistance,
815                          gint32 *highmovedistance, gint method);
816 static gboolean file_setendoffile(gpointer handle);
817 static guint32 file_getfilesize(gpointer handle, guint32 *highsize);
818 static gboolean file_getfiletime(gpointer handle, FILETIME *create_time,
819                                  FILETIME *access_time,
820                                  FILETIME *write_time);
821 static gboolean file_setfiletime(gpointer handle,
822                                  const FILETIME *create_time,
823                                  const FILETIME *access_time,
824                                  const FILETIME *write_time);
825 static guint32 GetDriveTypeFromPath (const gchar *utf8_root_path_name);
826
827 /* File handle is only signalled for overlapped IO */
828 static MonoW32HandleOps _wapi_file_ops = {
829         file_close,             /* close */
830         NULL,                   /* signal */
831         NULL,                   /* own */
832         NULL,                   /* is_owned */
833         NULL,                   /* special_wait */
834         NULL,                   /* prewait */
835         file_details,   /* details */
836         file_typename,  /* typename */
837         file_typesize,  /* typesize */
838 };
839
840 static void console_close (gpointer handle, gpointer data);
841 static void console_details (gpointer data);
842 static const gchar* console_typename (void);
843 static gsize console_typesize (void);
844 static gint console_getfiletype(void);
845 static gboolean console_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread);
846 static gboolean console_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten);
847
848 /* Console is mostly the same as file, except it can block waiting for
849  * input or output
850  */
851 static MonoW32HandleOps _wapi_console_ops = {
852         console_close,          /* close */
853         NULL,                   /* signal */
854         NULL,                   /* own */
855         NULL,                   /* is_owned */
856         NULL,                   /* special_wait */
857         NULL,                   /* prewait */
858         console_details,        /* details */
859         console_typename,       /* typename */
860         console_typesize,       /* typesize */
861 };
862
863 static const gchar* find_typename (void);
864 static gsize find_typesize (void);
865
866 static MonoW32HandleOps _wapi_find_ops = {
867         NULL,                   /* close */
868         NULL,                   /* signal */
869         NULL,                   /* own */
870         NULL,                   /* is_owned */
871         NULL,                   /* special_wait */
872         NULL,                   /* prewait */
873         NULL,                   /* details */
874         find_typename,  /* typename */
875         find_typesize,  /* typesize */
876 };
877
878 static void pipe_close (gpointer handle, gpointer data);
879 static void pipe_details (gpointer data);
880 static const gchar* pipe_typename (void);
881 static gsize pipe_typesize (void);
882 static gint pipe_getfiletype (void);
883 static gboolean pipe_read (gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread);
884 static gboolean pipe_write (gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten);
885
886 /* Pipe handles
887  */
888 static MonoW32HandleOps _wapi_pipe_ops = {
889         pipe_close,             /* close */
890         NULL,                   /* signal */
891         NULL,                   /* own */
892         NULL,                   /* is_owned */
893         NULL,                   /* special_wait */
894         NULL,                   /* prewait */
895         pipe_details,   /* details */
896         pipe_typename,  /* typename */
897         pipe_typesize,  /* typesize */
898 };
899
900 static const struct {
901         /* File, console and pipe handles */
902         gint (*getfiletype)(void);
903         
904         /* File, console and pipe handles */
905         gboolean (*readfile)(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread);
906         gboolean (*writefile)(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten);
907         gboolean (*flushfile)(gpointer handle);
908         
909         /* File handles */
910         guint32 (*seek)(gpointer handle, gint32 movedistance,
911                         gint32 *highmovedistance, gint method);
912         gboolean (*setendoffile)(gpointer handle);
913         guint32 (*getfilesize)(gpointer handle, guint32 *highsize);
914         gboolean (*getfiletime)(gpointer handle, FILETIME *create_time,
915                                 FILETIME *access_time,
916                                 FILETIME *write_time);
917         gboolean (*setfiletime)(gpointer handle,
918                                 const FILETIME *create_time,
919                                 const FILETIME *access_time,
920                                 const FILETIME *write_time);
921 } io_ops[MONO_W32HANDLE_COUNT]={
922         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
923         /* file */
924         {file_getfiletype,
925          file_read, file_write,
926          file_flush, file_seek,
927          file_setendoffile,
928          file_getfilesize,
929          file_getfiletime,
930          file_setfiletime},
931         /* console */
932         {console_getfiletype,
933          console_read,
934          console_write,
935          NULL, NULL, NULL, NULL, NULL, NULL},
936         /* thread */
937         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
938         /* sem */
939         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
940         /* mutex */
941         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
942         /* event */
943         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
944         /* socket (will need at least read and write) */
945         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
946         /* find */
947         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
948         /* process */
949         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
950         /* pipe */
951         {pipe_getfiletype,
952          pipe_read,
953          pipe_write,
954          NULL, NULL, NULL, NULL, NULL, NULL},
955 };
956
957 static gboolean lock_while_writing = FALSE;
958
959 /* Some utility functions.
960  */
961
962 /*
963  * Check if a file is writable by the current user.
964  *
965  * This is is a best effort kind of thing. It assumes a reasonable sane set
966  * of permissions by the underlying OS.
967  *
968  * We generally assume that basic unix permission bits are authoritative. Which might not
969  * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
970  *
971  * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
972  *
973  * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
974  * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
975  * and should not be used with a dynamic runtime.
976  */
977 static gboolean
978 is_file_writable (struct stat *st, const gchar *path)
979 {
980 #if __APPLE__
981         // OS X Finder "locked" or `ls -lO` "uchg".
982         // This only covers one of several cases where an OS X file could be unwritable through special flags.
983         if (st->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
984                 return 0;
985 #endif
986
987         /* Is it globally writable? */
988         if (st->st_mode & S_IWOTH)
989                 return 1;
990
991         /* Am I the owner? */
992         if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
993                 return 1;
994
995         /* Am I in the same group? */
996         if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
997                 return 1;
998
999         /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
1000          * but it's the only sane option we have on unix.
1001          */
1002         return access (path, W_OK) == 0;
1003 }
1004
1005
1006 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
1007                                               struct stat *buf,
1008                                               struct stat *lbuf)
1009 {
1010         guint32 attrs = 0;
1011         gchar *filename;
1012         
1013         /* FIXME: this could definitely be better, but there seems to
1014          * be no pattern to the attributes that are set
1015          */
1016
1017         /* Sockets (0140000) != Directory (040000) + Regular file (0100000) */
1018         if (S_ISSOCK (buf->st_mode))
1019                 buf->st_mode &= ~S_IFSOCK; /* don't consider socket protection */
1020
1021         filename = _wapi_basename (pathname);
1022
1023         if (S_ISDIR (buf->st_mode)) {
1024                 attrs = FILE_ATTRIBUTE_DIRECTORY;
1025                 if (!is_file_writable (buf, pathname)) {
1026                         attrs |= FILE_ATTRIBUTE_READONLY;
1027                 }
1028                 if (filename[0] == '.') {
1029                         attrs |= FILE_ATTRIBUTE_HIDDEN;
1030                 }
1031         } else {
1032                 if (!is_file_writable (buf, pathname)) {
1033                         attrs = FILE_ATTRIBUTE_READONLY;
1034
1035                         if (filename[0] == '.') {
1036                                 attrs |= FILE_ATTRIBUTE_HIDDEN;
1037                         }
1038                 } else if (filename[0] == '.') {
1039                         attrs = FILE_ATTRIBUTE_HIDDEN;
1040                 } else {
1041                         attrs = FILE_ATTRIBUTE_NORMAL;
1042                 }
1043         }
1044
1045         if (lbuf != NULL) {
1046                 if (S_ISLNK (lbuf->st_mode)) {
1047                         attrs |= FILE_ATTRIBUTE_REPARSE_POINT;
1048                 }
1049         }
1050         
1051         g_free (filename);
1052         
1053         return attrs;
1054 }
1055
1056 static void
1057 _wapi_set_last_error_from_errno (void)
1058 {
1059         mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
1060 }
1061
1062 static void _wapi_set_last_path_error_from_errno (const gchar *dir,
1063                                                   const gchar *path)
1064 {
1065         if (errno == ENOENT) {
1066                 /* Check the path - if it's a missing directory then
1067                  * we need to set PATH_NOT_FOUND not FILE_NOT_FOUND
1068                  */
1069                 gchar *dirname;
1070
1071
1072                 if (dir == NULL) {
1073                         dirname = _wapi_dirname (path);
1074                 } else {
1075                         dirname = g_strdup (dir);
1076                 }
1077                 
1078                 if (_wapi_access (dirname, F_OK) == 0) {
1079                         mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
1080                 } else {
1081                         mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
1082                 }
1083
1084                 g_free (dirname);
1085         } else {
1086                 _wapi_set_last_error_from_errno ();
1087         }
1088 }
1089
1090 /* Handle ops.
1091  */
1092 static void file_close (gpointer handle, gpointer data)
1093 {
1094         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
1095         MONO_ENTER_GC_UNSAFE;
1096         MonoW32HandleFile *file_handle = (MonoW32HandleFile *)data;
1097         gint fd = file_handle->fd;
1098         
1099         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
1100                   file_handle->filename);
1101
1102         if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
1103                 _wapi_unlink (file_handle->filename);
1104         
1105         g_free (file_handle->filename);
1106         
1107         if (file_handle->share_info)
1108                 file_share_release (file_handle->share_info);
1109         
1110         MONO_ENTER_GC_SAFE;
1111         close (fd);
1112         MONO_EXIT_GC_SAFE;
1113         MONO_EXIT_GC_UNSAFE;
1114 }
1115
1116 static void file_details (gpointer data)
1117 {
1118         MonoW32HandleFile *file = (MonoW32HandleFile *)data;
1119         
1120         g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
1121                  file->filename,
1122                  file->fileaccess&GENERIC_READ?'R':'.',
1123                  file->fileaccess&GENERIC_WRITE?'W':'.',
1124                  file->fileaccess&GENERIC_EXECUTE?'X':'.',
1125                  file->sharemode&FILE_SHARE_READ?'R':'.',
1126                  file->sharemode&FILE_SHARE_WRITE?'W':'.',
1127                  file->sharemode&FILE_SHARE_DELETE?'D':'.',
1128                  file->attrs);
1129 }
1130
1131 static const gchar* file_typename (void)
1132 {
1133         return "File";
1134 }
1135
1136 static gsize file_typesize (void)
1137 {
1138         return sizeof (MonoW32HandleFile);
1139 }
1140
1141 static gint file_getfiletype(void)
1142 {
1143         return(FILE_TYPE_DISK);
1144 }
1145
1146 static gboolean
1147 file_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
1148 {
1149         MonoW32HandleFile *file_handle;
1150         gboolean ok;
1151         gint fd, ret;
1152         MonoThreadInfo *info = mono_thread_info_current ();
1153         
1154         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1155                                 (gpointer *)&file_handle);
1156         if(ok==FALSE) {
1157                 g_warning ("%s: error looking up file handle %p", __func__,
1158                            handle);
1159                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1160                 return(FALSE);
1161         }
1162
1163         fd = file_handle->fd;
1164         if(bytesread!=NULL) {
1165                 *bytesread=0;
1166         }
1167         
1168         if(!(file_handle->fileaccess & GENERIC_READ) &&
1169            !(file_handle->fileaccess & GENERIC_ALL)) {
1170                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1171                           __func__, handle, file_handle->fileaccess);
1172
1173                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1174                 return(FALSE);
1175         }
1176
1177         do {
1178                 MONO_ENTER_GC_SAFE;
1179                 ret = read (fd, buffer, numbytes);
1180                 MONO_EXIT_GC_SAFE;
1181         } while (ret == -1 && errno == EINTR &&
1182                  !mono_thread_info_is_interrupt_state (info));
1183                         
1184         if(ret==-1) {
1185                 gint err = errno;
1186
1187                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1188                           handle, strerror(err));
1189                 mono_w32error_set_last (mono_w32error_unix_to_win32 (err));
1190                 return(FALSE);
1191         }
1192                 
1193         if (bytesread != NULL) {
1194                 *bytesread = ret;
1195         }
1196                 
1197         return(TRUE);
1198 }
1199
1200 static gboolean
1201 file_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
1202 {
1203         MonoW32HandleFile *file_handle;
1204         gboolean ok;
1205         gint ret, fd;
1206         off_t current_pos = 0;
1207         MonoThreadInfo *info = mono_thread_info_current ();
1208         
1209         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1210                                 (gpointer *)&file_handle);
1211         if(ok==FALSE) {
1212                 g_warning ("%s: error looking up file handle %p", __func__,
1213                            handle);
1214                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1215                 return(FALSE);
1216         }
1217
1218         fd = file_handle->fd;
1219         
1220         if(byteswritten!=NULL) {
1221                 *byteswritten=0;
1222         }
1223         
1224         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1225            !(file_handle->fileaccess & GENERIC_ALL)) {
1226                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1227
1228                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1229                 return(FALSE);
1230         }
1231         
1232         if (lock_while_writing) {
1233                 /* Need to lock the region we're about to write to,
1234                  * because we only do advisory locking on POSIX
1235                  * systems
1236                  */
1237                 MONO_ENTER_GC_SAFE;
1238                 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
1239                 MONO_EXIT_GC_SAFE;
1240                 if (current_pos == -1) {
1241                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
1242                                    handle, strerror (errno));
1243                         _wapi_set_last_error_from_errno ();
1244                         return(FALSE);
1245                 }
1246                 
1247                 if (_wapi_lock_file_region (fd, current_pos,
1248                                             numbytes) == FALSE) {
1249                         /* The error has already been set */
1250                         return(FALSE);
1251                 }
1252         }
1253                 
1254         do {
1255                 MONO_ENTER_GC_SAFE;
1256                 ret = write (fd, buffer, numbytes);
1257                 MONO_EXIT_GC_SAFE;
1258         } while (ret == -1 && errno == EINTR &&
1259                  !mono_thread_info_is_interrupt_state (info));
1260         
1261         if (lock_while_writing) {
1262                 _wapi_unlock_file_region (fd, current_pos, numbytes);
1263         }
1264
1265         if (ret == -1) {
1266                 if (errno == EINTR) {
1267                         ret = 0;
1268                 } else {
1269                         _wapi_set_last_error_from_errno ();
1270                                 
1271                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1272                                   __func__, handle, strerror(errno));
1273
1274                         return(FALSE);
1275                 }
1276         }
1277         if (byteswritten != NULL) {
1278                 *byteswritten = ret;
1279         }
1280         return(TRUE);
1281 }
1282
1283 static gboolean file_flush(gpointer handle)
1284 {
1285         MonoW32HandleFile *file_handle;
1286         gboolean ok;
1287         gint ret, fd;
1288         
1289         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1290                                 (gpointer *)&file_handle);
1291         if(ok==FALSE) {
1292                 g_warning ("%s: error looking up file handle %p", __func__,
1293                            handle);
1294                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1295                 return(FALSE);
1296         }
1297
1298         fd = file_handle->fd;
1299
1300         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1301            !(file_handle->fileaccess & GENERIC_ALL)) {
1302                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1303
1304                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1305                 return(FALSE);
1306         }
1307
1308         MONO_ENTER_GC_SAFE;
1309         ret=fsync(fd);
1310         MONO_EXIT_GC_SAFE;
1311         if (ret==-1) {
1312                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
1313                           strerror(errno));
1314
1315                 _wapi_set_last_error_from_errno ();
1316                 return(FALSE);
1317         }
1318         
1319         return(TRUE);
1320 }
1321
1322 static guint32 file_seek(gpointer handle, gint32 movedistance,
1323                          gint32 *highmovedistance, gint method)
1324 {
1325         MonoW32HandleFile *file_handle;
1326         gboolean ok;
1327         gint64 offset, newpos;
1328         gint whence, fd;
1329         guint32 ret;
1330         
1331         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1332                                 (gpointer *)&file_handle);
1333         if(ok==FALSE) {
1334                 g_warning ("%s: error looking up file handle %p", __func__,
1335                            handle);
1336                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1337                 return(INVALID_SET_FILE_POINTER);
1338         }
1339         
1340         fd = file_handle->fd;
1341
1342         if(!(file_handle->fileaccess & GENERIC_READ) &&
1343            !(file_handle->fileaccess & GENERIC_WRITE) &&
1344            !(file_handle->fileaccess & GENERIC_ALL)) {
1345                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1346
1347                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1348                 return(INVALID_SET_FILE_POINTER);
1349         }
1350
1351         switch(method) {
1352         case FILE_BEGIN:
1353                 whence=SEEK_SET;
1354                 break;
1355         case FILE_CURRENT:
1356                 whence=SEEK_CUR;
1357                 break;
1358         case FILE_END:
1359                 whence=SEEK_END;
1360                 break;
1361         default:
1362                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
1363
1364                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1365                 return(INVALID_SET_FILE_POINTER);
1366         }
1367
1368 #ifdef HAVE_LARGE_FILE_SUPPORT
1369         if(highmovedistance==NULL) {
1370                 offset=movedistance;
1371                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %" G_GINT64_FORMAT " (low %" G_GINT32_FORMAT ")", __func__,
1372                           offset, movedistance);
1373         } else {
1374                 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
1375                 
1376                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %" G_GINT64_FORMAT " 0x%" PRIx64 " (high %" G_GINT32_FORMAT " 0x%" PRIx32 ", low %" G_GINT32_FORMAT " 0x%" PRIx32 ")",
1377                           __func__, offset, offset, *highmovedistance, *highmovedistance, movedistance, movedistance);
1378         }
1379 #else
1380         offset=movedistance;
1381 #endif
1382
1383         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %" G_GINT64_FORMAT " bytes from %d", __func__,
1384                    handle, offset, whence);
1385
1386 #ifdef PLATFORM_ANDROID
1387         /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
1388         MONO_ENTER_GC_SAFE;
1389         newpos=lseek64(fd, offset, whence);
1390         MONO_EXIT_GC_SAFE;
1391 #else
1392         MONO_ENTER_GC_SAFE;
1393         newpos=lseek(fd, offset, whence);
1394         MONO_EXIT_GC_SAFE;
1395 #endif
1396         if(newpos==-1) {
1397                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
1398                           __func__, handle, strerror(errno));
1399
1400                 _wapi_set_last_error_from_errno ();
1401                 return(INVALID_SET_FILE_POINTER);
1402         }
1403
1404         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %" G_GINT64_FORMAT, __func__, newpos);
1405
1406 #ifdef HAVE_LARGE_FILE_SUPPORT
1407         ret=newpos & 0xFFFFFFFF;
1408         if(highmovedistance!=NULL) {
1409                 *highmovedistance=newpos>>32;
1410         }
1411 #else
1412         ret=newpos;
1413         if(highmovedistance!=NULL) {
1414                 /* Accurate, but potentially dodgy :-) */
1415                 *highmovedistance=0;
1416         }
1417 #endif
1418
1419         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %" G_GUINT32_FORMAT "/%" G_GINT32_FORMAT, __func__,
1420                    handle, ret, highmovedistance==NULL?0:*highmovedistance);
1421
1422         return(ret);
1423 }
1424
1425 static gboolean file_setendoffile(gpointer handle)
1426 {
1427         MonoW32HandleFile *file_handle;
1428         gboolean ok;
1429         struct stat statbuf;
1430         off_t pos;
1431         gint ret, fd;
1432         MonoThreadInfo *info = mono_thread_info_current ();
1433         
1434         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1435                                 (gpointer *)&file_handle);
1436         if(ok==FALSE) {
1437                 g_warning ("%s: error looking up file handle %p", __func__,
1438                            handle);
1439                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1440                 return(FALSE);
1441         }
1442         fd = file_handle->fd;
1443         
1444         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1445            !(file_handle->fileaccess & GENERIC_ALL)) {
1446                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1447
1448                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1449                 return(FALSE);
1450         }
1451
1452         /* Find the current file position, and the file length.  If
1453          * the file position is greater than the length, write to
1454          * extend the file with a hole.  If the file position is less
1455          * than the length, truncate the file.
1456          */
1457         
1458         MONO_ENTER_GC_SAFE;
1459         ret=fstat(fd, &statbuf);
1460         MONO_EXIT_GC_SAFE;
1461         if(ret==-1) {
1462                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
1463                            handle, strerror(errno));
1464
1465                 _wapi_set_last_error_from_errno ();
1466                 return(FALSE);
1467         }
1468
1469         MONO_ENTER_GC_SAFE;
1470         pos=lseek(fd, (off_t)0, SEEK_CUR);
1471         MONO_EXIT_GC_SAFE;
1472         if(pos==-1) {
1473                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
1474                           handle, strerror(errno));
1475
1476                 _wapi_set_last_error_from_errno ();
1477                 return(FALSE);
1478         }
1479         
1480 #ifdef FTRUNCATE_DOESNT_EXTEND
1481         off_t size = statbuf.st_size;
1482         /* I haven't bothered to write the configure.ac stuff for this
1483          * because I don't know if any platform needs it.  I'm leaving
1484          * this code just in case though
1485          */
1486         if(pos>size) {
1487                 /* Extend the file.  Use write() here, because some
1488                  * manuals say that ftruncate() behaviour is undefined
1489                  * when the file needs extending.  The POSIX spec says
1490                  * that on XSI-conformant systems it extends, so if
1491                  * every system we care about conforms, then we can
1492                  * drop this write.
1493                  */
1494                 do {
1495                         MONO_ENTER_GC_SAFE;
1496                         ret = write (fd, "", 1);
1497                         MONO_EXIT_GC_SAFE;
1498                 } while (ret == -1 && errno == EINTR &&
1499                          !mono_thread_info_is_interrupt_state (info));
1500
1501                 if(ret==-1) {
1502                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
1503
1504                         _wapi_set_last_error_from_errno ();
1505                         return(FALSE);
1506                 }
1507
1508                 /* And put the file position back after the write */
1509                 MONO_ENTER_GC_SAFE;
1510                 ret = lseek (fd, pos, SEEK_SET);
1511                 MONO_EXIT_GC_SAFE;
1512                 if (ret == -1) {
1513                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
1514                                    __func__, handle, strerror(errno));
1515
1516                         _wapi_set_last_error_from_errno ();
1517                         return(FALSE);
1518                 }
1519         }
1520 #endif
1521
1522         /* always truncate, because the extend write() adds an extra
1523          * byte to the end of the file
1524          */
1525         do {
1526                 MONO_ENTER_GC_SAFE;
1527                 ret=ftruncate(fd, pos);
1528                 MONO_EXIT_GC_SAFE;
1529         }
1530         while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info)); 
1531         if(ret==-1) {
1532                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
1533                           handle, strerror(errno));
1534                 
1535                 _wapi_set_last_error_from_errno ();
1536                 return(FALSE);
1537         }
1538                 
1539         return(TRUE);
1540 }
1541
1542 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
1543 {
1544         MonoW32HandleFile *file_handle;
1545         gboolean ok;
1546         struct stat statbuf;
1547         guint32 size;
1548         gint ret;
1549         gint fd;
1550         
1551         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1552                                 (gpointer *)&file_handle);
1553         if(ok==FALSE) {
1554                 g_warning ("%s: error looking up file handle %p", __func__,
1555                            handle);
1556                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1557                 return(INVALID_FILE_SIZE);
1558         }
1559         fd = file_handle->fd;
1560         
1561         if(!(file_handle->fileaccess & GENERIC_READ) &&
1562            !(file_handle->fileaccess & GENERIC_WRITE) &&
1563            !(file_handle->fileaccess & GENERIC_ALL)) {
1564                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1565
1566                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1567                 return(INVALID_FILE_SIZE);
1568         }
1569
1570         /* If the file has a size with the low bits 0xFFFFFFFF the
1571          * caller can't tell if this is an error, so clear the error
1572          * value
1573          */
1574         mono_w32error_set_last (ERROR_SUCCESS);
1575         
1576         MONO_ENTER_GC_SAFE;
1577         ret = fstat(fd, &statbuf);
1578         MONO_EXIT_GC_SAFE;
1579         if (ret == -1) {
1580                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
1581                            handle, strerror(errno));
1582
1583                 _wapi_set_last_error_from_errno ();
1584                 return(INVALID_FILE_SIZE);
1585         }
1586         
1587         /* fstat indicates block devices as zero-length, so go a different path */
1588 #ifdef BLKGETSIZE64
1589         if (S_ISBLK(statbuf.st_mode)) {
1590                 guint64 bigsize;
1591                 gint res;
1592                 MONO_ENTER_GC_SAFE;
1593                 res = ioctl (fd, BLKGETSIZE64, &bigsize);
1594                 MONO_EXIT_GC_SAFE;
1595                 if (res < 0) {
1596                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
1597                                    __func__, handle, strerror(errno));
1598
1599                         _wapi_set_last_error_from_errno ();
1600                         return(INVALID_FILE_SIZE);
1601                 }
1602                 
1603                 size = bigsize & 0xFFFFFFFF;
1604                 if (highsize != NULL) {
1605                         *highsize = bigsize>>32;
1606                 }
1607
1608                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %" G_GUINT32_FORMAT "/%" G_GUINT32_FORMAT,
1609                            __func__, size, *highsize);
1610         
1611                 return(size);
1612         }
1613 #endif
1614         
1615 #ifdef HAVE_LARGE_FILE_SUPPORT
1616         size = statbuf.st_size & 0xFFFFFFFF;
1617         if (highsize != NULL) {
1618                 *highsize = statbuf.st_size>>32;
1619         }
1620 #else
1621         if (highsize != NULL) {
1622                 /* Accurate, but potentially dodgy :-) */
1623                 *highsize = 0;
1624         }
1625         size = statbuf.st_size;
1626 #endif
1627
1628         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %" G_GUINT32_FORMAT "/%" G_GUINT32_FORMAT, __func__, size, *highsize);
1629         
1630         return(size);
1631 }
1632
1633 static gboolean file_getfiletime(gpointer handle, FILETIME *create_time,
1634                                  FILETIME *access_time,
1635                                  FILETIME *write_time)
1636 {
1637         MonoW32HandleFile *file_handle;
1638         gboolean ok;
1639         struct stat statbuf;
1640         guint64 create_ticks, access_ticks, write_ticks;
1641         gint ret, fd;
1642         
1643         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1644                                 (gpointer *)&file_handle);
1645         if(ok==FALSE) {
1646                 g_warning ("%s: error looking up file handle %p", __func__,
1647                            handle);
1648                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1649                 return(FALSE);
1650         }
1651         fd = file_handle->fd;
1652
1653         if(!(file_handle->fileaccess & GENERIC_READ) &&
1654            !(file_handle->fileaccess & GENERIC_ALL)) {
1655                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1656                           __func__, handle, file_handle->fileaccess);
1657
1658                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1659                 return(FALSE);
1660         }
1661         
1662         MONO_ENTER_GC_SAFE;
1663         ret=fstat(fd, &statbuf);
1664         MONO_EXIT_GC_SAFE;
1665         if(ret==-1) {
1666                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1667                           strerror(errno));
1668
1669                 _wapi_set_last_error_from_errno ();
1670                 return(FALSE);
1671         }
1672
1673         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
1674                   statbuf.st_atime, statbuf.st_ctime,
1675                   statbuf.st_mtime);
1676
1677         /* Try and guess a meaningful create time by using the older
1678          * of atime or ctime
1679          */
1680         /* The magic constant comes from msdn documentation
1681          * "Converting a time_t Value to a File Time"
1682          */
1683         if(statbuf.st_atime < statbuf.st_ctime) {
1684                 create_ticks=((guint64)statbuf.st_atime*10000000)
1685                         + 116444736000000000ULL;
1686         } else {
1687                 create_ticks=((guint64)statbuf.st_ctime*10000000)
1688                         + 116444736000000000ULL;
1689         }
1690         
1691         access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1692         write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1693         
1694         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %" G_GUINT64_FORMAT " cticks: %" G_GUINT64_FORMAT " wticks: %" G_GUINT64_FORMAT, __func__,
1695                   access_ticks, create_ticks, write_ticks);
1696
1697         if(create_time!=NULL) {
1698                 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1699                 create_time->dwHighDateTime = create_ticks >> 32;
1700         }
1701         
1702         if(access_time!=NULL) {
1703                 access_time->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1704                 access_time->dwHighDateTime = access_ticks >> 32;
1705         }
1706         
1707         if(write_time!=NULL) {
1708                 write_time->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1709                 write_time->dwHighDateTime = write_ticks >> 32;
1710         }
1711
1712         return(TRUE);
1713 }
1714
1715 static gboolean file_setfiletime(gpointer handle,
1716                                  const FILETIME *create_time G_GNUC_UNUSED,
1717                                  const FILETIME *access_time,
1718                                  const FILETIME *write_time)
1719 {
1720         MonoW32HandleFile *file_handle;
1721         gboolean ok;
1722         struct utimbuf utbuf;
1723         struct stat statbuf;
1724         guint64 access_ticks, write_ticks;
1725         gint ret, fd;
1726         
1727         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1728                                 (gpointer *)&file_handle);
1729         if(ok==FALSE) {
1730                 g_warning ("%s: error looking up file handle %p", __func__,
1731                            handle);
1732                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1733                 return(FALSE);
1734         }
1735         fd = file_handle->fd;
1736         
1737         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1738            !(file_handle->fileaccess & GENERIC_ALL)) {
1739                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
1740
1741                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1742                 return(FALSE);
1743         }
1744
1745         if(file_handle->filename == NULL) {
1746                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1747
1748                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1749                 return(FALSE);
1750         }
1751         
1752         /* Get the current times, so we can put the same times back in
1753          * the event that one of the FileTime structs is NULL
1754          */
1755         MONO_ENTER_GC_SAFE;
1756         ret=fstat (fd, &statbuf);
1757         MONO_EXIT_GC_SAFE;
1758         if(ret==-1) {
1759                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1760                           strerror(errno));
1761
1762                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1763                 return(FALSE);
1764         }
1765
1766         if(access_time!=NULL) {
1767                 access_ticks=((guint64)access_time->dwHighDateTime << 32) +
1768                         access_time->dwLowDateTime;
1769                 /* This is (time_t)0.  We can actually go to INT_MIN,
1770                  * but this will do for now.
1771                  */
1772                 if (access_ticks < 116444736000000000ULL) {
1773                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1774                                    __func__);
1775                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1776                         return(FALSE);
1777                 }
1778
1779                 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1780                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
1781                                    __func__);
1782                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1783                         return(FALSE);
1784                 }
1785
1786                 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1787         } else {
1788                 utbuf.actime=statbuf.st_atime;
1789         }
1790
1791         if(write_time!=NULL) {
1792                 write_ticks=((guint64)write_time->dwHighDateTime << 32) +
1793                         write_time->dwLowDateTime;
1794                 /* This is (time_t)0.  We can actually go to INT_MIN,
1795                  * but this will do for now.
1796                  */
1797                 if (write_ticks < 116444736000000000ULL) {
1798                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1799                                    __func__);
1800                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1801                         return(FALSE);
1802                 }
1803                 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1804                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
1805                                    __func__);
1806                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1807                         return(FALSE);
1808                 }
1809                 
1810                 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1811         } else {
1812                 utbuf.modtime=statbuf.st_mtime;
1813         }
1814
1815         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1816                    handle, utbuf.actime, utbuf.modtime);
1817
1818         ret = _wapi_utime (file_handle->filename, &utbuf);
1819         if (ret == -1) {
1820                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1821                            handle, file_handle->filename, strerror(errno));
1822
1823                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1824                 return(FALSE);
1825         }
1826         
1827         return(TRUE);
1828 }
1829
1830 static void console_close (gpointer handle, gpointer data)
1831 {
1832         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
1833         MONO_ENTER_GC_UNSAFE;
1834         MonoW32HandleFile *console_handle = (MonoW32HandleFile *)data;
1835         gint fd = console_handle->fd;
1836         
1837         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1838
1839         g_free (console_handle->filename);
1840
1841         if (fd > 2) {
1842                 if (console_handle->share_info)
1843                         file_share_release (console_handle->share_info);
1844                 MONO_ENTER_GC_SAFE;
1845                 close (fd);
1846                 MONO_EXIT_GC_SAFE;
1847         }
1848         MONO_EXIT_GC_UNSAFE;
1849 }
1850
1851 static void console_details (gpointer data)
1852 {
1853         file_details (data);
1854 }
1855
1856 static const gchar* console_typename (void)
1857 {
1858         return "Console";
1859 }
1860
1861 static gsize console_typesize (void)
1862 {
1863         return sizeof (MonoW32HandleFile);
1864 }
1865
1866 static gint console_getfiletype(void)
1867 {
1868         return(FILE_TYPE_CHAR);
1869 }
1870
1871 static gboolean
1872 console_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
1873 {
1874         MonoW32HandleFile *console_handle;
1875         gboolean ok;
1876         gint ret, fd;
1877         MonoThreadInfo *info = mono_thread_info_current ();
1878
1879         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1880                                 (gpointer *)&console_handle);
1881         if(ok==FALSE) {
1882                 g_warning ("%s: error looking up console handle %p", __func__,
1883                            handle);
1884                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1885                 return(FALSE);
1886         }
1887         fd = console_handle->fd;
1888         
1889         if(bytesread!=NULL) {
1890                 *bytesread=0;
1891         }
1892         
1893         if(!(console_handle->fileaccess & GENERIC_READ) &&
1894            !(console_handle->fileaccess & GENERIC_ALL)) {
1895                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1896                            __func__, handle, console_handle->fileaccess);
1897
1898                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1899                 return(FALSE);
1900         }
1901         
1902         do {
1903                 MONO_ENTER_GC_SAFE;
1904                 ret=read(fd, buffer, numbytes);
1905                 MONO_EXIT_GC_SAFE;
1906         } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1907
1908         if(ret==-1) {
1909                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1910                           strerror(errno));
1911
1912                 _wapi_set_last_error_from_errno ();
1913                 return(FALSE);
1914         }
1915         
1916         if(bytesread!=NULL) {
1917                 *bytesread=ret;
1918         }
1919         
1920         return(TRUE);
1921 }
1922
1923 static gboolean
1924 console_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
1925 {
1926         MonoW32HandleFile *console_handle;
1927         gboolean ok;
1928         gint ret, fd;
1929         MonoThreadInfo *info = mono_thread_info_current ();
1930         
1931         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1932                                 (gpointer *)&console_handle);
1933         if(ok==FALSE) {
1934                 g_warning ("%s: error looking up console handle %p", __func__,
1935                            handle);
1936                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1937                 return(FALSE);
1938         }
1939         fd = console_handle->fd;
1940         
1941         if(byteswritten!=NULL) {
1942                 *byteswritten=0;
1943         }
1944         
1945         if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1946            !(console_handle->fileaccess & GENERIC_ALL)) {
1947                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, console_handle->fileaccess);
1948
1949                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1950                 return(FALSE);
1951         }
1952         
1953         do {
1954                 MONO_ENTER_GC_SAFE;
1955                 ret = write(fd, buffer, numbytes);
1956                 MONO_EXIT_GC_SAFE;
1957         } while (ret == -1 && errno == EINTR &&
1958                  !mono_thread_info_is_interrupt_state (info));
1959
1960         if (ret == -1) {
1961                 if (errno == EINTR) {
1962                         ret = 0;
1963                 } else {
1964                         _wapi_set_last_error_from_errno ();
1965                         
1966                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1967                                    __func__, handle, strerror(errno));
1968
1969                         return(FALSE);
1970                 }
1971         }
1972         if(byteswritten!=NULL) {
1973                 *byteswritten=ret;
1974         }
1975         
1976         return(TRUE);
1977 }
1978
1979 static const gchar* find_typename (void)
1980 {
1981         return "Find";
1982 }
1983
1984 static gsize find_typesize (void)
1985 {
1986         return sizeof (MonoW32HandleFind);
1987 }
1988
1989 static void pipe_close (gpointer handle, gpointer data)
1990 {
1991         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
1992         MONO_ENTER_GC_UNSAFE;
1993         MonoW32HandleFile *pipe_handle = (MonoW32HandleFile*)data;
1994         gint fd = pipe_handle->fd;
1995
1996         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
1997
1998         /* No filename with pipe handles */
1999
2000         if (pipe_handle->share_info)
2001                 file_share_release (pipe_handle->share_info);
2002
2003         MONO_ENTER_GC_SAFE;
2004         close (fd);
2005         MONO_EXIT_GC_SAFE;
2006         MONO_EXIT_GC_UNSAFE;
2007 }
2008
2009 static void pipe_details (gpointer data)
2010 {
2011         file_details (data);
2012 }
2013
2014 static const gchar* pipe_typename (void)
2015 {
2016         return "Pipe";
2017 }
2018
2019 static gsize pipe_typesize (void)
2020 {
2021         return sizeof (MonoW32HandleFile);
2022 }
2023
2024 static gint pipe_getfiletype(void)
2025 {
2026         return(FILE_TYPE_PIPE);
2027 }
2028
2029 static gboolean
2030 pipe_read (gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
2031 {
2032         MonoW32HandleFile *pipe_handle;
2033         gboolean ok;
2034         gint ret, fd;
2035         MonoThreadInfo *info = mono_thread_info_current ();
2036
2037         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
2038                                 (gpointer *)&pipe_handle);
2039         if(ok==FALSE) {
2040                 g_warning ("%s: error looking up pipe handle %p", __func__,
2041                            handle);
2042                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2043                 return(FALSE);
2044         }
2045         fd = pipe_handle->fd;
2046
2047         if(bytesread!=NULL) {
2048                 *bytesread=0;
2049         }
2050         
2051         if(!(pipe_handle->fileaccess & GENERIC_READ) &&
2052            !(pipe_handle->fileaccess & GENERIC_ALL)) {
2053                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
2054                           __func__, handle, pipe_handle->fileaccess);
2055
2056                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2057                 return(FALSE);
2058         }
2059         
2060         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %" G_GUINT32_FORMAT " bytes from pipe %p", __func__,
2061                    numbytes, handle);
2062
2063         do {
2064                 MONO_ENTER_GC_SAFE;
2065                 ret=read(fd, buffer, numbytes);
2066                 MONO_EXIT_GC_SAFE;
2067         } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
2068                 
2069         if (ret == -1) {
2070                 if (errno == EINTR) {
2071                         ret = 0;
2072                 } else {
2073                         _wapi_set_last_error_from_errno ();
2074                         
2075                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
2076                                   handle, strerror(errno));
2077
2078                         return(FALSE);
2079                 }
2080         }
2081         
2082         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
2083
2084         if(bytesread!=NULL) {
2085                 *bytesread=ret;
2086         }
2087         
2088         return(TRUE);
2089 }
2090
2091 static gboolean
2092 pipe_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
2093 {
2094         MonoW32HandleFile *pipe_handle;
2095         gboolean ok;
2096         gint ret, fd;
2097         MonoThreadInfo *info = mono_thread_info_current ();
2098         
2099         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
2100                                 (gpointer *)&pipe_handle);
2101         if(ok==FALSE) {
2102                 g_warning ("%s: error looking up pipe handle %p", __func__,
2103                            handle);
2104                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2105                 return(FALSE);
2106         }
2107         fd = pipe_handle->fd;
2108         
2109         if(byteswritten!=NULL) {
2110                 *byteswritten=0;
2111         }
2112         
2113         if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
2114            !(pipe_handle->fileaccess & GENERIC_ALL)) {
2115                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_WRITE access: %u", __func__, handle, pipe_handle->fileaccess);
2116
2117                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2118                 return(FALSE);
2119         }
2120         
2121         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %" G_GUINT32_FORMAT " bytes to pipe %p", __func__,
2122                    numbytes, handle);
2123
2124         do {
2125                 MONO_ENTER_GC_SAFE;
2126                 ret = write (fd, buffer, numbytes);
2127                 MONO_EXIT_GC_SAFE;
2128         } while (ret == -1 && errno == EINTR &&
2129                  !mono_thread_info_is_interrupt_state (info));
2130
2131         if (ret == -1) {
2132                 if (errno == EINTR) {
2133                         ret = 0;
2134                 } else {
2135                         _wapi_set_last_error_from_errno ();
2136                         
2137                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
2138                                   handle, strerror(errno));
2139
2140                         return(FALSE);
2141                 }
2142         }
2143         if(byteswritten!=NULL) {
2144                 *byteswritten=ret;
2145         }
2146         
2147         return(TRUE);
2148 }
2149
2150 static gint convert_flags(guint32 fileaccess, guint32 createmode)
2151 {
2152         gint flags=0;
2153         
2154         switch(fileaccess) {
2155         case GENERIC_READ:
2156                 flags=O_RDONLY;
2157                 break;
2158         case GENERIC_WRITE:
2159                 flags=O_WRONLY;
2160                 break;
2161         case GENERIC_READ|GENERIC_WRITE:
2162                 flags=O_RDWR;
2163                 break;
2164         default:
2165                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%" PRIx32, __func__,
2166                           fileaccess);
2167                 break;
2168         }
2169
2170         switch(createmode) {
2171         case CREATE_NEW:
2172                 flags|=O_CREAT|O_EXCL;
2173                 break;
2174         case CREATE_ALWAYS:
2175                 flags|=O_CREAT|O_TRUNC;
2176                 break;
2177         case OPEN_EXISTING:
2178                 break;
2179         case OPEN_ALWAYS:
2180                 flags|=O_CREAT;
2181                 break;
2182         case TRUNCATE_EXISTING:
2183                 flags|=O_TRUNC;
2184                 break;
2185         default:
2186                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%" PRIx32, __func__,
2187                           createmode);
2188                 break;
2189         }
2190         
2191         return(flags);
2192 }
2193
2194 #if 0 /* unused */
2195 static mode_t convert_perms(guint32 sharemode)
2196 {
2197         mode_t perms=0600;
2198         
2199         if(sharemode&FILE_SHARE_READ) {
2200                 perms|=044;
2201         }
2202         if(sharemode&FILE_SHARE_WRITE) {
2203                 perms|=022;
2204         }
2205
2206         return(perms);
2207 }
2208 #endif
2209
2210 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
2211                                    guint32 fileaccess,
2212                                    FileShare **share_info)
2213 {
2214         gboolean file_already_shared;
2215         guint32 file_existing_share, file_existing_access;
2216
2217         file_already_shared = file_share_get (statbuf->st_dev, statbuf->st_ino, sharemode, fileaccess, &file_existing_share, &file_existing_access, share_info);
2218         
2219         if (file_already_shared) {
2220                 /* The reference to this share info was incremented
2221                  * when we looked it up, so be careful to put it back
2222                  * if we conclude we can't use this file.
2223                  */
2224                 if (file_existing_share == 0) {
2225                         /* Quick and easy, no possibility to share */
2226                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%" PRIx32 ", file has sharing = NONE", __func__, fileaccess);
2227
2228                         file_share_release (*share_info);
2229                         
2230                         return(FALSE);
2231                 }
2232
2233                 if (((file_existing_share == FILE_SHARE_READ) &&
2234                      (fileaccess != GENERIC_READ)) ||
2235                     ((file_existing_share == FILE_SHARE_WRITE) &&
2236                      (fileaccess != GENERIC_WRITE))) {
2237                         /* New access mode doesn't match up */
2238                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%" PRIx32 ", file has sharing: 0x%" PRIx32, __func__, fileaccess, file_existing_share);
2239
2240                         file_share_release (*share_info);
2241                 
2242                         return(FALSE);
2243                 }
2244
2245                 if (((file_existing_access & GENERIC_READ) &&
2246                      !(sharemode & FILE_SHARE_READ)) ||
2247                     ((file_existing_access & GENERIC_WRITE) &&
2248                      !(sharemode & FILE_SHARE_WRITE))) {
2249                         /* New share mode doesn't match up */
2250                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Access mode prevents open: requested share: 0x%" PRIx32 ", file has access: 0x%" PRIx32, __func__, sharemode, file_existing_access);
2251
2252                         file_share_release (*share_info);
2253                 
2254                         return(FALSE);
2255                 }
2256         } else {
2257                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
2258         }
2259
2260         return(TRUE);
2261 }
2262
2263
2264 static gboolean
2265 share_allows_delete (struct stat *statbuf, FileShare **share_info)
2266 {
2267         gboolean file_already_shared;
2268         guint32 file_existing_share, file_existing_access;
2269
2270         file_already_shared = file_share_get (statbuf->st_dev, statbuf->st_ino, FILE_SHARE_DELETE, GENERIC_READ, &file_existing_share, &file_existing_access, share_info);
2271
2272         if (file_already_shared) {
2273                 /* The reference to this share info was incremented
2274                  * when we looked it up, so be careful to put it back
2275                  * if we conclude we can't use this file.
2276                  */
2277                 if (file_existing_share == 0) {
2278                         /* Quick and easy, no possibility to share */
2279                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%" PRIx32 ", file has sharing = NONE", __func__, (*share_info)->access);
2280
2281                         file_share_release (*share_info);
2282
2283                         return(FALSE);
2284                 }
2285
2286                 if (!(file_existing_share & FILE_SHARE_DELETE)) {
2287                         /* New access mode doesn't match up */
2288                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Share mode prevents open: requested access: 0x%" PRIx32 ", file has sharing: 0x%" PRIx32, __func__, (*share_info)->access, file_existing_share);
2289
2290                         file_share_release (*share_info);
2291
2292                         return(FALSE);
2293                 }
2294         } else {
2295                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
2296         }
2297
2298         return(TRUE);
2299 }
2300
2301 gpointer
2302 mono_w32file_create(const gunichar2 *name, guint32 fileaccess, guint32 sharemode, guint32 createmode, guint32 attrs)
2303 {
2304         MonoW32HandleFile file_handle = {0};
2305         gpointer handle;
2306         gint flags=convert_flags(fileaccess, createmode);
2307         /*mode_t perms=convert_perms(sharemode);*/
2308         /* we don't use sharemode, because that relates to sharing of
2309          * the file when the file is open and is already handled by
2310          * other code, perms instead are the on-disk permissions and
2311          * this is a sane default.
2312          */
2313         mode_t perms=0666;
2314         gchar *filename;
2315         gint fd, ret;
2316         MonoW32HandleType handle_type;
2317         struct stat statbuf;
2318
2319         if (attrs & FILE_ATTRIBUTE_TEMPORARY)
2320                 perms = 0600;
2321         
2322         if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
2323                 mono_w32error_set_last (ERROR_ENCRYPTION_FAILED);
2324                 return INVALID_HANDLE_VALUE;
2325         }
2326         
2327         if (name == NULL) {
2328                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2329
2330                 mono_w32error_set_last (ERROR_INVALID_NAME);
2331                 return(INVALID_HANDLE_VALUE);
2332         }
2333
2334         filename = mono_unicode_to_external (name);
2335         if (filename == NULL) {
2336                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2337
2338                 mono_w32error_set_last (ERROR_INVALID_NAME);
2339                 return(INVALID_HANDLE_VALUE);
2340         }
2341         
2342         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%" PRIx32 " and access 0x%" PRIx32, __func__,
2343                    filename, sharemode, fileaccess);
2344         
2345         fd = _wapi_open (filename, flags, perms);
2346     
2347         /* If we were trying to open a directory with write permissions
2348          * (e.g. O_WRONLY or O_RDWR), this call will fail with
2349          * EISDIR. However, this is a bit bogus because calls to
2350          * manipulate the directory (e.g. mono_w32file_set_times) will still work on
2351          * the directory because they use other API calls
2352          * (e.g. utime()). Hence, if we failed with the EISDIR error, try
2353          * to open the directory again without write permission.
2354          */
2355         if (fd == -1 && errno == EISDIR)
2356         {
2357                 /* Try again but don't try to make it writable */
2358                 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
2359         }
2360         
2361         if (fd == -1) {
2362                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
2363                           strerror(errno));
2364                 _wapi_set_last_path_error_from_errno (NULL, filename);
2365                 g_free (filename);
2366
2367                 return(INVALID_HANDLE_VALUE);
2368         }
2369
2370         if (fd >= mono_w32handle_fd_reserve) {
2371                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
2372
2373                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
2374                 
2375                 MONO_ENTER_GC_SAFE;
2376                 close (fd);
2377                 MONO_EXIT_GC_SAFE;
2378                 g_free (filename);
2379                 
2380                 return(INVALID_HANDLE_VALUE);
2381         }
2382
2383         MONO_ENTER_GC_SAFE;
2384         ret = fstat (fd, &statbuf);
2385         MONO_EXIT_GC_SAFE;
2386         if (ret == -1) {
2387                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
2388                            filename, strerror (errno));
2389                 _wapi_set_last_error_from_errno ();
2390                 g_free (filename);
2391                 MONO_ENTER_GC_SAFE;
2392                 close (fd);
2393                 MONO_EXIT_GC_SAFE;
2394                 
2395                 return(INVALID_HANDLE_VALUE);
2396         }
2397
2398         if (share_allows_open (&statbuf, sharemode, fileaccess,
2399                          &file_handle.share_info) == FALSE) {
2400                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2401                 g_free (filename);
2402                 MONO_ENTER_GC_SAFE;
2403                 close (fd);
2404                 MONO_EXIT_GC_SAFE;
2405                 
2406                 return (INVALID_HANDLE_VALUE);
2407         }
2408         if (file_handle.share_info == NULL) {
2409                 /* No space, so no more files can be opened */
2410                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
2411
2412                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
2413                 MONO_ENTER_GC_SAFE;
2414                 close (fd);
2415                 MONO_EXIT_GC_SAFE;
2416                 g_free (filename);
2417                 
2418                 return(INVALID_HANDLE_VALUE);
2419         }
2420         
2421         file_handle.filename = filename;
2422         
2423         file_handle.fd = fd;
2424         file_handle.fileaccess=fileaccess;
2425         file_handle.sharemode=sharemode;
2426         file_handle.attrs=attrs;
2427
2428 #ifdef HAVE_POSIX_FADVISE
2429         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN) {
2430                 MONO_ENTER_GC_SAFE;
2431                 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
2432                 MONO_EXIT_GC_SAFE;
2433         }
2434         if (attrs & FILE_FLAG_RANDOM_ACCESS) {
2435                 MONO_ENTER_GC_SAFE;
2436                 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
2437                 MONO_EXIT_GC_SAFE;
2438         }
2439 #endif
2440
2441 #ifdef F_RDAHEAD
2442         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN) {
2443                 MONO_ENTER_GC_SAFE;
2444                 fcntl(fd, F_RDAHEAD, 1);
2445                 MONO_EXIT_GC_SAFE;
2446         }
2447 #endif
2448
2449 #ifndef S_ISFIFO
2450 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
2451 #endif
2452         if (S_ISFIFO (statbuf.st_mode)) {
2453                 handle_type = MONO_W32HANDLE_PIPE;
2454                 /* maintain invariant that pipes have no filename */
2455                 file_handle.filename = NULL;
2456                 g_free (filename);
2457                 filename = NULL;
2458         } else if (S_ISCHR (statbuf.st_mode)) {
2459                 handle_type = MONO_W32HANDLE_CONSOLE;
2460         } else {
2461                 handle_type = MONO_W32HANDLE_FILE;
2462         }
2463
2464         MONO_ENTER_GC_SAFE; /* FIXME: mono_w32handle_new_fd should be updated with coop transitions */
2465         handle = mono_w32handle_new_fd (handle_type, fd, &file_handle);
2466         MONO_EXIT_GC_SAFE;
2467         if (handle == INVALID_HANDLE_VALUE) {
2468                 g_warning ("%s: error creating file handle", __func__);
2469                 g_free (filename);
2470                 MONO_ENTER_GC_SAFE;
2471                 close (fd);
2472                 MONO_EXIT_GC_SAFE;
2473                 
2474                 mono_w32error_set_last (ERROR_GEN_FAILURE);
2475                 return(INVALID_HANDLE_VALUE);
2476         }
2477         
2478         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
2479         
2480         return(handle);
2481 }
2482
2483 gboolean
2484 mono_w32file_close (gpointer handle)
2485 {
2486         gboolean res;
2487         MONO_ENTER_GC_SAFE;
2488         /* FIXME: we transition here and not in file_close, pipe_close,
2489          * console_close because w32handle_close is not coop aware yet, but it
2490          * calls back into w32file. */
2491         res = mono_w32handle_close (handle);
2492         MONO_EXIT_GC_SAFE;
2493         return res;
2494 }
2495
2496 gboolean mono_w32file_delete(const gunichar2 *name)
2497 {
2498         gchar *filename;
2499         gint retval;
2500         gboolean ret = FALSE;
2501 #if 0
2502         struct stat statbuf;
2503         FileShare *shareinfo;
2504 #endif
2505         
2506         if(name==NULL) {
2507                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2508
2509                 mono_w32error_set_last (ERROR_INVALID_NAME);
2510                 return(FALSE);
2511         }
2512
2513         filename=mono_unicode_to_external(name);
2514         if(filename==NULL) {
2515                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2516
2517                 mono_w32error_set_last (ERROR_INVALID_NAME);
2518                 return(FALSE);
2519         }
2520
2521 #if 0
2522         /* Check to make sure sharing allows us to open the file for
2523          * writing.  See bug 323389.
2524          *
2525          * Do the checks that don't need an open file descriptor, for
2526          * simplicity's sake.  If we really have to do the full checks
2527          * then we can implement that later.
2528          */
2529         if (_wapi_stat (filename, &statbuf) < 0) {
2530                 _wapi_set_last_path_error_from_errno (NULL, filename);
2531                 g_free (filename);
2532                 return(FALSE);
2533         }
2534         
2535         if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
2536                                &shareinfo) == FALSE) {
2537                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2538                 g_free (filename);
2539                 return FALSE;
2540         }
2541         if (shareinfo)
2542                 file_share_release (shareinfo);
2543 #endif
2544
2545         retval = _wapi_unlink (filename);
2546         
2547         if (retval == -1) {
2548                 /* On linux, calling unlink on an non-existing file in a read-only mount will fail with EROFS.
2549                  * The expected behavior is for this function to return FALSE and not trigger an exception.
2550                  * To work around this behavior, we stat the file on failure.
2551                  *
2552                  * This was supposedly fixed on kernel 3.0 [1] but we could reproduce it with Ubuntu 16.04 which has kernel 4.4.
2553                  * We can't remove this workaround until the early 2020's when most Android deviced will have a fix.
2554                  * [1] https://github.com/torvalds/linux/commit/50338b889dc504c69e0cb316ac92d1b9e51f3c8a
2555                  */
2556                 if (errno == EROFS) {
2557                         MonoIOStat stat;
2558                         if (mono_w32file_get_attributes_ex (name, &stat)) //The file exists, so must be due the RO file system
2559                                 errno = EROFS;
2560                 }
2561                 _wapi_set_last_path_error_from_errno (NULL, filename);
2562         } else {
2563                 ret = TRUE;
2564         }
2565
2566         g_free(filename);
2567
2568         return(ret);
2569 }
2570
2571 static gboolean
2572 MoveFile (gunichar2 *name, gunichar2 *dest_name)
2573 {
2574         gchar *utf8_name, *utf8_dest_name;
2575         gint result, errno_copy;
2576         struct stat stat_src, stat_dest;
2577         gboolean ret = FALSE;
2578         FileShare *shareinfo;
2579         
2580         if(name==NULL) {
2581                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2582
2583                 mono_w32error_set_last (ERROR_INVALID_NAME);
2584                 return(FALSE);
2585         }
2586
2587         utf8_name = mono_unicode_to_external (name);
2588         if (utf8_name == NULL) {
2589                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2590                 
2591                 mono_w32error_set_last (ERROR_INVALID_NAME);
2592                 return FALSE;
2593         }
2594         
2595         if(dest_name==NULL) {
2596                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2597
2598                 g_free (utf8_name);
2599                 mono_w32error_set_last (ERROR_INVALID_NAME);
2600                 return(FALSE);
2601         }
2602
2603         utf8_dest_name = mono_unicode_to_external (dest_name);
2604         if (utf8_dest_name == NULL) {
2605                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2606
2607                 g_free (utf8_name);
2608                 mono_w32error_set_last (ERROR_INVALID_NAME);
2609                 return FALSE;
2610         }
2611
2612         /*
2613          * In C# land we check for the existence of src, but not for dest.
2614          * We check it here and return the failure if dest exists and is not
2615          * the same file as src.
2616          */
2617         if (_wapi_stat (utf8_name, &stat_src) < 0) {
2618                 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
2619                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2620                         g_free (utf8_name);
2621                         g_free (utf8_dest_name);
2622                         return FALSE;
2623                 }
2624         }
2625         
2626         if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
2627                 if (stat_dest.st_dev != stat_src.st_dev ||
2628                     stat_dest.st_ino != stat_src.st_ino) {
2629                         g_free (utf8_name);
2630                         g_free (utf8_dest_name);
2631                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2632                         return FALSE;
2633                 }
2634         }
2635
2636         /* Check to make that we have delete sharing permission.
2637          * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
2638          *
2639          * Do the checks that don't need an open file descriptor, for
2640          * simplicity's sake.  If we really have to do the full checks
2641          * then we can implement that later.
2642          */
2643         if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
2644                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2645                 return FALSE;
2646         }
2647         if (shareinfo)
2648                 file_share_release (shareinfo);
2649
2650         result = _wapi_rename (utf8_name, utf8_dest_name);
2651         errno_copy = errno;
2652         
2653         if (result == -1) {
2654                 switch(errno_copy) {
2655                 case EEXIST:
2656                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2657                         break;
2658
2659                 case EXDEV:
2660                         /* Ignore here, it is dealt with below */
2661                         break;
2662
2663                 case ENOENT:
2664                         /* We already know src exists. Must be dest that doesn't exist. */
2665                         _wapi_set_last_path_error_from_errno (NULL, utf8_dest_name);
2666                         break;
2667
2668                 default:
2669                         _wapi_set_last_error_from_errno ();
2670                 }
2671         }
2672         
2673         g_free (utf8_name);
2674         g_free (utf8_dest_name);
2675
2676         if (result != 0 && errno_copy == EXDEV) {
2677                 gint32 copy_error;
2678
2679                 if (S_ISDIR (stat_src.st_mode)) {
2680                         mono_w32error_set_last (ERROR_NOT_SAME_DEVICE);
2681                         return FALSE;
2682                 }
2683                 /* Try a copy to the new location, and delete the source */
2684                 if (!mono_w32file_copy (name, dest_name, FALSE, &copy_error)) {
2685                         /* mono_w32file_copy will set the error */
2686                         return(FALSE);
2687                 }
2688                 
2689                 return(mono_w32file_delete (name));
2690         }
2691
2692         if (result == 0) {
2693                 ret = TRUE;
2694         }
2695
2696         return(ret);
2697 }
2698
2699 static gboolean
2700 write_file (gint src_fd, gint dest_fd, struct stat *st_src, gboolean report_errors)
2701 {
2702         gint remain, n;
2703         gchar *buf, *wbuf;
2704         gint buf_size = st_src->st_blksize;
2705         MonoThreadInfo *info = mono_thread_info_current ();
2706
2707         buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2708         buf = (gchar *) g_malloc (buf_size);
2709
2710         for (;;) {
2711                 MONO_ENTER_GC_SAFE;
2712                 remain = read (src_fd, buf, buf_size);
2713                 MONO_EXIT_GC_SAFE;
2714                 if (remain < 0) {
2715                         if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2716                                 continue;
2717
2718                         if (report_errors)
2719                                 _wapi_set_last_error_from_errno ();
2720
2721                         g_free (buf);
2722                         return FALSE;
2723                 }
2724                 if (remain == 0) {
2725                         break;
2726                 }
2727
2728                 wbuf = buf;
2729                 while (remain > 0) {
2730                         MONO_ENTER_GC_SAFE;
2731                         n = write (dest_fd, wbuf, remain);
2732                         MONO_EXIT_GC_SAFE;
2733                         if (n < 0) {
2734                                 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2735                                         continue;
2736
2737                                 if (report_errors)
2738                                         _wapi_set_last_error_from_errno ();
2739                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2740                                 g_free (buf);
2741                                 return FALSE;
2742                         }
2743
2744                         remain -= n;
2745                         wbuf += n;
2746                 }
2747         }
2748
2749         g_free (buf);
2750         return TRUE ;
2751 }
2752
2753 static gboolean
2754 CopyFile (const gunichar2 *name, const gunichar2 *dest_name, gboolean fail_if_exists)
2755 {
2756         gchar *utf8_src, *utf8_dest;
2757         gint src_fd, dest_fd;
2758         struct stat st, dest_st;
2759         struct utimbuf dest_time;
2760         gboolean ret = TRUE;
2761         gint ret_utime;
2762         gint syscall_res;
2763         
2764         if(name==NULL) {
2765                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2766
2767                 mono_w32error_set_last (ERROR_INVALID_NAME);
2768                 return(FALSE);
2769         }
2770         
2771         utf8_src = mono_unicode_to_external (name);
2772         if (utf8_src == NULL) {
2773                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2774                            __func__);
2775
2776                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2777                 return(FALSE);
2778         }
2779         
2780         if(dest_name==NULL) {
2781                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2782
2783                 g_free (utf8_src);
2784                 mono_w32error_set_last (ERROR_INVALID_NAME);
2785                 return(FALSE);
2786         }
2787         
2788         utf8_dest = mono_unicode_to_external (dest_name);
2789         if (utf8_dest == NULL) {
2790                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2791                            __func__);
2792
2793                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2794
2795                 g_free (utf8_src);
2796                 
2797                 return(FALSE);
2798         }
2799         
2800         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2801         if (src_fd < 0) {
2802                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2803                 
2804                 g_free (utf8_src);
2805                 g_free (utf8_dest);
2806                 
2807                 return(FALSE);
2808         }
2809
2810         MONO_ENTER_GC_SAFE;
2811         syscall_res = fstat (src_fd, &st);
2812         MONO_EXIT_GC_SAFE;
2813         if (syscall_res < 0) {
2814                 _wapi_set_last_error_from_errno ();
2815
2816                 g_free (utf8_src);
2817                 g_free (utf8_dest);
2818                 MONO_ENTER_GC_SAFE;
2819                 close (src_fd);
2820                 MONO_EXIT_GC_SAFE;
2821                 
2822                 return(FALSE);
2823         }
2824
2825         /* Before trying to open/create the dest, we need to report a 'file busy'
2826          * error if src and dest are actually the same file. We do the check here to take
2827          * advantage of the IOMAP capability */
2828         if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev && 
2829                         st.st_ino == dest_st.st_ino) {
2830
2831                 g_free (utf8_src);
2832                 g_free (utf8_dest);
2833                 MONO_ENTER_GC_SAFE;
2834                 close (src_fd);
2835                 MONO_EXIT_GC_SAFE;
2836
2837                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2838                 return (FALSE);
2839         }
2840         
2841         if (fail_if_exists) {
2842                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2843         } else {
2844                 /* FIXME: it kinda sucks that this code path potentially scans
2845                  * the directory twice due to the weird mono_w32error_set_last()
2846                  * behavior. */
2847                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2848                 if (dest_fd < 0) {
2849                         /* The file does not exist, try creating it */
2850                         dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2851                 } else {
2852                         /* Apparently this error is set if we
2853                          * overwrite the dest file
2854                          */
2855                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2856                 }
2857         }
2858         if (dest_fd < 0) {
2859                 _wapi_set_last_error_from_errno ();
2860
2861                 g_free (utf8_src);
2862                 g_free (utf8_dest);
2863                 MONO_ENTER_GC_SAFE;
2864                 close (src_fd);
2865                 MONO_EXIT_GC_SAFE;
2866
2867                 return(FALSE);
2868         }
2869
2870         if (!write_file (src_fd, dest_fd, &st, TRUE))
2871                 ret = FALSE;
2872
2873         close (src_fd);
2874         close (dest_fd);
2875         
2876         dest_time.modtime = st.st_mtime;
2877         dest_time.actime = st.st_atime;
2878         MONO_ENTER_GC_SAFE;
2879         ret_utime = utime (utf8_dest, &dest_time);
2880         MONO_EXIT_GC_SAFE;
2881         if (ret_utime == -1)
2882                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2883         
2884         g_free (utf8_src);
2885         g_free (utf8_dest);
2886
2887         return ret;
2888 }
2889
2890 static gchar*
2891 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2892 {
2893         gchar *utf8_ret;
2894
2895         if (arg == NULL) {
2896                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2897                 mono_w32error_set_last (ERROR_INVALID_NAME);
2898                 return NULL;
2899         }
2900
2901         utf8_ret = mono_unicode_to_external (arg);
2902         if (utf8_ret == NULL) {
2903                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2904                            __func__, arg_name);
2905                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2906                 return NULL;
2907         }
2908
2909         return utf8_ret;
2910 }
2911
2912 static gboolean
2913 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName, const gunichar2 *backupFileName, guint32 replaceFlags, gpointer exclude, gpointer reserved)
2914 {
2915         gint result, backup_fd = -1,replaced_fd = -1;
2916         gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2917         struct stat stBackup;
2918         gboolean ret = FALSE;
2919
2920         if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2921                 return FALSE;
2922         if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2923                 goto replace_cleanup;
2924         if (backupFileName != NULL) {
2925                 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2926                         goto replace_cleanup;
2927         }
2928
2929         if (utf8_backupFileName) {
2930                 // Open the backup file for read so we can restore the file if an error occurs.
2931                 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2932                 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2933                 if (result == -1)
2934                         goto replace_cleanup;
2935         }
2936
2937         result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2938         if (result == -1) {
2939                 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2940                 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2941                 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2942                         replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2943                                                   stBackup.st_mode);
2944                         
2945                         if (replaced_fd == -1)
2946                                 goto replace_cleanup;
2947
2948                         write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2949                 }
2950
2951                 goto replace_cleanup;
2952         }
2953
2954         ret = TRUE;
2955
2956 replace_cleanup:
2957         g_free (utf8_replacedFileName);
2958         g_free (utf8_replacementFileName);
2959         g_free (utf8_backupFileName);
2960         if (backup_fd != -1) {
2961                 MONO_ENTER_GC_SAFE;
2962                 close (backup_fd);
2963                 MONO_EXIT_GC_SAFE;
2964         }
2965         if (replaced_fd != -1) {
2966                 MONO_ENTER_GC_SAFE;
2967                 close (replaced_fd);
2968                 MONO_EXIT_GC_SAFE;
2969         }
2970         return ret;
2971 }
2972
2973 static MonoCoopMutex stdhandle_mutex;
2974
2975 static gpointer
2976 _wapi_stdhandle_create (gint fd, const gchar *name)
2977 {
2978         gpointer handle;
2979         gint flags;
2980         MonoW32HandleFile file_handle = {0};
2981
2982         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: creating standard handle type %s, fd %d", __func__, name, fd);
2983
2984         /* Check if fd is valid */
2985         do {
2986                 flags = fcntl(fd, F_GETFL);
2987         } while (flags == -1 && errno == EINTR);
2988
2989         if (flags == -1) {
2990                 /* Invalid fd.  Not really much point checking for EBADF
2991                  * specifically
2992                  */
2993                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fcntl error on fd %d: %s", __func__, fd, strerror(errno));
2994
2995                 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
2996                 return INVALID_HANDLE_VALUE;
2997         }
2998
2999         switch (flags & (O_RDONLY|O_WRONLY|O_RDWR)) {
3000         case O_RDONLY:
3001                 file_handle.fileaccess = GENERIC_READ;
3002                 break;
3003         case O_WRONLY:
3004                 file_handle.fileaccess = GENERIC_WRITE;
3005                 break;
3006         case O_RDWR:
3007                 file_handle.fileaccess = GENERIC_READ | GENERIC_WRITE;
3008                 break;
3009         default:
3010                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't figure out flags 0x%x", __func__, flags);
3011                 file_handle.fileaccess = 0;
3012                 break;
3013         }
3014
3015         file_handle.fd = fd;
3016         file_handle.filename = g_strdup(name);
3017         /* some default security attributes might be needed */
3018         file_handle.security_attributes = 0;
3019
3020         /* Apparently input handles can't be written to.  (I don't
3021          * know if output or error handles can't be read from.)
3022          */
3023         if (fd == 0)
3024                 file_handle.fileaccess &= ~GENERIC_WRITE;
3025
3026         file_handle.sharemode = 0;
3027         file_handle.attrs = 0;
3028
3029         handle = mono_w32handle_new_fd (MONO_W32HANDLE_CONSOLE, fd, &file_handle);
3030         if (handle == INVALID_HANDLE_VALUE) {
3031                 g_warning ("%s: error creating file handle", __func__);
3032                 mono_w32error_set_last (ERROR_GEN_FAILURE);
3033                 return INVALID_HANDLE_VALUE;
3034         }
3035
3036         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
3037
3038         return handle;
3039 }
3040
3041 enum {
3042         STD_INPUT_HANDLE  = -10,
3043         STD_OUTPUT_HANDLE = -11,
3044         STD_ERROR_HANDLE  = -12,
3045 };
3046
3047 static gpointer
3048 mono_w32file_get_std_handle (gint stdhandle)
3049 {
3050         MonoW32HandleFile *file_handle;
3051         gpointer handle;
3052         gint fd;
3053         const gchar *name;
3054         gboolean ok;
3055         
3056         switch(stdhandle) {
3057         case STD_INPUT_HANDLE:
3058                 fd = 0;
3059                 name = "<stdin>";
3060                 break;
3061
3062         case STD_OUTPUT_HANDLE:
3063                 fd = 1;
3064                 name = "<stdout>";
3065                 break;
3066
3067         case STD_ERROR_HANDLE:
3068                 fd = 2;
3069                 name = "<stderr>";
3070                 break;
3071
3072         default:
3073                 g_assert_not_reached ();
3074         }
3075
3076         handle = GINT_TO_POINTER (fd);
3077
3078         mono_coop_mutex_lock (&stdhandle_mutex);
3079
3080         ok = mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
3081                                   (gpointer *)&file_handle);
3082         if (ok == FALSE) {
3083                 /* Need to create this console handle */
3084                 handle = _wapi_stdhandle_create (fd, name);
3085                 
3086                 if (handle == INVALID_HANDLE_VALUE) {
3087                         mono_w32error_set_last (ERROR_NO_MORE_FILES);
3088                         goto done;
3089                 }
3090         }
3091         
3092   done:
3093         mono_coop_mutex_unlock (&stdhandle_mutex);
3094
3095         return(handle);
3096 }
3097
3098 gboolean
3099 mono_w32file_read (gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
3100 {
3101         MonoW32HandleType type;
3102
3103         type = mono_w32handle_get_type (handle);
3104         
3105         if(io_ops[type].readfile==NULL) {
3106                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3107                 return(FALSE);
3108         }
3109         
3110         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread));
3111 }
3112
3113 gboolean
3114 mono_w32file_write (gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
3115 {
3116         MonoW32HandleType type;
3117
3118         type = mono_w32handle_get_type (handle);
3119         
3120         if(io_ops[type].writefile==NULL) {
3121                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3122                 return(FALSE);
3123         }
3124         
3125         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten));
3126 }
3127
3128 gboolean
3129 mono_w32file_flush (gpointer handle)
3130 {
3131         MonoW32HandleType type;
3132
3133         type = mono_w32handle_get_type (handle);
3134         
3135         if(io_ops[type].flushfile==NULL) {
3136                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3137                 return(FALSE);
3138         }
3139         
3140         return(io_ops[type].flushfile (handle));
3141 }
3142
3143 gboolean
3144 mono_w32file_truncate (gpointer handle)
3145 {
3146         MonoW32HandleType type;
3147
3148         type = mono_w32handle_get_type (handle);
3149         
3150         if (io_ops[type].setendoffile == NULL) {
3151                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3152                 return(FALSE);
3153         }
3154         
3155         return(io_ops[type].setendoffile (handle));
3156 }
3157
3158 guint32
3159 mono_w32file_seek (gpointer handle, gint32 movedistance, gint32 *highmovedistance, guint32 method)
3160 {
3161         MonoW32HandleType type;
3162
3163         type = mono_w32handle_get_type (handle);
3164         
3165         if (io_ops[type].seek == NULL) {
3166                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3167                 return(INVALID_SET_FILE_POINTER);
3168         }
3169         
3170         return(io_ops[type].seek (handle, movedistance, highmovedistance,
3171                                   method));
3172 }
3173
3174 gint
3175 mono_w32file_get_type(gpointer handle)
3176 {
3177         MonoW32HandleType type;
3178
3179         type = mono_w32handle_get_type (handle);
3180         
3181         if (io_ops[type].getfiletype == NULL) {
3182                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3183                 return(FILE_TYPE_UNKNOWN);
3184         }
3185         
3186         return(io_ops[type].getfiletype ());
3187 }
3188
3189 static guint32
3190 GetFileSize(gpointer handle, guint32 *highsize)
3191 {
3192         MonoW32HandleType type;
3193
3194         type = mono_w32handle_get_type (handle);
3195         
3196         if (io_ops[type].getfilesize == NULL) {
3197                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3198                 return(INVALID_FILE_SIZE);
3199         }
3200         
3201         return(io_ops[type].getfilesize (handle, highsize));
3202 }
3203
3204 gboolean
3205 mono_w32file_get_times(gpointer handle, FILETIME *create_time, FILETIME *access_time, FILETIME *write_time)
3206 {
3207         MonoW32HandleType type;
3208
3209         type = mono_w32handle_get_type (handle);
3210         
3211         if (io_ops[type].getfiletime == NULL) {
3212                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3213                 return(FALSE);
3214         }
3215         
3216         return(io_ops[type].getfiletime (handle, create_time, access_time,
3217                                          write_time));
3218 }
3219
3220 gboolean
3221 mono_w32file_set_times(gpointer handle, const FILETIME *create_time, const FILETIME *access_time, const FILETIME *write_time)
3222 {
3223         MonoW32HandleType type;
3224
3225         type = mono_w32handle_get_type (handle);
3226         
3227         if (io_ops[type].setfiletime == NULL) {
3228                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3229                 return(FALSE);
3230         }
3231         
3232         return(io_ops[type].setfiletime (handle, create_time, access_time,
3233                                          write_time));
3234 }
3235
3236 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
3237  * January 1 1601 GMT
3238  */
3239
3240 #define TICKS_PER_MILLISECOND 10000L
3241 #define TICKS_PER_SECOND 10000000L
3242 #define TICKS_PER_MINUTE 600000000L
3243 #define TICKS_PER_HOUR 36000000000LL
3244 #define TICKS_PER_DAY 864000000000LL
3245
3246 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
3247
3248 static const guint16 mon_yday[2][13]={
3249         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
3250         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
3251 };
3252
3253 gboolean
3254 mono_w32file_filetime_to_systemtime(const FILETIME *file_time, SYSTEMTIME *system_time)
3255 {
3256         gint64 file_ticks, totaldays, rem, y;
3257         const guint16 *ip;
3258         
3259         if(system_time==NULL) {
3260                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
3261
3262                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3263                 return(FALSE);
3264         }
3265         
3266         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
3267                 file_time->dwLowDateTime;
3268         
3269         /* Really compares if file_ticks>=0x8000000000000000
3270          * (LLONG_MAX+1) but we're working with a signed value for the
3271          * year and day calculation to work later
3272          */
3273         if(file_ticks<0) {
3274                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
3275
3276                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3277                 return(FALSE);
3278         }
3279
3280         totaldays=(file_ticks / TICKS_PER_DAY);
3281         rem = file_ticks % TICKS_PER_DAY;
3282         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %" G_GINT64_FORMAT " rem: %" G_GINT64_FORMAT, __func__,
3283                   totaldays, rem);
3284
3285         system_time->wHour=rem/TICKS_PER_HOUR;
3286         rem %= TICKS_PER_HOUR;
3287         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %" G_GINT64_FORMAT,  __func__,
3288                   system_time->wHour, rem);
3289         
3290         system_time->wMinute = rem / TICKS_PER_MINUTE;
3291         rem %= TICKS_PER_MINUTE;
3292         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %" G_GINT64_FORMAT, __func__,
3293                   system_time->wMinute, rem);
3294         
3295         system_time->wSecond = rem / TICKS_PER_SECOND;
3296         rem %= TICKS_PER_SECOND;
3297         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %" G_GINT64_FORMAT, __func__,
3298                   system_time->wSecond, rem);
3299         
3300         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
3301         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
3302                   system_time->wMilliseconds);
3303
3304         /* January 1, 1601 was a Monday, according to Emacs calendar */
3305         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
3306         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
3307         
3308         /* This algorithm to find year and month given days from epoch
3309          * from glibc
3310          */
3311         y=1601;
3312         
3313 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
3314 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
3315
3316         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
3317                 /* Guess a corrected year, assuming 365 days per year */
3318                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
3319                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %" G_GINT64_FORMAT " yg: %" G_GINT64_FORMAT " y: %" G_GINT64_FORMAT, __func__,
3320                           totaldays, yg, y);
3321                 g_message("%s: LEAPS(yg): %li LEAPS(y): %li", __func__,
3322                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
3323                 
3324                 /* Adjust days and y to match the guessed year. */
3325                 totaldays -= ((yg - y) * 365
3326                               + LEAPS_THRU_END_OF (yg - 1)
3327                               - LEAPS_THRU_END_OF (y - 1));
3328                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %" G_GINT64_FORMAT,
3329                           __func__, totaldays);
3330                 y = yg;
3331                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %" G_GINT64_FORMAT, __func__, y);
3332         }
3333         
3334         system_time->wYear = y;
3335         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
3336
3337         ip = mon_yday[isleap(y)];
3338         
3339         for(y=11; totaldays < ip[y]; --y) {
3340                 continue;
3341         }
3342         totaldays-=ip[y];
3343         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %" G_GINT64_FORMAT, __func__, totaldays);
3344         
3345         system_time->wMonth = y + 1;
3346         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
3347
3348         system_time->wDay = totaldays + 1;
3349         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
3350         
3351         return(TRUE);
3352 }
3353
3354 gpointer
3355 mono_w32file_find_first (const gunichar2 *pattern, WIN32_FIND_DATA *find_data)
3356 {
3357         MonoW32HandleFind find_handle = {0};
3358         gpointer handle;
3359         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
3360         gint result;
3361         
3362         if (pattern == NULL) {
3363                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
3364
3365                 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
3366                 return(INVALID_HANDLE_VALUE);
3367         }
3368
3369         utf8_pattern = mono_unicode_to_external (pattern);
3370         if (utf8_pattern == NULL) {
3371                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3372                 
3373                 mono_w32error_set_last (ERROR_INVALID_NAME);
3374                 return(INVALID_HANDLE_VALUE);
3375         }
3376
3377         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
3378         
3379         /* Figure out which bit of the pattern is the directory */
3380         dir_part = _wapi_dirname (utf8_pattern);
3381         entry_part = _wapi_basename (utf8_pattern);
3382
3383 #if 0
3384         /* Don't do this check for now, it breaks if directories
3385          * really do have metachars in their names (see bug 58116).
3386          * FIXME: Figure out a better solution to keep some checks...
3387          */
3388         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
3389                 mono_w32error_set_last (ERROR_INVALID_NAME);
3390                 g_free (dir_part);
3391                 g_free (entry_part);
3392                 g_free (utf8_pattern);
3393                 return(INVALID_HANDLE_VALUE);
3394         }
3395 #endif
3396
3397         /* The pattern can specify a directory or a set of files.
3398          *
3399          * The pattern can have wildcard characters ? and *, but only
3400          * in the section after the last directory delimiter.  (Return
3401          * ERROR_INVALID_NAME if there are wildcards in earlier path
3402          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
3403          * means "match one character", "??" seems to mean "match one
3404          * or two characters", "???" seems to mean "match one, two or
3405          * three characters", etc.  Windows will also try and match
3406          * the mangled "short name" of files, so 8 character patterns
3407          * with wildcards will show some surprising results.
3408          *
3409          * All the written documentation I can find says that '?' 
3410          * should only match one character, and doesn't mention '??',
3411          * '???' etc.  I'm going to assume that the strict behaviour
3412          * (ie '???' means three and only three characters) is the
3413          * correct one, because that lets me use fnmatch(3) rather
3414          * than mess around with regexes.
3415          */
3416
3417         find_handle.namelist = NULL;
3418         result = _wapi_io_scandir (dir_part, entry_part,
3419                                    &find_handle.namelist);
3420         
3421         if (result == 0) {
3422                 /* No files, which windows seems to call
3423                  * FILE_NOT_FOUND
3424                  */
3425                 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
3426                 g_free (utf8_pattern);
3427                 g_free (entry_part);
3428                 g_free (dir_part);
3429                 return (INVALID_HANDLE_VALUE);
3430         }
3431         
3432         if (result < 0) {
3433                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
3434                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
3435                 g_free (utf8_pattern);
3436                 g_free (entry_part);
3437                 g_free (dir_part);
3438                 return (INVALID_HANDLE_VALUE);
3439         }
3440
3441         g_free (utf8_pattern);
3442         g_free (entry_part);
3443         
3444         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
3445
3446         find_handle.dir_part = dir_part;
3447         find_handle.num = result;
3448         find_handle.count = 0;
3449         
3450         handle = mono_w32handle_new (MONO_W32HANDLE_FIND, &find_handle);
3451         if (handle == INVALID_HANDLE_VALUE) {
3452                 g_warning ("%s: error creating find handle", __func__);
3453                 g_free (dir_part);
3454                 g_free (entry_part);
3455                 g_free (utf8_pattern);
3456                 mono_w32error_set_last (ERROR_GEN_FAILURE);
3457                 
3458                 return(INVALID_HANDLE_VALUE);
3459         }
3460
3461         if (handle != INVALID_HANDLE_VALUE &&
3462             !mono_w32file_find_next (handle, find_data)) {
3463                 mono_w32file_find_close (handle);
3464                 mono_w32error_set_last (ERROR_NO_MORE_FILES);
3465                 handle = INVALID_HANDLE_VALUE;
3466         }
3467
3468         return (handle);
3469 }
3470
3471 gboolean
3472 mono_w32file_find_next (gpointer handle, WIN32_FIND_DATA *find_data)
3473 {
3474         MonoW32HandleFind *find_handle;
3475         gboolean ok;
3476         struct stat buf, linkbuf;
3477         gint result;
3478         gchar *filename;
3479         gchar *utf8_filename, *utf8_basename;
3480         gunichar2 *utf16_basename;
3481         time_t create_time;
3482         glong bytes;
3483         gboolean ret = FALSE;
3484         
3485         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3486                                 (gpointer *)&find_handle);
3487         if(ok==FALSE) {
3488                 g_warning ("%s: error looking up find handle %p", __func__,
3489                            handle);
3490                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3491                 return(FALSE);
3492         }
3493
3494         mono_w32handle_lock_handle (handle);
3495         
3496 retry:
3497         if (find_handle->count >= find_handle->num) {
3498                 mono_w32error_set_last (ERROR_NO_MORE_FILES);
3499                 goto cleanup;
3500         }
3501
3502         /* stat next match */
3503
3504         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
3505
3506         result = _wapi_stat (filename, &buf);
3507         if (result == -1 && errno == ENOENT) {
3508                 /* Might be a dangling symlink */
3509                 result = _wapi_lstat (filename, &buf);
3510         }
3511         
3512         if (result != 0) {
3513                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
3514
3515                 g_free (filename);
3516                 goto retry;
3517         }
3518
3519         result = _wapi_lstat (filename, &linkbuf);
3520         if (result != 0) {
3521                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
3522
3523                 g_free (filename);
3524                 goto retry;
3525         }
3526
3527         utf8_filename = mono_utf8_from_external (filename);
3528         if (utf8_filename == NULL) {
3529                 /* We couldn't turn this filename into utf8 (eg the
3530                  * encoding of the name wasn't convertible), so just
3531                  * ignore it.
3532                  */
3533                 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
3534                 
3535                 g_free (filename);
3536                 goto retry;
3537         }
3538         g_free (filename);
3539         
3540         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
3541         
3542         /* fill data block */
3543
3544         if (buf.st_mtime < buf.st_ctime)
3545                 create_time = buf.st_mtime;
3546         else
3547                 create_time = buf.st_ctime;
3548         
3549         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3550
3551         time_t_to_filetime (create_time, &find_data->ftCreationTime);
3552         time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3553         time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3554
3555         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3556                 find_data->nFileSizeHigh = 0;
3557                 find_data->nFileSizeLow = 0;
3558         } else {
3559                 find_data->nFileSizeHigh = buf.st_size >> 32;
3560                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3561         }
3562
3563         find_data->dwReserved0 = 0;
3564         find_data->dwReserved1 = 0;
3565
3566         utf8_basename = _wapi_basename (utf8_filename);
3567         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3568                                           NULL);
3569         if(utf16_basename==NULL) {
3570                 g_free (utf8_basename);
3571                 g_free (utf8_filename);
3572                 goto retry;
3573         }
3574         ret = TRUE;
3575         
3576         /* utf16 is 2 * utf8 */
3577         bytes *= 2;
3578
3579         memset (find_data->cFileName, '\0', (MAX_PATH*2));
3580
3581         /* Truncating a utf16 string like this might leave the last
3582          * gchar incomplete
3583          */
3584         memcpy (find_data->cFileName, utf16_basename,
3585                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3586
3587         find_data->cAlternateFileName [0] = 0;  /* not used */
3588
3589         g_free (utf8_basename);
3590         g_free (utf8_filename);
3591         g_free (utf16_basename);
3592
3593 cleanup:
3594         mono_w32handle_unlock_handle (handle);
3595         
3596         return(ret);
3597 }
3598
3599 gboolean
3600 mono_w32file_find_close (gpointer handle)
3601 {
3602         MonoW32HandleFind *find_handle;
3603         gboolean ok;
3604
3605         if (handle == NULL) {
3606                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3607                 return(FALSE);
3608         }
3609         
3610         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3611                                 (gpointer *)&find_handle);
3612         if(ok==FALSE) {
3613                 g_warning ("%s: error looking up find handle %p", __func__,
3614                            handle);
3615                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3616                 return(FALSE);
3617         }
3618
3619         mono_w32handle_lock_handle (handle);
3620         
3621         g_strfreev (find_handle->namelist);
3622         g_free (find_handle->dir_part);
3623
3624         mono_w32handle_unlock_handle (handle);
3625         
3626         MONO_ENTER_GC_SAFE;
3627         mono_w32handle_unref (handle);
3628         MONO_EXIT_GC_SAFE;
3629         
3630         return(TRUE);
3631 }
3632
3633 gboolean
3634 mono_w32file_create_directory (const gunichar2 *name)
3635 {
3636         gchar *utf8_name;
3637         gint result;
3638         
3639         if (name == NULL) {
3640                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3641
3642                 mono_w32error_set_last (ERROR_INVALID_NAME);
3643                 return(FALSE);
3644         }
3645         
3646         utf8_name = mono_unicode_to_external (name);
3647         if (utf8_name == NULL) {
3648                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3649         
3650                 mono_w32error_set_last (ERROR_INVALID_NAME);
3651                 return FALSE;
3652         }
3653
3654         result = _wapi_mkdir (utf8_name, 0777);
3655
3656         if (result == 0) {
3657                 g_free (utf8_name);
3658                 return TRUE;
3659         }
3660
3661         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3662         g_free (utf8_name);
3663         return FALSE;
3664 }
3665
3666 gboolean
3667 mono_w32file_remove_directory (const gunichar2 *name)
3668 {
3669         gchar *utf8_name;
3670         gint result;
3671         
3672         if (name == NULL) {
3673                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3674
3675                 mono_w32error_set_last (ERROR_INVALID_NAME);
3676                 return(FALSE);
3677         }
3678
3679         utf8_name = mono_unicode_to_external (name);
3680         if (utf8_name == NULL) {
3681                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3682                 
3683                 mono_w32error_set_last (ERROR_INVALID_NAME);
3684                 return FALSE;
3685         }
3686
3687         result = _wapi_rmdir (utf8_name);
3688         if (result == -1) {
3689                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3690                 g_free (utf8_name);
3691                 
3692                 return(FALSE);
3693         }
3694         g_free (utf8_name);
3695
3696         return(TRUE);
3697 }
3698
3699 guint32
3700 mono_w32file_get_attributes (const gunichar2 *name)
3701 {
3702         gchar *utf8_name;
3703         struct stat buf, linkbuf;
3704         gint result;
3705         guint32 ret;
3706         
3707         if (name == NULL) {
3708                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3709
3710                 mono_w32error_set_last (ERROR_INVALID_NAME);
3711                 return(FALSE);
3712         }
3713         
3714         utf8_name = mono_unicode_to_external (name);
3715         if (utf8_name == NULL) {
3716                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3717
3718                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3719                 return (INVALID_FILE_ATTRIBUTES);
3720         }
3721
3722         result = _wapi_stat (utf8_name, &buf);
3723         if (result == -1 && (errno == ENOENT || errno == ELOOP)) {
3724                 /* Might be a dangling symlink... */
3725                 result = _wapi_lstat (utf8_name, &buf);
3726         }
3727
3728         if (result != 0) {
3729                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3730                 g_free (utf8_name);
3731                 return (INVALID_FILE_ATTRIBUTES);
3732         }
3733
3734         result = _wapi_lstat (utf8_name, &linkbuf);
3735         if (result != 0) {
3736                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3737                 g_free (utf8_name);
3738                 return (INVALID_FILE_ATTRIBUTES);
3739         }
3740         
3741         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3742         
3743         g_free (utf8_name);
3744
3745         return(ret);
3746 }
3747
3748 gboolean
3749 mono_w32file_get_attributes_ex (const gunichar2 *name, MonoIOStat *stat)
3750 {
3751         gchar *utf8_name;
3752
3753         struct stat buf, linkbuf;
3754         gint result;
3755         
3756         if (name == NULL) {
3757                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3758
3759                 mono_w32error_set_last (ERROR_INVALID_NAME);
3760                 return(FALSE);
3761         }
3762
3763         utf8_name = mono_unicode_to_external (name);
3764         if (utf8_name == NULL) {
3765                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3766
3767                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3768                 return FALSE;
3769         }
3770
3771         result = _wapi_stat (utf8_name, &buf);
3772         if (result == -1 && errno == ENOENT) {
3773                 /* Might be a dangling symlink... */
3774                 result = _wapi_lstat (utf8_name, &buf);
3775         }
3776         
3777         if (result != 0) {
3778                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3779                 g_free (utf8_name);
3780                 return FALSE;
3781         }
3782
3783         result = _wapi_lstat (utf8_name, &linkbuf);
3784         if (result != 0) {
3785                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3786                 g_free (utf8_name);
3787                 return(FALSE);
3788         }
3789
3790         /* fill stat block */
3791
3792         stat->attributes = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3793         stat->creation_time = (((guint64) (buf.st_mtime < buf.st_ctime ? buf.st_mtime : buf.st_ctime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3794         stat->last_access_time = (((guint64) (buf.st_atime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3795         stat->last_write_time = (((guint64) (buf.st_mtime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3796         stat->length = (stat->attributes & FILE_ATTRIBUTE_DIRECTORY) ? 0 : buf.st_size;
3797
3798         g_free (utf8_name);
3799         return TRUE;
3800 }
3801
3802 gboolean
3803 mono_w32file_set_attributes (const gunichar2 *name, guint32 attrs)
3804 {
3805         /* FIXME: think of something clever to do on unix */
3806         gchar *utf8_name;
3807         struct stat buf;
3808         gint result;
3809
3810         /*
3811          * Currently we only handle one *internal* case, with a value that is
3812          * not standard: 0x80000000, which means `set executable bit'
3813          */
3814         
3815         if (name == NULL) {
3816                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3817
3818                 mono_w32error_set_last (ERROR_INVALID_NAME);
3819                 return(FALSE);
3820         }
3821
3822         utf8_name = mono_unicode_to_external (name);
3823         if (utf8_name == NULL) {
3824                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3825
3826                 mono_w32error_set_last (ERROR_INVALID_NAME);
3827                 return FALSE;
3828         }
3829
3830         result = _wapi_stat (utf8_name, &buf);
3831         if (result == -1 && errno == ENOENT) {
3832                 /* Might be a dangling symlink... */
3833                 result = _wapi_lstat (utf8_name, &buf);
3834         }
3835
3836         if (result != 0) {
3837                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3838                 g_free (utf8_name);
3839                 return FALSE;
3840         }
3841
3842         /* Contrary to the documentation, ms allows NORMAL to be
3843          * specified along with other attributes, so dont bother to
3844          * catch that case here.
3845          */
3846         if (attrs & FILE_ATTRIBUTE_READONLY) {
3847                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3848         } else {
3849                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3850         }
3851
3852         /* Ignore the other attributes for now */
3853
3854         if (attrs & 0x80000000){
3855                 mode_t exec_mask = 0;
3856
3857                 if ((buf.st_mode & S_IRUSR) != 0)
3858                         exec_mask |= S_IXUSR;
3859
3860                 if ((buf.st_mode & S_IRGRP) != 0)
3861                         exec_mask |= S_IXGRP;
3862
3863                 if ((buf.st_mode & S_IROTH) != 0)
3864                         exec_mask |= S_IXOTH;
3865
3866                 MONO_ENTER_GC_SAFE;
3867                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3868                 MONO_EXIT_GC_SAFE;
3869         }
3870         /* Don't bother to reset executable (might need to change this
3871          * policy)
3872          */
3873         
3874         g_free (utf8_name);
3875
3876         return(TRUE);
3877 }
3878
3879 guint32
3880 mono_w32file_get_cwd (guint32 length, gunichar2 *buffer)
3881 {
3882         gunichar2 *utf16_path;
3883         glong count;
3884         gsize bytes;
3885
3886         if (getcwd ((gchar*)buffer, length) == NULL) {
3887                 if (errno == ERANGE) { /*buffer length is not big enough */ 
3888                         gchar *path = g_get_current_dir (); /*FIXME g_get_current_dir doesn't work with broken paths and calling it just to know the path length is silly*/
3889                         if (path == NULL)
3890                                 return 0;
3891                         utf16_path = mono_unicode_from_external (path, &bytes);
3892                         g_free (utf16_path);
3893                         g_free (path);
3894                         return (bytes/2)+1;
3895                 }
3896                 _wapi_set_last_error_from_errno ();
3897                 return 0;
3898         }
3899
3900         utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3901         count = (bytes/2)+1;
3902         g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3903
3904         /* Add the terminator */
3905         memset (buffer, '\0', bytes+2);
3906         memcpy (buffer, utf16_path, bytes);
3907         
3908         g_free (utf16_path);
3909
3910         return count;
3911 }
3912
3913 gboolean
3914 mono_w32file_set_cwd (const gunichar2 *path)
3915 {
3916         gchar *utf8_path;
3917         gboolean result;
3918
3919         if (path == NULL) {
3920                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3921                 return(FALSE);
3922         }
3923         
3924         utf8_path = mono_unicode_to_external (path);
3925         if (_wapi_chdir (utf8_path) != 0) {
3926                 _wapi_set_last_error_from_errno ();
3927                 result = FALSE;
3928         }
3929         else
3930                 result = TRUE;
3931
3932         g_free (utf8_path);
3933         return result;
3934 }
3935
3936 gboolean
3937 mono_w32file_create_pipe (gpointer *readpipe, gpointer *writepipe, guint32 size)
3938 {
3939         MonoW32HandleFile pipe_read_handle = {0};
3940         MonoW32HandleFile pipe_write_handle = {0};
3941         gpointer read_handle;
3942         gpointer write_handle;
3943         gint filedes[2];
3944         gint ret;
3945         
3946         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3947
3948         MONO_ENTER_GC_SAFE;
3949         ret=pipe (filedes);
3950         MONO_EXIT_GC_SAFE;
3951         if(ret==-1) {
3952                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3953                            strerror (errno));
3954                 
3955                 _wapi_set_last_error_from_errno ();
3956                 return(FALSE);
3957         }
3958
3959         if (filedes[0] >= mono_w32handle_fd_reserve ||
3960             filedes[1] >= mono_w32handle_fd_reserve) {
3961                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3962
3963                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
3964                 
3965                 MONO_ENTER_GC_SAFE;
3966                 close (filedes[0]);
3967                 close (filedes[1]);
3968                 MONO_EXIT_GC_SAFE;
3969                 
3970                 return(FALSE);
3971         }
3972         
3973         /* filedes[0] is open for reading, filedes[1] for writing */
3974
3975         pipe_read_handle.fd = filedes [0];
3976         pipe_read_handle.fileaccess = GENERIC_READ;
3977         read_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[0],
3978                                            &pipe_read_handle);
3979         if (read_handle == INVALID_HANDLE_VALUE) {
3980                 g_warning ("%s: error creating pipe read handle", __func__);
3981                 MONO_ENTER_GC_SAFE;
3982                 close (filedes[0]);
3983                 close (filedes[1]);
3984                 MONO_EXIT_GC_SAFE;
3985                 mono_w32error_set_last (ERROR_GEN_FAILURE);
3986                 
3987                 return(FALSE);
3988         }
3989         
3990         pipe_write_handle.fd = filedes [1];
3991         pipe_write_handle.fileaccess = GENERIC_WRITE;
3992         write_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[1],
3993                                             &pipe_write_handle);
3994         if (write_handle == INVALID_HANDLE_VALUE) {
3995                 g_warning ("%s: error creating pipe write handle", __func__);
3996
3997                 MONO_ENTER_GC_SAFE;
3998                 mono_w32handle_unref (read_handle);
3999                 
4000                 close (filedes[0]);
4001                 close (filedes[1]);
4002                 MONO_EXIT_GC_SAFE;
4003                 mono_w32error_set_last (ERROR_GEN_FAILURE);
4004                 
4005                 return(FALSE);
4006         }
4007         
4008         *readpipe = read_handle;
4009         *writepipe = write_handle;
4010
4011         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
4012                    __func__, read_handle, write_handle);
4013
4014         return(TRUE);
4015 }
4016
4017 #ifdef HAVE_GETFSSTAT
4018 /* Darwin has getfsstat */
4019 gint32
4020 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4021 {
4022         struct statfs *stats;
4023         gint size, n, i;
4024         gunichar2 *dir;
4025         glong length, total = 0;
4026         gint syscall_res;
4027
4028         MONO_ENTER_GC_SAFE;
4029         n = getfsstat (NULL, 0, MNT_NOWAIT);
4030         MONO_EXIT_GC_SAFE;
4031         if (n == -1)
4032                 return 0;
4033         size = n * sizeof (struct statfs);
4034         stats = (struct statfs *) g_malloc (size);
4035         if (stats == NULL)
4036                 return 0;
4037         MONO_ENTER_GC_SAFE;
4038         syscall_res = getfsstat (stats, size, MNT_NOWAIT);
4039         MONO_EXIT_GC_SAFE;
4040         if (syscall_res == -1){
4041                 g_free (stats);
4042                 return 0;
4043         }
4044         for (i = 0; i < n; i++){
4045                 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
4046                 if (total + length < len){
4047                         memcpy (buf + total, dir, sizeof (gunichar2) * length);
4048                         buf [total+length] = 0;
4049                 } 
4050                 g_free (dir);
4051                 total += length + 1;
4052         }
4053         if (total < len)
4054                 buf [total] = 0;
4055         total++;
4056         g_free (stats);
4057         return total;
4058 }
4059 #else
4060 /* In-place octal sequence replacement */
4061 static void
4062 unescape_octal (gchar *str)
4063 {
4064         gchar *rptr;
4065         gchar *wptr;
4066
4067         if (str == NULL)
4068                 return;
4069
4070         rptr = wptr = str;
4071         while (*rptr != '\0') {
4072                 if (*rptr == '\\') {
4073                         gchar c;
4074                         rptr++;
4075                         c = (*(rptr++) - '0') << 6;
4076                         c += (*(rptr++) - '0') << 3;
4077                         c += *(rptr++) - '0';
4078                         *wptr++ = c;
4079                 } else if (wptr != rptr) {
4080                         *wptr++ = *rptr++;
4081                 } else {
4082                         rptr++; wptr++;
4083                 }
4084         }
4085         *wptr = '\0';
4086 }
4087 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
4088
4089 #if __linux__
4090 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
4091 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
4092 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
4093
4094 typedef struct 
4095 {
4096         glong total;
4097         guint32 buffer_index;
4098         guint32 mountpoint_index;
4099         guint32 field_number;
4100         guint32 allocated_size;
4101         guint32 fsname_index;
4102         guint32 fstype_index;
4103         gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
4104         gchar *mountpoint_allocated;
4105         gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
4106         gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
4107         gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
4108         ssize_t nbytes;
4109         gchar delimiter;
4110         gboolean check_mount_source;
4111 } LinuxMountInfoParseState;
4112
4113 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4114 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4115 static void append_to_mountpoint (LinuxMountInfoParseState *state);
4116 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4117
4118 gint32
4119 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4120 {
4121         gint fd;
4122         gint32 ret = 0;
4123         LinuxMountInfoParseState state;
4124         gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
4125
4126         memset (buf, 0, len * sizeof (gunichar2));
4127         MONO_ENTER_GC_SAFE;
4128         fd = open ("/proc/self/mountinfo", O_RDONLY);
4129         MONO_EXIT_GC_SAFE;
4130         if (fd != -1)
4131                 parser = GetLogicalDriveStrings_MountInfo;
4132         else {
4133                 MONO_ENTER_GC_SAFE;
4134                 fd = open ("/proc/mounts", O_RDONLY);
4135                 MONO_EXIT_GC_SAFE;
4136                 if (fd != -1)
4137                         parser = GetLogicalDriveStrings_Mounts;
4138         }
4139
4140         if (!parser) {
4141                 ret = GetLogicalDriveStrings_Mtab (len, buf);
4142                 goto done_and_out;
4143         }
4144
4145         memset (&state, 0, sizeof (LinuxMountInfoParseState));
4146         state.field_number = 1;
4147         state.delimiter = ' ';
4148
4149         while (1) {
4150                 MONO_ENTER_GC_SAFE;
4151                 state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER);
4152                 MONO_EXIT_GC_SAFE;
4153                 if (!(state.nbytes > 0))
4154                         break;
4155                 state.buffer_index = 0;
4156
4157                 while ((*parser)(len, buf, &state)) {
4158                         if (state.buffer [state.buffer_index] == '\n') {
4159                                 gboolean quit = add_drive_string (len, buf, &state);
4160                                 state.field_number = 1;
4161                                 state.buffer_index++;
4162                                 if (state.mountpoint_allocated) {
4163                                         g_free (state.mountpoint_allocated);
4164                                         state.mountpoint_allocated = NULL;
4165                                 }
4166                                 if (quit) {
4167                                         ret = state.total;
4168                                         goto done_and_out;
4169                                 }
4170                         }
4171                 }
4172         };
4173         ret = state.total;
4174
4175   done_and_out:
4176         if (fd != -1) {
4177                 MONO_ENTER_GC_SAFE;
4178                 close (fd);
4179                 MONO_EXIT_GC_SAFE;
4180         }
4181         return ret;
4182 }
4183
4184 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4185 {
4186         gchar *ptr;
4187
4188         if (state->field_number == 1)
4189                 state->check_mount_source = TRUE;
4190
4191         while (state->buffer_index < (guint32)state->nbytes) {
4192                 if (state->buffer [state->buffer_index] == state->delimiter) {
4193                         state->field_number++;
4194                         switch (state->field_number) {
4195                                 case 2:
4196                                         state->mountpoint_index = 0;
4197                                         break;
4198
4199                                 case 3:
4200                                         if (state->mountpoint_allocated)
4201                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
4202                                         else
4203                                                 state->mountpoint [state->mountpoint_index] = 0;
4204                                         break;
4205
4206                                 default:
4207                                         ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
4208                                         if (ptr)
4209                                                 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
4210                                         else
4211                                                 state->buffer_index = state->nbytes;
4212                                         return TRUE;
4213                         }
4214                         state->buffer_index++;
4215                         continue;
4216                 } else if (state->buffer [state->buffer_index] == '\n')
4217                         return TRUE;
4218
4219                 switch (state->field_number) {
4220                         case 1:
4221                                 if (state->check_mount_source) {
4222                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
4223                                                 /* We can ignore the rest, it's a device
4224                                                  * path */
4225                                                 state->check_mount_source = FALSE;
4226                                                 state->fsname [state->fsname_index++] = '/';
4227                                                 break;
4228                                         }
4229                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4230                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
4231                                 }
4232                                 break;
4233
4234                         case 2:
4235                                 append_to_mountpoint (state);
4236                                 break;
4237
4238                         case 3:
4239                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4240                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
4241                                 break;
4242                 }
4243
4244                 state->buffer_index++;
4245         }
4246
4247         return FALSE;
4248 }
4249
4250 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4251 {
4252         while (state->buffer_index < (guint32)state->nbytes) {
4253                 if (state->buffer [state->buffer_index] == state->delimiter) {
4254                         state->field_number++;
4255                         switch (state->field_number) {
4256                                 case 5:
4257                                         state->mountpoint_index = 0;
4258                                         break;
4259
4260                                 case 6:
4261                                         if (state->mountpoint_allocated)
4262                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
4263                                         else
4264                                                 state->mountpoint [state->mountpoint_index] = 0;
4265                                         break;
4266
4267                                 case 7:
4268                                         state->delimiter = '-';
4269                                         break;
4270
4271                                 case 8:
4272                                         state->delimiter = ' ';
4273                                         break;
4274
4275                                 case 10:
4276                                         state->check_mount_source = TRUE;
4277                                         break;
4278                         }
4279                         state->buffer_index++;
4280                         continue;
4281                 } else if (state->buffer [state->buffer_index] == '\n')
4282                         return TRUE;
4283
4284                 switch (state->field_number) {
4285                         case 5:
4286                                 append_to_mountpoint (state);
4287                                 break;
4288
4289                         case 9:
4290                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4291                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
4292                                 break;
4293
4294                         case 10:
4295                                 if (state->check_mount_source) {
4296                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
4297                                                 /* We can ignore the rest, it's a device
4298                                                  * path */
4299                                                 state->check_mount_source = FALSE;
4300                                                 state->fsname [state->fsname_index++] = '/';
4301                                                 break;
4302                                         }
4303                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4304                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
4305                                 }
4306                                 break;
4307                 }
4308
4309                 state->buffer_index++;
4310         }
4311
4312         return FALSE;
4313 }
4314
4315 static void
4316 append_to_mountpoint (LinuxMountInfoParseState *state)
4317 {
4318         gchar ch = state->buffer [state->buffer_index];
4319         if (state->mountpoint_allocated) {
4320                 if (state->mountpoint_index >= state->allocated_size) {
4321                         guint32 newsize = (state->allocated_size << 1) + 1;
4322                         gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
4323
4324                         memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
4325                         g_free (state->mountpoint_allocated);
4326                         state->mountpoint_allocated = newbuf;
4327                         state->allocated_size = newsize;
4328                 }
4329                 state->mountpoint_allocated [state->mountpoint_index++] = ch;
4330         } else {
4331                 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
4332                         state->allocated_size = (state->mountpoint_index << 1) + 1;
4333                         state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
4334                         memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
4335                         state->mountpoint_allocated [state->mountpoint_index++] = ch;
4336                 } else
4337                         state->mountpoint [state->mountpoint_index++] = ch;
4338         }
4339 }
4340
4341 static gboolean
4342 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4343 {
4344         gboolean quit = FALSE;
4345         gboolean ignore_entry;
4346
4347         if (state->fsname_index == 1 && state->fsname [0] == '/')
4348                 ignore_entry = FALSE;
4349         else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
4350                 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
4351                 /* Don't ignore overlayfs and aufs - these might be used on Docker
4352                  * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
4353                 ignore_entry = FALSE;
4354         } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
4355                 ignore_entry = TRUE;
4356         } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
4357                 /* Ignore GNOME's gvfs */
4358                 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
4359                         ignore_entry = TRUE;
4360                 else
4361                         ignore_entry = FALSE;
4362         } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
4363                 ignore_entry = FALSE;
4364         else
4365                 ignore_entry = TRUE;
4366
4367         if (!ignore_entry) {
4368                 gunichar2 *dir;
4369                 glong length;
4370                 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
4371
4372                 unescape_octal (mountpoint);
4373                 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
4374                 if (state->total + length + 1 > len) {
4375                         quit = TRUE;
4376                         state->total = len * 2;
4377                 } else {
4378                         length++;
4379                         memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
4380                         state->total += length;
4381                 }
4382                 g_free (dir);
4383         }
4384         state->fsname_index = 0;
4385         state->fstype_index = 0;
4386
4387         return quit;
4388 }
4389 #else
4390 gint32
4391 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4392 {
4393         return GetLogicalDriveStrings_Mtab (len, buf);
4394 }
4395 #endif
4396 static gint32
4397 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
4398 {
4399         FILE *fp;
4400         gunichar2 *ptr, *dir;
4401         glong length, total = 0;
4402         gchar buffer [512];
4403         gchar **splitted;
4404
4405         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
4406         buf [0] = '/';
4407         buf [1] = 0;
4408         buf [2] = 0;
4409
4410         /* Sigh, mntent and friends don't work well.
4411          * It stops on the first line that doesn't begin with a '/'.
4412          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
4413         MONO_ENTER_GC_SAFE;
4414         fp = fopen ("/etc/mtab", "rt");
4415         MONO_EXIT_GC_SAFE;
4416         if (fp == NULL) {
4417                 MONO_ENTER_GC_SAFE;
4418                 fp = fopen ("/etc/mnttab", "rt");
4419                 MONO_EXIT_GC_SAFE;
4420                 if (fp == NULL)
4421                         return 1;
4422         }
4423
4424         ptr = buf;
4425         while (1) {
4426                 gchar *fgets_res;
4427                 MONO_ENTER_GC_SAFE;
4428                 fgets_res = fgets (buffer, 512, fp);
4429                 MONO_EXIT_GC_SAFE;
4430                 if (!fgets_res)
4431                         break;
4432                 if (*buffer != '/')
4433                         continue;
4434
4435                 splitted = g_strsplit (buffer, " ", 0);
4436                 if (!*splitted || !*(splitted + 1)) {
4437                         g_strfreev (splitted);
4438                         continue;
4439                 }
4440
4441                 unescape_octal (*(splitted + 1));
4442                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
4443                 g_strfreev (splitted);
4444                 if (total + length + 1 > len) {
4445                         MONO_ENTER_GC_SAFE;
4446                         fclose (fp);
4447                         MONO_EXIT_GC_SAFE;
4448                         g_free (dir);
4449                         return len * 2; /* guess */
4450                 }
4451
4452                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
4453                 g_free (dir);
4454                 total += length + 1;
4455         }
4456
4457         MONO_ENTER_GC_SAFE;
4458         fclose (fp);
4459         MONO_EXIT_GC_SAFE;
4460         return total;
4461 /* Commented out, does not work with my mtab!!! - Gonz */
4462 #ifdef NOTENABLED /* HAVE_MNTENT_H */
4463 {
4464         FILE *fp;
4465         struct mntent *mnt;
4466         gunichar2 *ptr, *dir;
4467         glong len, total = 0;
4468         
4469
4470         MONO_ENTER_GC_SAFE;
4471         fp = setmntent ("/etc/mtab", "rt");
4472         MONO_EXIT_GC_SAFE;
4473         if (fp == NULL) {
4474                 MONO_ENTER_GC_SAFE;
4475                 fp = setmntent ("/etc/mnttab", "rt");
4476                 MONO_EXIT_GC_SAFE;
4477                 if (fp == NULL)
4478                         return;
4479         }
4480
4481         ptr = buf;
4482         while (1) {
4483                 MONO_ENTER_GC_SAFE;
4484                 mnt = getmntent (fp);
4485                 MONO_EXIT_GC_SAFE;
4486                 if (mnt == NULL)
4487                         break;
4488                 g_print ("GOT %s\n", mnt->mnt_dir);
4489                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4490                 if (total + len + 1 > len) {
4491                         MONO_ENTER_GC_SAFE;
4492                         endmntent (fp);
4493                         MONO_EXIT_GC_SAFE;
4494                         return len * 2; /* guess */
4495                 }
4496
4497                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4498                 g_free (dir);
4499                 total += len + 1;
4500         }
4501
4502         MONO_ENTER_GC_SAFE;
4503         endmntent (fp);
4504         MONO_EXIT_GC_SAFE;
4505         return total;
4506 }
4507 #endif
4508 }
4509 #endif
4510
4511 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4512 gboolean
4513 mono_w32file_get_disk_free_space (const gunichar2 *path_name, guint64 *free_bytes_avail, guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes)
4514 {
4515 #ifdef HAVE_STATVFS
4516         struct statvfs fsstat;
4517 #elif defined(HAVE_STATFS)
4518         struct statfs fsstat;
4519 #endif
4520         gboolean isreadonly;
4521         gchar *utf8_path_name;
4522         gint ret;
4523         unsigned long block_size;
4524
4525         if (path_name == NULL) {
4526                 utf8_path_name = g_strdup (g_get_current_dir());
4527                 if (utf8_path_name == NULL) {
4528                         mono_w32error_set_last (ERROR_DIRECTORY);
4529                         return(FALSE);
4530                 }
4531         }
4532         else {
4533                 utf8_path_name = mono_unicode_to_external (path_name);
4534                 if (utf8_path_name == NULL) {
4535                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4536
4537                         mono_w32error_set_last (ERROR_INVALID_NAME);
4538                         return(FALSE);
4539                 }
4540         }
4541
4542         do {
4543 #ifdef HAVE_STATVFS
4544                 MONO_ENTER_GC_SAFE;
4545                 ret = statvfs (utf8_path_name, &fsstat);
4546                 MONO_EXIT_GC_SAFE;
4547                 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4548                 block_size = fsstat.f_frsize;
4549 #elif defined(HAVE_STATFS)
4550                 MONO_ENTER_GC_SAFE;
4551                 ret = statfs (utf8_path_name, &fsstat);
4552                 MONO_EXIT_GC_SAFE;
4553 #if defined (MNT_RDONLY)
4554                 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4555 #elif defined (MS_RDONLY)
4556                 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4557 #endif
4558                 block_size = fsstat.f_bsize;
4559 #endif
4560         } while(ret == -1 && errno == EINTR);
4561
4562         g_free(utf8_path_name);
4563
4564         if (ret == -1) {
4565                 _wapi_set_last_error_from_errno ();
4566                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4567                 return(FALSE);
4568         }
4569
4570         /* total number of free bytes for non-root */
4571         if (free_bytes_avail != NULL) {
4572                 if (isreadonly) {
4573                         *free_bytes_avail = 0;
4574                 }
4575                 else {
4576                         *free_bytes_avail = block_size * (guint64)fsstat.f_bavail;
4577                 }
4578         }
4579
4580         /* total number of bytes available for non-root */
4581         if (total_number_of_bytes != NULL) {
4582                 *total_number_of_bytes = block_size * (guint64)fsstat.f_blocks;
4583         }
4584
4585         /* total number of bytes available for root */
4586         if (total_number_of_free_bytes != NULL) {
4587                 if (isreadonly) {
4588                         *total_number_of_free_bytes = 0;
4589                 }
4590                 else {
4591                         *total_number_of_free_bytes = block_size * (guint64)fsstat.f_bfree;
4592                 }
4593         }
4594         
4595         return(TRUE);
4596 }
4597 #else
4598 gboolean
4599 mono_w32file_get_disk_free_space (const gunichar2 *path_name, guint64 *free_bytes_avail, guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes)
4600 {
4601         if (free_bytes_avail != NULL) {
4602                 *free_bytes_avail = (guint64) -1;
4603         }
4604
4605         if (total_number_of_bytes != NULL) {
4606                 *total_number_of_bytes = (guint64) -1;
4607         }
4608
4609         if (total_number_of_free_bytes != NULL) {
4610                 *total_number_of_free_bytes = (guint64) -1;
4611         }
4612
4613         return(TRUE);
4614 }
4615 #endif
4616
4617 /*
4618  * General Unix support
4619  */
4620 typedef struct {
4621         guint32 drive_type;
4622 #if __linux__
4623         const long fstypeid;
4624 #endif
4625         const gchar* fstype;
4626 } _wapi_drive_type;
4627
4628 static _wapi_drive_type _wapi_drive_types[] = {
4629 #if PLATFORM_MACOSX
4630         { DRIVE_REMOTE, "afp" },
4631         { DRIVE_REMOTE, "autofs" },
4632         { DRIVE_CDROM, "cddafs" },
4633         { DRIVE_CDROM, "cd9660" },
4634         { DRIVE_RAMDISK, "devfs" },
4635         { DRIVE_FIXED, "exfat" },
4636         { DRIVE_RAMDISK, "fdesc" },
4637         { DRIVE_REMOTE, "ftp" },
4638         { DRIVE_FIXED, "hfs" },
4639         { DRIVE_FIXED, "msdos" },
4640         { DRIVE_REMOTE, "nfs" },
4641         { DRIVE_FIXED, "ntfs" },
4642         { DRIVE_REMOTE, "smbfs" },
4643         { DRIVE_FIXED, "udf" },
4644         { DRIVE_REMOTE, "webdav" },
4645         { DRIVE_UNKNOWN, NULL }
4646 #elif __linux__
4647         { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4648         { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4649         { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4650         { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4651         { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4652         { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4653         { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4654         { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4655         { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4656         { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4657         { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4658         { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4659         { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4660         { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4661         { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4662         { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4663         { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4664         { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4665         { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4666         { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4667         { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4668         { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4669         { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4670         { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4671         { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4672         { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4673         { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4674         { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4675         { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4676         { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4677         { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4678         { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4679         { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4680         { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4681         { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4682         { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4683         { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4684         { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4685         { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4686         { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4687         { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4688         { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4689         { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4690         { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4691         { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4692         { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4693         { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4694         { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4695         { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4696         { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4697         { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4698         { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4699         { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4700         { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4701         { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4702         { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4703         { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4704         { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4705         { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4706         { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4707         { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4708         { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4709         { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4710         { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4711         { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4712         { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4713         { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4714         { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4715         { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4716         { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4717         { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4718         { DRIVE_UNKNOWN, 0, NULL}
4719 #else
4720         { DRIVE_RAMDISK, "ramfs"      },
4721         { DRIVE_RAMDISK, "tmpfs"      },
4722         { DRIVE_RAMDISK, "proc"       },
4723         { DRIVE_RAMDISK, "sysfs"      },
4724         { DRIVE_RAMDISK, "debugfs"    },
4725         { DRIVE_RAMDISK, "devpts"     },
4726         { DRIVE_RAMDISK, "securityfs" },
4727         { DRIVE_CDROM,   "iso9660"    },
4728         { DRIVE_FIXED,   "ext2"       },
4729         { DRIVE_FIXED,   "ext3"       },
4730         { DRIVE_FIXED,   "ext4"       },
4731         { DRIVE_FIXED,   "sysv"       },
4732         { DRIVE_FIXED,   "reiserfs"   },
4733         { DRIVE_FIXED,   "ufs"        },
4734         { DRIVE_FIXED,   "vfat"       },
4735         { DRIVE_FIXED,   "msdos"      },
4736         { DRIVE_FIXED,   "udf"        },
4737         { DRIVE_FIXED,   "hfs"        },
4738         { DRIVE_FIXED,   "hpfs"       },
4739         { DRIVE_FIXED,   "qnx4"       },
4740         { DRIVE_FIXED,   "ntfs"       },
4741         { DRIVE_FIXED,   "ntfs-3g"    },
4742         { DRIVE_REMOTE,  "smbfs"      },
4743         { DRIVE_REMOTE,  "fuse"       },
4744         { DRIVE_REMOTE,  "nfs"        },
4745         { DRIVE_REMOTE,  "nfs4"       },
4746         { DRIVE_REMOTE,  "cifs"       },
4747         { DRIVE_REMOTE,  "ncpfs"      },
4748         { DRIVE_REMOTE,  "coda"       },
4749         { DRIVE_REMOTE,  "afs"        },
4750         { DRIVE_UNKNOWN, NULL         }
4751 #endif
4752 };
4753
4754 #if __linux__
4755 static guint32 _wapi_get_drive_type(long f_type)
4756 {
4757         _wapi_drive_type *current;
4758
4759         current = &_wapi_drive_types[0];
4760         while (current->drive_type != DRIVE_UNKNOWN) {
4761                 if (current->fstypeid == f_type)
4762                         return current->drive_type;
4763                 current++;
4764         }
4765
4766         return DRIVE_UNKNOWN;
4767 }
4768 #else
4769 static guint32 _wapi_get_drive_type(const gchar* fstype)
4770 {
4771         _wapi_drive_type *current;
4772
4773         current = &_wapi_drive_types[0];
4774         while (current->drive_type != DRIVE_UNKNOWN) {
4775                 if (strcmp (current->fstype, fstype) == 0)
4776                         break;
4777
4778                 current++;
4779         }
4780         
4781         return current->drive_type;
4782 }
4783 #endif
4784
4785 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4786 static guint32
4787 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4788 {
4789         struct statfs buf;
4790         gint res;
4791
4792         MONO_ENTER_GC_SAFE;
4793         res = statfs (utf8_root_path_name, &buf);
4794         MONO_EXIT_GC_SAFE;
4795         if (res == -1)
4796                 return DRIVE_UNKNOWN;
4797 #if PLATFORM_MACOSX
4798         return _wapi_get_drive_type (buf.f_fstypename);
4799 #else
4800         return _wapi_get_drive_type (buf.f_type);
4801 #endif
4802 }
4803 #else
4804 static guint32
4805 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4806 {
4807         guint32 drive_type;
4808         FILE *fp;
4809         gchar buffer [512];
4810         gchar **splitted;
4811
4812         MONO_ENTER_GC_SAFE;
4813         fp = fopen ("/etc/mtab", "rt");
4814         MONO_EXIT_GC_SAFE;
4815         if (fp == NULL) {
4816                 MONO_ENTER_GC_SAFE;
4817                 fp = fopen ("/etc/mnttab", "rt");
4818                 MONO_EXIT_GC_SAFE;
4819                 if (fp == NULL) 
4820                         return(DRIVE_UNKNOWN);
4821         }
4822
4823         drive_type = DRIVE_NO_ROOT_DIR;
4824         while (1) {
4825                 gchar *fgets_res;
4826                 MONO_ENTER_GC_SAFE;
4827                 fgets_res = fgets (buffer, 512, fp);
4828                 MONO_EXIT_GC_SAFE;
4829                 if (fgets_res == NULL)
4830                         break;
4831                 splitted = g_strsplit (buffer, " ", 0);
4832                 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4833                         g_strfreev (splitted);
4834                         continue;
4835                 }
4836
4837                 /* compare given root_path_name with the one from mtab, 
4838                   if length of utf8_root_path_name is zero it must be the root dir */
4839                 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4840                     (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4841                         drive_type = _wapi_get_drive_type (*(splitted + 2));
4842                         /* it is possible this path might be mounted again with
4843                            a known type...keep looking */
4844                         if (drive_type != DRIVE_UNKNOWN) {
4845                                 g_strfreev (splitted);
4846                                 break;
4847                         }
4848                 }
4849
4850                 g_strfreev (splitted);
4851         }
4852
4853         MONO_ENTER_GC_SAFE;
4854         fclose (fp);
4855         MONO_EXIT_GC_SAFE;
4856         return drive_type;
4857 }
4858 #endif
4859
4860 guint32
4861 mono_w32file_get_drive_type(const gunichar2 *root_path_name)
4862 {
4863         gchar *utf8_root_path_name;
4864         guint32 drive_type;
4865
4866         if (root_path_name == NULL) {
4867                 utf8_root_path_name = g_strdup (g_get_current_dir());
4868                 if (utf8_root_path_name == NULL) {
4869                         return(DRIVE_NO_ROOT_DIR);
4870                 }
4871         }
4872         else {
4873                 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4874                 if (utf8_root_path_name == NULL) {
4875                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4876                         return(DRIVE_NO_ROOT_DIR);
4877                 }
4878                 
4879                 /* strip trailing slash for compare below */
4880                 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4881                         utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4882                 }
4883         }
4884         drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4885         g_free (utf8_root_path_name);
4886
4887         return (drive_type);
4888 }
4889
4890 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__FreeBSD_kernel__) || defined(__HAIKU__)
4891 static gchar*
4892 get_fstypename (gchar *utfpath)
4893 {
4894 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4895         struct statfs stat;
4896 #if __linux__
4897         _wapi_drive_type *current;
4898 #endif
4899         gint statfs_res;
4900         MONO_ENTER_GC_SAFE;
4901         statfs_res = statfs (utfpath, &stat);
4902         MONO_EXIT_GC_SAFE;
4903         if (statfs_res == -1)
4904                 return NULL;
4905 #if PLATFORM_MACOSX
4906         return g_strdup (stat.f_fstypename);
4907 #else
4908         current = &_wapi_drive_types[0];
4909         while (current->drive_type != DRIVE_UNKNOWN) {
4910                 if (stat.f_type == current->fstypeid)
4911                         return g_strdup (current->fstype);
4912                 current++;
4913         }
4914         return NULL;
4915 #endif
4916 #else
4917         return NULL;
4918 #endif
4919 }
4920
4921 /* Linux has struct statfs which has a different layout */
4922 gboolean
4923 mono_w32file_get_volume_information (const gunichar2 *path, gunichar2 *volumename, gint volumesize, gint *outserial, gint *maxcomp, gint *fsflags, gunichar2 *fsbuffer, gint fsbuffersize)
4924 {
4925         gchar *utfpath;
4926         gchar *fstypename;
4927         gboolean status = FALSE;
4928         glong len;
4929         
4930         // We only support getting the file system type
4931         if (fsbuffer == NULL)
4932                 return 0;
4933         
4934         utfpath = mono_unicode_to_external (path);
4935         if ((fstypename = get_fstypename (utfpath)) != NULL){
4936                 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4937                 if (ret != NULL && len < fsbuffersize){
4938                         memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4939                         fsbuffer [len] = 0;
4940                         status = TRUE;
4941                 }
4942                 if (ret != NULL)
4943                         g_free (ret);
4944                 g_free (fstypename);
4945         }
4946         g_free (utfpath);
4947         return status;
4948 }
4949 #endif
4950
4951 static gboolean
4952 LockFile (gpointer handle, guint32 offset_low, guint32 offset_high, guint32 length_low, guint32 length_high)
4953 {
4954         MonoW32HandleFile *file_handle;
4955         off_t offset, length;
4956
4957         if (!mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE, (gpointer *)&file_handle)) {
4958                 g_warning ("%s: error looking up file handle %p", __func__, handle);
4959                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
4960                 return FALSE;
4961         }
4962
4963         if (!(file_handle->fileaccess & GENERIC_READ) && !(file_handle->fileaccess & GENERIC_WRITE) && !(file_handle->fileaccess & GENERIC_ALL)) {
4964                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
4965                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
4966                 return FALSE;
4967         }
4968
4969 #ifdef HAVE_LARGE_FILE_SUPPORT
4970         offset = ((gint64)offset_high << 32) | offset_low;
4971         length = ((gint64)length_high << 32) | length_low;
4972
4973         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Locking handle %p, offset %" G_GINT64_FORMAT ", length %" G_GINT64_FORMAT, __func__,
4974                   handle, (gint64) offset, (gint64) length);
4975 #else
4976         if (offset_high > 0 || length_high > 0) {
4977                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
4978                 return FALSE;
4979         }
4980         offset = offset_low;
4981         length = length_low;
4982
4983         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Locking handle %p, offset %" G_GINT64_FORMAT ", length %" G_GINT64_FORMAT, __func__,
4984                   handle, (gint64) offset, (gint64) length);
4985 #endif
4986
4987         return _wapi_lock_file_region (GPOINTER_TO_UINT(handle), offset, length);
4988 }
4989
4990 static gboolean
4991 UnlockFile (gpointer handle, guint32 offset_low, guint32 offset_high, guint32 length_low, guint32 length_high)
4992 {
4993         MonoW32HandleFile *file_handle;
4994         off_t offset, length;
4995
4996         if (!mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE, (gpointer *)&file_handle)) {
4997                 g_warning ("%s: error looking up file handle %p", __func__, handle);
4998                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
4999                 return FALSE;
5000         }
5001
5002         if (!(file_handle->fileaccess & GENERIC_READ) && !(file_handle->fileaccess & GENERIC_WRITE) && !(file_handle->fileaccess & GENERIC_ALL)) {
5003                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
5004                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
5005                 return FALSE;
5006         }
5007
5008 #ifdef HAVE_LARGE_FILE_SUPPORT
5009         offset = ((gint64)offset_high << 32) | offset_low;
5010         length = ((gint64)length_high << 32) | length_low;
5011
5012         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unlocking handle %p, offset %" G_GINT64_FORMAT ", length %" G_GINT64_FORMAT, __func__,
5013                   handle, (gint64) offset, (gint64) length);
5014 #else
5015         offset = offset_low;
5016         length = length_low;
5017
5018         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unlocking handle %p, offset %" G_GINT64_FORMAT ", length %" G_GINT64_FORMAT, __func__, handle, (gint64) offset, (gint64) length);
5019 #endif
5020
5021         return _wapi_unlock_file_region (GPOINTER_TO_UINT(handle), offset, length);
5022 }
5023
5024 void
5025 mono_w32file_init (void)
5026 {
5027         mono_coop_mutex_init (&stdhandle_mutex);
5028         mono_coop_mutex_init (&file_share_mutex);
5029
5030         mono_w32handle_register_ops (MONO_W32HANDLE_FILE,    &_wapi_file_ops);
5031         mono_w32handle_register_ops (MONO_W32HANDLE_CONSOLE, &_wapi_console_ops);
5032         mono_w32handle_register_ops (MONO_W32HANDLE_FIND,    &_wapi_find_ops);
5033         mono_w32handle_register_ops (MONO_W32HANDLE_PIPE,    &_wapi_pipe_ops);
5034
5035 /*      mono_w32handle_register_capabilities (MONO_W32HANDLE_FILE, */
5036 /*                                          MONO_W32HANDLE_CAP_WAIT); */
5037 /*      mono_w32handle_register_capabilities (MONO_W32HANDLE_CONSOLE, */
5038 /*                                          MONO_W32HANDLE_CAP_WAIT); */
5039
5040         if (g_hasenv ("MONO_STRICT_IO_EMULATION"))
5041                 lock_while_writing = TRUE;
5042 }
5043
5044 void
5045 mono_w32file_cleanup (void)
5046 {
5047         mono_coop_mutex_destroy (&file_share_mutex);
5048
5049         if (file_share_table)
5050                 g_hash_table_destroy (file_share_table);
5051 }
5052
5053 gboolean
5054 mono_w32file_move (gunichar2 *path, gunichar2 *dest, gint32 *error)
5055 {
5056         gboolean result;
5057
5058         result = MoveFile (path, dest);
5059         if (!result)
5060                 *error = mono_w32error_get_last ();
5061         return result;
5062 }
5063
5064 gboolean
5065 mono_w32file_copy (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
5066 {
5067         gboolean result;
5068
5069         result = CopyFile (path, dest, !overwrite);
5070         if (!result)
5071                 *error = mono_w32error_get_last ();
5072
5073         return result;
5074 }
5075
5076 gboolean
5077 mono_w32file_replace (gunichar2 *destinationFileName, gunichar2 *sourceFileName, gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
5078 {
5079         gboolean result;
5080
5081         result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
5082         if (!result)
5083                 *error = mono_w32error_get_last ();
5084         return result;
5085 }
5086
5087 gint64
5088 mono_w32file_get_file_size (gpointer handle, gint32 *error)
5089 {
5090         gint64 length;
5091         guint32 length_hi;
5092
5093         length = GetFileSize (handle, &length_hi);
5094         if(length==INVALID_FILE_SIZE) {
5095                 *error=mono_w32error_get_last ();
5096         }
5097
5098         return length | ((gint64)length_hi << 32);
5099 }
5100
5101 gboolean
5102 mono_w32file_lock (gpointer handle, gint64 position, gint64 length, gint32 *error)
5103 {
5104         gboolean result;
5105
5106         result = LockFile (handle, position & 0xFFFFFFFF, position >> 32, length & 0xFFFFFFFF, length >> 32);
5107         if (!result)
5108                 *error = mono_w32error_get_last ();
5109         return result;
5110 }
5111
5112 gboolean
5113 mono_w32file_unlock (gpointer handle, gint64 position, gint64 length, gint32 *error)
5114 {
5115         gboolean result;
5116
5117         result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32, length & 0xFFFFFFFF, length >> 32);
5118         if (!result)
5119                 *error = mono_w32error_get_last ();
5120         return result;
5121 }
5122
5123 gpointer
5124 mono_w32file_get_console_input (void)
5125 {
5126         return mono_w32file_get_std_handle (STD_INPUT_HANDLE);
5127 }
5128
5129 gpointer
5130 mono_w32file_get_console_output (void)
5131 {
5132         return mono_w32file_get_std_handle (STD_OUTPUT_HANDLE);
5133 }
5134
5135 gpointer
5136 mono_w32file_get_console_error (void)
5137 {
5138         return mono_w32file_get_std_handle (STD_ERROR_HANDLE);
5139 }