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