Merge pull request #4169 from evincarofautumn/fix-xmm-scanning-mac-x86
[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         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
1103         MONO_ENTER_GC_UNSAFE;
1104         MonoW32HandleFile *file_handle = (MonoW32HandleFile *)data;
1105         gint fd = file_handle->fd;
1106         
1107         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing file handle %p [%s]", __func__, handle,
1108                   file_handle->filename);
1109
1110         if (file_handle->attrs & FILE_FLAG_DELETE_ON_CLOSE)
1111                 _wapi_unlink (file_handle->filename);
1112         
1113         g_free (file_handle->filename);
1114         
1115         if (file_handle->share_info)
1116                 file_share_release (file_handle->share_info);
1117         
1118         MONO_ENTER_GC_SAFE;
1119         close (fd);
1120         MONO_EXIT_GC_SAFE;
1121         MONO_EXIT_GC_UNSAFE;
1122 }
1123
1124 static void file_details (gpointer data)
1125 {
1126         MonoW32HandleFile *file = (MonoW32HandleFile *)data;
1127         
1128         g_print ("[%20s] acc: %c%c%c, shr: %c%c%c, attrs: %5u",
1129                  file->filename,
1130                  file->fileaccess&GENERIC_READ?'R':'.',
1131                  file->fileaccess&GENERIC_WRITE?'W':'.',
1132                  file->fileaccess&GENERIC_EXECUTE?'X':'.',
1133                  file->sharemode&FILE_SHARE_READ?'R':'.',
1134                  file->sharemode&FILE_SHARE_WRITE?'W':'.',
1135                  file->sharemode&FILE_SHARE_DELETE?'D':'.',
1136                  file->attrs);
1137 }
1138
1139 static const gchar* file_typename (void)
1140 {
1141         return "File";
1142 }
1143
1144 static gsize file_typesize (void)
1145 {
1146         return sizeof (MonoW32HandleFile);
1147 }
1148
1149 static gint file_getfiletype(void)
1150 {
1151         return(FILE_TYPE_DISK);
1152 }
1153
1154 static gboolean
1155 file_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
1156 {
1157         MonoW32HandleFile *file_handle;
1158         gboolean ok;
1159         gint fd, ret;
1160         MonoThreadInfo *info = mono_thread_info_current ();
1161         
1162         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1163                                 (gpointer *)&file_handle);
1164         if(ok==FALSE) {
1165                 g_warning ("%s: error looking up file handle %p", __func__,
1166                            handle);
1167                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1168                 return(FALSE);
1169         }
1170
1171         fd = file_handle->fd;
1172         if(bytesread!=NULL) {
1173                 *bytesread=0;
1174         }
1175         
1176         if(!(file_handle->fileaccess & GENERIC_READ) &&
1177            !(file_handle->fileaccess & GENERIC_ALL)) {
1178                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1179                           __func__, handle, file_handle->fileaccess);
1180
1181                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1182                 return(FALSE);
1183         }
1184
1185         do {
1186                 MONO_ENTER_GC_SAFE;
1187                 ret = read (fd, buffer, numbytes);
1188                 MONO_EXIT_GC_SAFE;
1189         } while (ret == -1 && errno == EINTR &&
1190                  !mono_thread_info_is_interrupt_state (info));
1191                         
1192         if(ret==-1) {
1193                 gint err = errno;
1194
1195                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
1196                           handle, strerror(err));
1197                 mono_w32error_set_last (mono_w32error_unix_to_win32 (err));
1198                 return(FALSE);
1199         }
1200                 
1201         if (bytesread != NULL) {
1202                 *bytesread = ret;
1203         }
1204                 
1205         return(TRUE);
1206 }
1207
1208 static gboolean
1209 file_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
1210 {
1211         MonoW32HandleFile *file_handle;
1212         gboolean ok;
1213         gint ret, fd;
1214         off_t current_pos = 0;
1215         MonoThreadInfo *info = mono_thread_info_current ();
1216         
1217         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1218                                 (gpointer *)&file_handle);
1219         if(ok==FALSE) {
1220                 g_warning ("%s: error looking up file handle %p", __func__,
1221                            handle);
1222                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1223                 return(FALSE);
1224         }
1225
1226         fd = file_handle->fd;
1227         
1228         if(byteswritten!=NULL) {
1229                 *byteswritten=0;
1230         }
1231         
1232         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1233            !(file_handle->fileaccess & GENERIC_ALL)) {
1234                 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);
1235
1236                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1237                 return(FALSE);
1238         }
1239         
1240         if (lock_while_writing) {
1241                 /* Need to lock the region we're about to write to,
1242                  * because we only do advisory locking on POSIX
1243                  * systems
1244                  */
1245                 MONO_ENTER_GC_SAFE;
1246                 current_pos = lseek (fd, (off_t)0, SEEK_CUR);
1247                 MONO_EXIT_GC_SAFE;
1248                 if (current_pos == -1) {
1249                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
1250                                    handle, strerror (errno));
1251                         _wapi_set_last_error_from_errno ();
1252                         return(FALSE);
1253                 }
1254                 
1255                 if (_wapi_lock_file_region (fd, current_pos,
1256                                             numbytes) == FALSE) {
1257                         /* The error has already been set */
1258                         return(FALSE);
1259                 }
1260         }
1261                 
1262         do {
1263                 MONO_ENTER_GC_SAFE;
1264                 ret = write (fd, buffer, numbytes);
1265                 MONO_EXIT_GC_SAFE;
1266         } while (ret == -1 && errno == EINTR &&
1267                  !mono_thread_info_is_interrupt_state (info));
1268         
1269         if (lock_while_writing) {
1270                 _wapi_unlock_file_region (fd, current_pos, numbytes);
1271         }
1272
1273         if (ret == -1) {
1274                 if (errno == EINTR) {
1275                         ret = 0;
1276                 } else {
1277                         _wapi_set_last_error_from_errno ();
1278                                 
1279                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1280                                   __func__, handle, strerror(errno));
1281
1282                         return(FALSE);
1283                 }
1284         }
1285         if (byteswritten != NULL) {
1286                 *byteswritten = ret;
1287         }
1288         return(TRUE);
1289 }
1290
1291 static gboolean file_flush(gpointer handle)
1292 {
1293         MonoW32HandleFile *file_handle;
1294         gboolean ok;
1295         gint ret, fd;
1296         
1297         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1298                                 (gpointer *)&file_handle);
1299         if(ok==FALSE) {
1300                 g_warning ("%s: error looking up file handle %p", __func__,
1301                            handle);
1302                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1303                 return(FALSE);
1304         }
1305
1306         fd = file_handle->fd;
1307
1308         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1309            !(file_handle->fileaccess & GENERIC_ALL)) {
1310                 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);
1311
1312                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1313                 return(FALSE);
1314         }
1315
1316         MONO_ENTER_GC_SAFE;
1317         ret=fsync(fd);
1318         MONO_EXIT_GC_SAFE;
1319         if (ret==-1) {
1320                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fsync of handle %p error: %s", __func__, handle,
1321                           strerror(errno));
1322
1323                 _wapi_set_last_error_from_errno ();
1324                 return(FALSE);
1325         }
1326         
1327         return(TRUE);
1328 }
1329
1330 static guint32 file_seek(gpointer handle, gint32 movedistance,
1331                          gint32 *highmovedistance, gint method)
1332 {
1333         MonoW32HandleFile *file_handle;
1334         gboolean ok;
1335         gint64 offset, newpos;
1336         gint whence, fd;
1337         guint32 ret;
1338         
1339         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1340                                 (gpointer *)&file_handle);
1341         if(ok==FALSE) {
1342                 g_warning ("%s: error looking up file handle %p", __func__,
1343                            handle);
1344                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1345                 return(INVALID_SET_FILE_POINTER);
1346         }
1347         
1348         fd = file_handle->fd;
1349
1350         if(!(file_handle->fileaccess & GENERIC_READ) &&
1351            !(file_handle->fileaccess & GENERIC_WRITE) &&
1352            !(file_handle->fileaccess & GENERIC_ALL)) {
1353                 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);
1354
1355                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1356                 return(INVALID_SET_FILE_POINTER);
1357         }
1358
1359         switch(method) {
1360         case FILE_BEGIN:
1361                 whence=SEEK_SET;
1362                 break;
1363         case FILE_CURRENT:
1364                 whence=SEEK_CUR;
1365                 break;
1366         case FILE_END:
1367                 whence=SEEK_END;
1368                 break;
1369         default:
1370                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: invalid seek type %d", __func__, method);
1371
1372                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1373                 return(INVALID_SET_FILE_POINTER);
1374         }
1375
1376 #ifdef HAVE_LARGE_FILE_SUPPORT
1377         if(highmovedistance==NULL) {
1378                 offset=movedistance;
1379                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting offset to %lld (low %d)", __func__,
1380                           offset, movedistance);
1381         } else {
1382                 offset=((gint64) *highmovedistance << 32) | (guint32)movedistance;
1383                 
1384                 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);
1385         }
1386 #else
1387         offset=movedistance;
1388 #endif
1389
1390         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: moving handle %p by %lld bytes from %d", __func__,
1391                    handle, (long long)offset, whence);
1392
1393 #ifdef PLATFORM_ANDROID
1394         /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
1395         MONO_ENTER_GC_SAFE;
1396         newpos=lseek64(fd, offset, whence);
1397         MONO_EXIT_GC_SAFE;
1398 #else
1399         MONO_ENTER_GC_SAFE;
1400         newpos=lseek(fd, offset, whence);
1401         MONO_EXIT_GC_SAFE;
1402 #endif
1403         if(newpos==-1) {
1404                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek on handle %p returned error %s",
1405                           __func__, handle, strerror(errno));
1406
1407                 _wapi_set_last_error_from_errno ();
1408                 return(INVALID_SET_FILE_POINTER);
1409         }
1410
1411         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lseek returns %lld", __func__, newpos);
1412
1413 #ifdef HAVE_LARGE_FILE_SUPPORT
1414         ret=newpos & 0xFFFFFFFF;
1415         if(highmovedistance!=NULL) {
1416                 *highmovedistance=newpos>>32;
1417         }
1418 #else
1419         ret=newpos;
1420         if(highmovedistance!=NULL) {
1421                 /* Accurate, but potentially dodgy :-) */
1422                 *highmovedistance=0;
1423         }
1424 #endif
1425
1426         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: move of handle %p returning %d/%d", __func__,
1427                    handle, ret, highmovedistance==NULL?0:*highmovedistance);
1428
1429         return(ret);
1430 }
1431
1432 static gboolean file_setendoffile(gpointer handle)
1433 {
1434         MonoW32HandleFile *file_handle;
1435         gboolean ok;
1436         struct stat statbuf;
1437         off_t pos;
1438         gint ret, fd;
1439         MonoThreadInfo *info = mono_thread_info_current ();
1440         
1441         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1442                                 (gpointer *)&file_handle);
1443         if(ok==FALSE) {
1444                 g_warning ("%s: error looking up file handle %p", __func__,
1445                            handle);
1446                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1447                 return(FALSE);
1448         }
1449         fd = file_handle->fd;
1450         
1451         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1452            !(file_handle->fileaccess & GENERIC_ALL)) {
1453                 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);
1454
1455                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1456                 return(FALSE);
1457         }
1458
1459         /* Find the current file position, and the file length.  If
1460          * the file position is greater than the length, write to
1461          * extend the file with a hole.  If the file position is less
1462          * than the length, truncate the file.
1463          */
1464         
1465         MONO_ENTER_GC_SAFE;
1466         ret=fstat(fd, &statbuf);
1467         MONO_EXIT_GC_SAFE;
1468         if(ret==-1) {
1469                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
1470                            handle, strerror(errno));
1471
1472                 _wapi_set_last_error_from_errno ();
1473                 return(FALSE);
1474         }
1475
1476         MONO_ENTER_GC_SAFE;
1477         pos=lseek(fd, (off_t)0, SEEK_CUR);
1478         MONO_EXIT_GC_SAFE;
1479         if(pos==-1) {
1480                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p lseek failed: %s", __func__,
1481                           handle, strerror(errno));
1482
1483                 _wapi_set_last_error_from_errno ();
1484                 return(FALSE);
1485         }
1486         
1487 #ifdef FTRUNCATE_DOESNT_EXTEND
1488         off_t size = statbuf.st_size;
1489         /* I haven't bothered to write the configure.ac stuff for this
1490          * because I don't know if any platform needs it.  I'm leaving
1491          * this code just in case though
1492          */
1493         if(pos>size) {
1494                 /* Extend the file.  Use write() here, because some
1495                  * manuals say that ftruncate() behaviour is undefined
1496                  * when the file needs extending.  The POSIX spec says
1497                  * that on XSI-conformant systems it extends, so if
1498                  * every system we care about conforms, then we can
1499                  * drop this write.
1500                  */
1501                 do {
1502                         MONO_ENTER_GC_SAFE;
1503                         ret = write (fd, "", 1);
1504                         MONO_EXIT_GC_SAFE;
1505                 } while (ret == -1 && errno == EINTR &&
1506                          !mono_thread_info_is_interrupt_state (info));
1507
1508                 if(ret==-1) {
1509                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p extend write failed: %s", __func__, handle, strerror(errno));
1510
1511                         _wapi_set_last_error_from_errno ();
1512                         return(FALSE);
1513                 }
1514
1515                 /* And put the file position back after the write */
1516                 MONO_ENTER_GC_SAFE;
1517                 ret = lseek (fd, pos, SEEK_SET);
1518                 MONO_EXIT_GC_SAFE;
1519                 if (ret == -1) {
1520                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p second lseek failed: %s",
1521                                    __func__, handle, strerror(errno));
1522
1523                         _wapi_set_last_error_from_errno ();
1524                         return(FALSE);
1525                 }
1526         }
1527 #endif
1528
1529 /* Native Client has no ftruncate function, even in standalone sel_ldr. */
1530 #ifndef __native_client__
1531         /* always truncate, because the extend write() adds an extra
1532          * byte to the end of the file
1533          */
1534         do {
1535                 MONO_ENTER_GC_SAFE;
1536                 ret=ftruncate(fd, pos);
1537                 MONO_EXIT_GC_SAFE;
1538         }
1539         while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info)); 
1540         if(ret==-1) {
1541                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ftruncate failed: %s", __func__,
1542                           handle, strerror(errno));
1543                 
1544                 _wapi_set_last_error_from_errno ();
1545                 return(FALSE);
1546         }
1547 #endif
1548                 
1549         return(TRUE);
1550 }
1551
1552 static guint32 file_getfilesize(gpointer handle, guint32 *highsize)
1553 {
1554         MonoW32HandleFile *file_handle;
1555         gboolean ok;
1556         struct stat statbuf;
1557         guint32 size;
1558         gint ret;
1559         gint fd;
1560         
1561         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1562                                 (gpointer *)&file_handle);
1563         if(ok==FALSE) {
1564                 g_warning ("%s: error looking up file handle %p", __func__,
1565                            handle);
1566                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1567                 return(INVALID_FILE_SIZE);
1568         }
1569         fd = file_handle->fd;
1570         
1571         if(!(file_handle->fileaccess & GENERIC_READ) &&
1572            !(file_handle->fileaccess & GENERIC_WRITE) &&
1573            !(file_handle->fileaccess & GENERIC_ALL)) {
1574                 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);
1575
1576                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1577                 return(INVALID_FILE_SIZE);
1578         }
1579
1580         /* If the file has a size with the low bits 0xFFFFFFFF the
1581          * caller can't tell if this is an error, so clear the error
1582          * value
1583          */
1584         mono_w32error_set_last (ERROR_SUCCESS);
1585         
1586         MONO_ENTER_GC_SAFE;
1587         ret = fstat(fd, &statbuf);
1588         MONO_EXIT_GC_SAFE;
1589         if (ret == -1) {
1590                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__,
1591                            handle, strerror(errno));
1592
1593                 _wapi_set_last_error_from_errno ();
1594                 return(INVALID_FILE_SIZE);
1595         }
1596         
1597         /* fstat indicates block devices as zero-length, so go a different path */
1598 #ifdef BLKGETSIZE64
1599         if (S_ISBLK(statbuf.st_mode)) {
1600                 guint64 bigsize;
1601                 gint res;
1602                 MONO_ENTER_GC_SAFE;
1603                 res = ioctl (fd, BLKGETSIZE64, &bigsize);
1604                 MONO_EXIT_GC_SAFE;
1605                 if (res < 0) {
1606                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p ioctl BLKGETSIZE64 failed: %s",
1607                                    __func__, handle, strerror(errno));
1608
1609                         _wapi_set_last_error_from_errno ();
1610                         return(INVALID_FILE_SIZE);
1611                 }
1612                 
1613                 size = bigsize & 0xFFFFFFFF;
1614                 if (highsize != NULL) {
1615                         *highsize = bigsize>>32;
1616                 }
1617
1618                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning block device size %d/%d",
1619                            __func__, size, *highsize);
1620         
1621                 return(size);
1622         }
1623 #endif
1624         
1625 #ifdef HAVE_LARGE_FILE_SUPPORT
1626         size = statbuf.st_size & 0xFFFFFFFF;
1627         if (highsize != NULL) {
1628                 *highsize = statbuf.st_size>>32;
1629         }
1630 #else
1631         if (highsize != NULL) {
1632                 /* Accurate, but potentially dodgy :-) */
1633                 *highsize = 0;
1634         }
1635         size = statbuf.st_size;
1636 #endif
1637
1638         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning size %d/%d", __func__, size, *highsize);
1639         
1640         return(size);
1641 }
1642
1643 static gboolean file_getfiletime(gpointer handle, FILETIME *create_time,
1644                                  FILETIME *access_time,
1645                                  FILETIME *write_time)
1646 {
1647         MonoW32HandleFile *file_handle;
1648         gboolean ok;
1649         struct stat statbuf;
1650         guint64 create_ticks, access_ticks, write_ticks;
1651         gint ret, fd;
1652         
1653         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1654                                 (gpointer *)&file_handle);
1655         if(ok==FALSE) {
1656                 g_warning ("%s: error looking up file handle %p", __func__,
1657                            handle);
1658                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1659                 return(FALSE);
1660         }
1661         fd = file_handle->fd;
1662
1663         if(!(file_handle->fileaccess & GENERIC_READ) &&
1664            !(file_handle->fileaccess & GENERIC_ALL)) {
1665                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1666                           __func__, handle, file_handle->fileaccess);
1667
1668                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1669                 return(FALSE);
1670         }
1671         
1672         MONO_ENTER_GC_SAFE;
1673         ret=fstat(fd, &statbuf);
1674         MONO_EXIT_GC_SAFE;
1675         if(ret==-1) {
1676                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1677                           strerror(errno));
1678
1679                 _wapi_set_last_error_from_errno ();
1680                 return(FALSE);
1681         }
1682
1683         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: atime: %ld ctime: %ld mtime: %ld", __func__,
1684                   statbuf.st_atime, statbuf.st_ctime,
1685                   statbuf.st_mtime);
1686
1687         /* Try and guess a meaningful create time by using the older
1688          * of atime or ctime
1689          */
1690         /* The magic constant comes from msdn documentation
1691          * "Converting a time_t Value to a File Time"
1692          */
1693         if(statbuf.st_atime < statbuf.st_ctime) {
1694                 create_ticks=((guint64)statbuf.st_atime*10000000)
1695                         + 116444736000000000ULL;
1696         } else {
1697                 create_ticks=((guint64)statbuf.st_ctime*10000000)
1698                         + 116444736000000000ULL;
1699         }
1700         
1701         access_ticks=((guint64)statbuf.st_atime*10000000)+116444736000000000ULL;
1702         write_ticks=((guint64)statbuf.st_mtime*10000000)+116444736000000000ULL;
1703         
1704         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: aticks: %llu cticks: %llu wticks: %llu", __func__,
1705                   access_ticks, create_ticks, write_ticks);
1706
1707         if(create_time!=NULL) {
1708                 create_time->dwLowDateTime = create_ticks & 0xFFFFFFFF;
1709                 create_time->dwHighDateTime = create_ticks >> 32;
1710         }
1711         
1712         if(access_time!=NULL) {
1713                 access_time->dwLowDateTime = access_ticks & 0xFFFFFFFF;
1714                 access_time->dwHighDateTime = access_ticks >> 32;
1715         }
1716         
1717         if(write_time!=NULL) {
1718                 write_time->dwLowDateTime = write_ticks & 0xFFFFFFFF;
1719                 write_time->dwHighDateTime = write_ticks >> 32;
1720         }
1721
1722         return(TRUE);
1723 }
1724
1725 static gboolean file_setfiletime(gpointer handle,
1726                                  const FILETIME *create_time G_GNUC_UNUSED,
1727                                  const FILETIME *access_time,
1728                                  const FILETIME *write_time)
1729 {
1730         MonoW32HandleFile *file_handle;
1731         gboolean ok;
1732         struct utimbuf utbuf;
1733         struct stat statbuf;
1734         guint64 access_ticks, write_ticks;
1735         gint ret, fd;
1736         
1737         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE,
1738                                 (gpointer *)&file_handle);
1739         if(ok==FALSE) {
1740                 g_warning ("%s: error looking up file handle %p", __func__,
1741                            handle);
1742                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1743                 return(FALSE);
1744         }
1745         fd = file_handle->fd;
1746         
1747         if(!(file_handle->fileaccess & GENERIC_WRITE) &&
1748            !(file_handle->fileaccess & GENERIC_ALL)) {
1749                 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);
1750
1751                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1752                 return(FALSE);
1753         }
1754
1755         if(file_handle->filename == NULL) {
1756                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p unknown filename", __func__, handle);
1757
1758                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1759                 return(FALSE);
1760         }
1761         
1762         /* Get the current times, so we can put the same times back in
1763          * the event that one of the FileTime structs is NULL
1764          */
1765         MONO_ENTER_GC_SAFE;
1766         ret=fstat (fd, &statbuf);
1767         MONO_EXIT_GC_SAFE;
1768         if(ret==-1) {
1769                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p fstat failed: %s", __func__, handle,
1770                           strerror(errno));
1771
1772                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1773                 return(FALSE);
1774         }
1775
1776         if(access_time!=NULL) {
1777                 access_ticks=((guint64)access_time->dwHighDateTime << 32) +
1778                         access_time->dwLowDateTime;
1779                 /* This is (time_t)0.  We can actually go to INT_MIN,
1780                  * but this will do for now.
1781                  */
1782                 if (access_ticks < 116444736000000000ULL) {
1783                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set access time too early",
1784                                    __func__);
1785                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1786                         return(FALSE);
1787                 }
1788
1789                 if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1790                         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",
1791                                    __func__);
1792                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1793                         return(FALSE);
1794                 }
1795
1796                 utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
1797         } else {
1798                 utbuf.actime=statbuf.st_atime;
1799         }
1800
1801         if(write_time!=NULL) {
1802                 write_ticks=((guint64)write_time->dwHighDateTime << 32) +
1803                         write_time->dwLowDateTime;
1804                 /* This is (time_t)0.  We can actually go to INT_MIN,
1805                  * but this will do for now.
1806                  */
1807                 if (write_ticks < 116444736000000000ULL) {
1808                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time too early",
1809                                    __func__);
1810                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1811                         return(FALSE);
1812                 }
1813                 if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
1814                         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",
1815                                    __func__);
1816                         mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1817                         return(FALSE);
1818                 }
1819                 
1820                 utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
1821         } else {
1822                 utbuf.modtime=statbuf.st_mtime;
1823         }
1824
1825         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: setting handle %p access %ld write %ld", __func__,
1826                    handle, utbuf.actime, utbuf.modtime);
1827
1828         ret = _wapi_utime (file_handle->filename, &utbuf);
1829         if (ret == -1) {
1830                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p [%s] utime failed: %s", __func__,
1831                            handle, file_handle->filename, strerror(errno));
1832
1833                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
1834                 return(FALSE);
1835         }
1836         
1837         return(TRUE);
1838 }
1839
1840 static void console_close (gpointer handle, gpointer data)
1841 {
1842         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
1843         MONO_ENTER_GC_UNSAFE;
1844         MonoW32HandleFile *console_handle = (MonoW32HandleFile *)data;
1845         gint fd = console_handle->fd;
1846         
1847         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing console handle %p", __func__, handle);
1848
1849         g_free (console_handle->filename);
1850
1851         if (fd > 2) {
1852                 if (console_handle->share_info)
1853                         file_share_release (console_handle->share_info);
1854                 MONO_ENTER_GC_SAFE;
1855                 close (fd);
1856                 MONO_EXIT_GC_SAFE;
1857         }
1858         MONO_EXIT_GC_UNSAFE;
1859 }
1860
1861 static void console_details (gpointer data)
1862 {
1863         file_details (data);
1864 }
1865
1866 static const gchar* console_typename (void)
1867 {
1868         return "Console";
1869 }
1870
1871 static gsize console_typesize (void)
1872 {
1873         return sizeof (MonoW32HandleFile);
1874 }
1875
1876 static gint console_getfiletype(void)
1877 {
1878         return(FILE_TYPE_CHAR);
1879 }
1880
1881 static gboolean
1882 console_read(gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
1883 {
1884         MonoW32HandleFile *console_handle;
1885         gboolean ok;
1886         gint ret, fd;
1887         MonoThreadInfo *info = mono_thread_info_current ();
1888
1889         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1890                                 (gpointer *)&console_handle);
1891         if(ok==FALSE) {
1892                 g_warning ("%s: error looking up console handle %p", __func__,
1893                            handle);
1894                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1895                 return(FALSE);
1896         }
1897         fd = console_handle->fd;
1898         
1899         if(bytesread!=NULL) {
1900                 *bytesread=0;
1901         }
1902         
1903         if(!(console_handle->fileaccess & GENERIC_READ) &&
1904            !(console_handle->fileaccess & GENERIC_ALL)) {
1905                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
1906                            __func__, handle, console_handle->fileaccess);
1907
1908                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1909                 return(FALSE);
1910         }
1911         
1912         do {
1913                 MONO_ENTER_GC_SAFE;
1914                 ret=read(fd, buffer, numbytes);
1915                 MONO_EXIT_GC_SAFE;
1916         } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
1917
1918         if(ret==-1) {
1919                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__, handle,
1920                           strerror(errno));
1921
1922                 _wapi_set_last_error_from_errno ();
1923                 return(FALSE);
1924         }
1925         
1926         if(bytesread!=NULL) {
1927                 *bytesread=ret;
1928         }
1929         
1930         return(TRUE);
1931 }
1932
1933 static gboolean
1934 console_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
1935 {
1936         MonoW32HandleFile *console_handle;
1937         gboolean ok;
1938         gint ret, fd;
1939         MonoThreadInfo *info = mono_thread_info_current ();
1940         
1941         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
1942                                 (gpointer *)&console_handle);
1943         if(ok==FALSE) {
1944                 g_warning ("%s: error looking up console handle %p", __func__,
1945                            handle);
1946                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
1947                 return(FALSE);
1948         }
1949         fd = console_handle->fd;
1950         
1951         if(byteswritten!=NULL) {
1952                 *byteswritten=0;
1953         }
1954         
1955         if(!(console_handle->fileaccess & GENERIC_WRITE) &&
1956            !(console_handle->fileaccess & GENERIC_ALL)) {
1957                 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);
1958
1959                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
1960                 return(FALSE);
1961         }
1962         
1963         do {
1964                 MONO_ENTER_GC_SAFE;
1965                 ret = write(fd, buffer, numbytes);
1966                 MONO_EXIT_GC_SAFE;
1967         } while (ret == -1 && errno == EINTR &&
1968                  !mono_thread_info_is_interrupt_state (info));
1969
1970         if (ret == -1) {
1971                 if (errno == EINTR) {
1972                         ret = 0;
1973                 } else {
1974                         _wapi_set_last_error_from_errno ();
1975                         
1976                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s",
1977                                    __func__, handle, strerror(errno));
1978
1979                         return(FALSE);
1980                 }
1981         }
1982         if(byteswritten!=NULL) {
1983                 *byteswritten=ret;
1984         }
1985         
1986         return(TRUE);
1987 }
1988
1989 static const gchar* find_typename (void)
1990 {
1991         return "Find";
1992 }
1993
1994 static gsize find_typesize (void)
1995 {
1996         return sizeof (MonoW32HandleFind);
1997 }
1998
1999 static void pipe_close (gpointer handle, gpointer data)
2000 {
2001         /* FIXME: after mono_w32handle_close is coop-aware, change this to MONO_REQ_GC_UNSAFE_MODE and leave just the switch to SAFE around close() below */
2002         MONO_ENTER_GC_UNSAFE;
2003         MonoW32HandleFile *pipe_handle = (MonoW32HandleFile*)data;
2004         gint fd = pipe_handle->fd;
2005
2006         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: closing pipe handle %p fd %d", __func__, handle, fd);
2007
2008         /* No filename with pipe handles */
2009
2010         if (pipe_handle->share_info)
2011                 file_share_release (pipe_handle->share_info);
2012
2013         MONO_ENTER_GC_SAFE;
2014         close (fd);
2015         MONO_EXIT_GC_SAFE;
2016         MONO_EXIT_GC_UNSAFE;
2017 }
2018
2019 static void pipe_details (gpointer data)
2020 {
2021         file_details (data);
2022 }
2023
2024 static const gchar* pipe_typename (void)
2025 {
2026         return "Pipe";
2027 }
2028
2029 static gsize pipe_typesize (void)
2030 {
2031         return sizeof (MonoW32HandleFile);
2032 }
2033
2034 static gint pipe_getfiletype(void)
2035 {
2036         return(FILE_TYPE_PIPE);
2037 }
2038
2039 static gboolean
2040 pipe_read (gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
2041 {
2042         MonoW32HandleFile *pipe_handle;
2043         gboolean ok;
2044         gint ret, fd;
2045         MonoThreadInfo *info = mono_thread_info_current ();
2046
2047         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
2048                                 (gpointer *)&pipe_handle);
2049         if(ok==FALSE) {
2050                 g_warning ("%s: error looking up pipe handle %p", __func__,
2051                            handle);
2052                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2053                 return(FALSE);
2054         }
2055         fd = pipe_handle->fd;
2056
2057         if(bytesread!=NULL) {
2058                 *bytesread=0;
2059         }
2060         
2061         if(!(pipe_handle->fileaccess & GENERIC_READ) &&
2062            !(pipe_handle->fileaccess & GENERIC_ALL)) {
2063                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: handle %p doesn't have GENERIC_READ access: %u",
2064                           __func__, handle, pipe_handle->fileaccess);
2065
2066                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2067                 return(FALSE);
2068         }
2069         
2070         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: reading up to %d bytes from pipe %p", __func__,
2071                    numbytes, handle);
2072
2073         do {
2074                 MONO_ENTER_GC_SAFE;
2075                 ret=read(fd, buffer, numbytes);
2076                 MONO_EXIT_GC_SAFE;
2077         } while (ret==-1 && errno==EINTR && !mono_thread_info_is_interrupt_state (info));
2078                 
2079         if (ret == -1) {
2080                 if (errno == EINTR) {
2081                         ret = 0;
2082                 } else {
2083                         _wapi_set_last_error_from_errno ();
2084                         
2085                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read of handle %p error: %s", __func__,
2086                                   handle, strerror(errno));
2087
2088                         return(FALSE);
2089                 }
2090         }
2091         
2092         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: read %d bytes from pipe %p", __func__, ret, handle);
2093
2094         if(bytesread!=NULL) {
2095                 *bytesread=ret;
2096         }
2097         
2098         return(TRUE);
2099 }
2100
2101 static gboolean
2102 pipe_write(gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
2103 {
2104         MonoW32HandleFile *pipe_handle;
2105         gboolean ok;
2106         gint ret, fd;
2107         MonoThreadInfo *info = mono_thread_info_current ();
2108         
2109         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_PIPE,
2110                                 (gpointer *)&pipe_handle);
2111         if(ok==FALSE) {
2112                 g_warning ("%s: error looking up pipe handle %p", __func__,
2113                            handle);
2114                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
2115                 return(FALSE);
2116         }
2117         fd = pipe_handle->fd;
2118         
2119         if(byteswritten!=NULL) {
2120                 *byteswritten=0;
2121         }
2122         
2123         if(!(pipe_handle->fileaccess & GENERIC_WRITE) &&
2124            !(pipe_handle->fileaccess & GENERIC_ALL)) {
2125                 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);
2126
2127                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
2128                 return(FALSE);
2129         }
2130         
2131         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: writing up to %d bytes to pipe %p", __func__, numbytes,
2132                    handle);
2133
2134         do {
2135                 MONO_ENTER_GC_SAFE;
2136                 ret = write (fd, buffer, numbytes);
2137                 MONO_EXIT_GC_SAFE;
2138         } while (ret == -1 && errno == EINTR &&
2139                  !mono_thread_info_is_interrupt_state (info));
2140
2141         if (ret == -1) {
2142                 if (errno == EINTR) {
2143                         ret = 0;
2144                 } else {
2145                         _wapi_set_last_error_from_errno ();
2146                         
2147                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write of handle %p error: %s", __func__,
2148                                   handle, strerror(errno));
2149
2150                         return(FALSE);
2151                 }
2152         }
2153         if(byteswritten!=NULL) {
2154                 *byteswritten=ret;
2155         }
2156         
2157         return(TRUE);
2158 }
2159
2160 static gint convert_flags(guint32 fileaccess, guint32 createmode)
2161 {
2162         gint flags=0;
2163         
2164         switch(fileaccess) {
2165         case GENERIC_READ:
2166                 flags=O_RDONLY;
2167                 break;
2168         case GENERIC_WRITE:
2169                 flags=O_WRONLY;
2170                 break;
2171         case GENERIC_READ|GENERIC_WRITE:
2172                 flags=O_RDWR;
2173                 break;
2174         default:
2175                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown access type 0x%x", __func__,
2176                           fileaccess);
2177                 break;
2178         }
2179
2180         switch(createmode) {
2181         case CREATE_NEW:
2182                 flags|=O_CREAT|O_EXCL;
2183                 break;
2184         case CREATE_ALWAYS:
2185                 flags|=O_CREAT|O_TRUNC;
2186                 break;
2187         case OPEN_EXISTING:
2188                 break;
2189         case OPEN_ALWAYS:
2190                 flags|=O_CREAT;
2191                 break;
2192         case TRUNCATE_EXISTING:
2193                 flags|=O_TRUNC;
2194                 break;
2195         default:
2196                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unknown create mode 0x%x", __func__,
2197                           createmode);
2198                 break;
2199         }
2200         
2201         return(flags);
2202 }
2203
2204 #if 0 /* unused */
2205 static mode_t convert_perms(guint32 sharemode)
2206 {
2207         mode_t perms=0600;
2208         
2209         if(sharemode&FILE_SHARE_READ) {
2210                 perms|=044;
2211         }
2212         if(sharemode&FILE_SHARE_WRITE) {
2213                 perms|=022;
2214         }
2215
2216         return(perms);
2217 }
2218 #endif
2219
2220 static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
2221                                    guint32 fileaccess,
2222                                    FileShare **share_info)
2223 {
2224         gboolean file_already_shared;
2225         guint32 file_existing_share, file_existing_access;
2226
2227         file_already_shared = file_share_get (statbuf->st_dev, statbuf->st_ino, sharemode, fileaccess, &file_existing_share, &file_existing_access, share_info);
2228         
2229         if (file_already_shared) {
2230                 /* The reference to this share info was incremented
2231                  * when we looked it up, so be careful to put it back
2232                  * if we conclude we can't use this file.
2233                  */
2234                 if (file_existing_share == 0) {
2235                         /* Quick and easy, no possibility to share */
2236                         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);
2237
2238                         file_share_release (*share_info);
2239                         
2240                         return(FALSE);
2241                 }
2242
2243                 if (((file_existing_share == FILE_SHARE_READ) &&
2244                      (fileaccess != GENERIC_READ)) ||
2245                     ((file_existing_share == FILE_SHARE_WRITE) &&
2246                      (fileaccess != GENERIC_WRITE))) {
2247                         /* New access mode doesn't match up */
2248                         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);
2249
2250                         file_share_release (*share_info);
2251                 
2252                         return(FALSE);
2253                 }
2254
2255                 if (((file_existing_access & GENERIC_READ) &&
2256                      !(sharemode & FILE_SHARE_READ)) ||
2257                     ((file_existing_access & GENERIC_WRITE) &&
2258                      !(sharemode & FILE_SHARE_WRITE))) {
2259                         /* New share mode doesn't match up */
2260                         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);
2261
2262                         file_share_release (*share_info);
2263                 
2264                         return(FALSE);
2265                 }
2266         } else {
2267                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
2268         }
2269
2270         return(TRUE);
2271 }
2272
2273
2274 static gboolean
2275 share_allows_delete (struct stat *statbuf, FileShare **share_info)
2276 {
2277         gboolean file_already_shared;
2278         guint32 file_existing_share, file_existing_access;
2279
2280         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);
2281
2282         if (file_already_shared) {
2283                 /* The reference to this share info was incremented
2284                  * when we looked it up, so be careful to put it back
2285                  * if we conclude we can't use this file.
2286                  */
2287                 if (file_existing_share == 0) {
2288                         /* Quick and easy, no possibility to share */
2289                         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);
2290
2291                         file_share_release (*share_info);
2292
2293                         return(FALSE);
2294                 }
2295
2296                 if (!(file_existing_share & FILE_SHARE_DELETE)) {
2297                         /* New access mode doesn't match up */
2298                         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);
2299
2300                         file_share_release (*share_info);
2301
2302                         return(FALSE);
2303                 }
2304         } else {
2305                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: New file!", __func__);
2306         }
2307
2308         return(TRUE);
2309 }
2310
2311 gpointer
2312 mono_w32file_create(const gunichar2 *name, guint32 fileaccess, guint32 sharemode, guint32 createmode, guint32 attrs)
2313 {
2314         MonoW32HandleFile file_handle = {0};
2315         gpointer handle;
2316         gint flags=convert_flags(fileaccess, createmode);
2317         /*mode_t perms=convert_perms(sharemode);*/
2318         /* we don't use sharemode, because that relates to sharing of
2319          * the file when the file is open and is already handled by
2320          * other code, perms instead are the on-disk permissions and
2321          * this is a sane default.
2322          */
2323         mode_t perms=0666;
2324         gchar *filename;
2325         gint fd, ret;
2326         MonoW32HandleType handle_type;
2327         struct stat statbuf;
2328
2329         if (attrs & FILE_ATTRIBUTE_TEMPORARY)
2330                 perms = 0600;
2331         
2332         if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
2333                 mono_w32error_set_last (ERROR_ENCRYPTION_FAILED);
2334                 return INVALID_HANDLE_VALUE;
2335         }
2336         
2337         if (name == NULL) {
2338                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2339
2340                 mono_w32error_set_last (ERROR_INVALID_NAME);
2341                 return(INVALID_HANDLE_VALUE);
2342         }
2343
2344         filename = mono_unicode_to_external (name);
2345         if (filename == NULL) {
2346                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2347
2348                 mono_w32error_set_last (ERROR_INVALID_NAME);
2349                 return(INVALID_HANDLE_VALUE);
2350         }
2351         
2352         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
2353                    filename, sharemode, fileaccess);
2354         
2355         fd = _wapi_open (filename, flags, perms);
2356     
2357         /* If we were trying to open a directory with write permissions
2358          * (e.g. O_WRONLY or O_RDWR), this call will fail with
2359          * EISDIR. However, this is a bit bogus because calls to
2360          * manipulate the directory (e.g. mono_w32file_set_times) will still work on
2361          * the directory because they use other API calls
2362          * (e.g. utime()). Hence, if we failed with the EISDIR error, try
2363          * to open the directory again without write permission.
2364          */
2365         if (fd == -1 && errno == EISDIR)
2366         {
2367                 /* Try again but don't try to make it writable */
2368                 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
2369         }
2370         
2371         if (fd == -1) {
2372                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
2373                           strerror(errno));
2374                 _wapi_set_last_path_error_from_errno (NULL, filename);
2375                 g_free (filename);
2376
2377                 return(INVALID_HANDLE_VALUE);
2378         }
2379
2380         if (fd >= mono_w32handle_fd_reserve) {
2381                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
2382
2383                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
2384                 
2385                 MONO_ENTER_GC_SAFE;
2386                 close (fd);
2387                 MONO_EXIT_GC_SAFE;
2388                 g_free (filename);
2389                 
2390                 return(INVALID_HANDLE_VALUE);
2391         }
2392
2393         MONO_ENTER_GC_SAFE;
2394         ret = fstat (fd, &statbuf);
2395         MONO_EXIT_GC_SAFE;
2396         if (ret == -1) {
2397                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
2398                            filename, strerror (errno));
2399                 _wapi_set_last_error_from_errno ();
2400                 g_free (filename);
2401                 MONO_ENTER_GC_SAFE;
2402                 close (fd);
2403                 MONO_EXIT_GC_SAFE;
2404                 
2405                 return(INVALID_HANDLE_VALUE);
2406         }
2407 #ifdef __native_client__
2408         /* Workaround: Native Client currently returns the same fake inode
2409          * for all files, so do a simple hash on the filename so we don't
2410          * use the same share info for each file.
2411          */
2412         statbuf.st_ino = g_str_hash(filename);
2413 #endif
2414
2415         if (share_allows_open (&statbuf, sharemode, fileaccess,
2416                          &file_handle.share_info) == FALSE) {
2417                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2418                 g_free (filename);
2419                 MONO_ENTER_GC_SAFE;
2420                 close (fd);
2421                 MONO_EXIT_GC_SAFE;
2422                 
2423                 return (INVALID_HANDLE_VALUE);
2424         }
2425         if (file_handle.share_info == NULL) {
2426                 /* No space, so no more files can be opened */
2427                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
2428
2429                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
2430                 MONO_ENTER_GC_SAFE;
2431                 close (fd);
2432                 MONO_EXIT_GC_SAFE;
2433                 g_free (filename);
2434                 
2435                 return(INVALID_HANDLE_VALUE);
2436         }
2437         
2438         file_handle.filename = filename;
2439         
2440         file_handle.fd = fd;
2441         file_handle.fileaccess=fileaccess;
2442         file_handle.sharemode=sharemode;
2443         file_handle.attrs=attrs;
2444
2445 #ifdef HAVE_POSIX_FADVISE
2446         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN) {
2447                 MONO_ENTER_GC_SAFE;
2448                 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
2449                 MONO_EXIT_GC_SAFE;
2450         }
2451         if (attrs & FILE_FLAG_RANDOM_ACCESS) {
2452                 MONO_ENTER_GC_SAFE;
2453                 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
2454                 MONO_EXIT_GC_SAFE;
2455         }
2456 #endif
2457
2458 #ifdef F_RDAHEAD
2459         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN) {
2460                 MONO_ENTER_GC_SAFE;
2461                 fcntl(fd, F_RDAHEAD, 1);
2462                 MONO_EXIT_GC_SAFE;
2463         }
2464 #endif
2465
2466 #ifndef S_ISFIFO
2467 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
2468 #endif
2469         if (S_ISFIFO (statbuf.st_mode)) {
2470                 handle_type = MONO_W32HANDLE_PIPE;
2471                 /* maintain invariant that pipes have no filename */
2472                 file_handle.filename = NULL;
2473                 g_free (filename);
2474                 filename = NULL;
2475         } else if (S_ISCHR (statbuf.st_mode)) {
2476                 handle_type = MONO_W32HANDLE_CONSOLE;
2477         } else {
2478                 handle_type = MONO_W32HANDLE_FILE;
2479         }
2480
2481         MONO_ENTER_GC_SAFE; /* FIXME: mono_w32handle_new_fd should be updated with coop transitions */
2482         handle = mono_w32handle_new_fd (handle_type, fd, &file_handle);
2483         MONO_EXIT_GC_SAFE;
2484         if (handle == INVALID_HANDLE_VALUE) {
2485                 g_warning ("%s: error creating file handle", __func__);
2486                 g_free (filename);
2487                 MONO_ENTER_GC_SAFE;
2488                 close (fd);
2489                 MONO_EXIT_GC_SAFE;
2490                 
2491                 mono_w32error_set_last (ERROR_GEN_FAILURE);
2492                 return(INVALID_HANDLE_VALUE);
2493         }
2494         
2495         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
2496         
2497         return(handle);
2498 }
2499
2500 gboolean
2501 mono_w32file_close (gpointer handle)
2502 {
2503         gboolean res;
2504         MONO_ENTER_GC_SAFE;
2505         /* FIXME: we transition here and not in file_close, pipe_close,
2506          * console_close because w32handle_close is not coop aware yet, but it
2507          * calls back into w32file. */
2508         res = mono_w32handle_close (handle);
2509         MONO_EXIT_GC_SAFE;
2510         return res;
2511 }
2512
2513 gboolean mono_w32file_delete(const gunichar2 *name)
2514 {
2515         gchar *filename;
2516         gint retval;
2517         gboolean ret = FALSE;
2518         guint32 attrs;
2519 #if 0
2520         struct stat statbuf;
2521         FileShare *shareinfo;
2522 #endif
2523         
2524         if(name==NULL) {
2525                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2526
2527                 mono_w32error_set_last (ERROR_INVALID_NAME);
2528                 return(FALSE);
2529         }
2530
2531         filename=mono_unicode_to_external(name);
2532         if(filename==NULL) {
2533                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2534
2535                 mono_w32error_set_last (ERROR_INVALID_NAME);
2536                 return(FALSE);
2537         }
2538
2539         attrs = mono_w32file_get_attributes (name);
2540         if (attrs == INVALID_FILE_ATTRIBUTES) {
2541                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
2542                 /* Error set by mono_w32file_get_attributes() */
2543                 g_free (filename);
2544                 return(FALSE);
2545         }
2546
2547 #if 0
2548         /* Check to make sure sharing allows us to open the file for
2549          * writing.  See bug 323389.
2550          *
2551          * Do the checks that don't need an open file descriptor, for
2552          * simplicity's sake.  If we really have to do the full checks
2553          * then we can implement that later.
2554          */
2555         if (_wapi_stat (filename, &statbuf) < 0) {
2556                 _wapi_set_last_path_error_from_errno (NULL, filename);
2557                 g_free (filename);
2558                 return(FALSE);
2559         }
2560         
2561         if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
2562                                &shareinfo) == FALSE) {
2563                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2564                 g_free (filename);
2565                 return FALSE;
2566         }
2567         if (shareinfo)
2568                 file_share_release (shareinfo);
2569 #endif
2570
2571         retval = _wapi_unlink (filename);
2572         
2573         if (retval == -1) {
2574                 _wapi_set_last_path_error_from_errno (NULL, filename);
2575         } else {
2576                 ret = TRUE;
2577         }
2578
2579         g_free(filename);
2580
2581         return(ret);
2582 }
2583
2584 static gboolean
2585 MoveFile (gunichar2 *name, gunichar2 *dest_name)
2586 {
2587         gchar *utf8_name, *utf8_dest_name;
2588         gint result, errno_copy;
2589         struct stat stat_src, stat_dest;
2590         gboolean ret = FALSE;
2591         FileShare *shareinfo;
2592         
2593         if(name==NULL) {
2594                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2595
2596                 mono_w32error_set_last (ERROR_INVALID_NAME);
2597                 return(FALSE);
2598         }
2599
2600         utf8_name = mono_unicode_to_external (name);
2601         if (utf8_name == NULL) {
2602                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2603                 
2604                 mono_w32error_set_last (ERROR_INVALID_NAME);
2605                 return FALSE;
2606         }
2607         
2608         if(dest_name==NULL) {
2609                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2610
2611                 g_free (utf8_name);
2612                 mono_w32error_set_last (ERROR_INVALID_NAME);
2613                 return(FALSE);
2614         }
2615
2616         utf8_dest_name = mono_unicode_to_external (dest_name);
2617         if (utf8_dest_name == NULL) {
2618                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2619
2620                 g_free (utf8_name);
2621                 mono_w32error_set_last (ERROR_INVALID_NAME);
2622                 return FALSE;
2623         }
2624
2625         /*
2626          * In C# land we check for the existence of src, but not for dest.
2627          * We check it here and return the failure if dest exists and is not
2628          * the same file as src.
2629          */
2630         if (_wapi_stat (utf8_name, &stat_src) < 0) {
2631                 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
2632                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2633                         g_free (utf8_name);
2634                         g_free (utf8_dest_name);
2635                         return FALSE;
2636                 }
2637         }
2638         
2639         if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
2640                 if (stat_dest.st_dev != stat_src.st_dev ||
2641                     stat_dest.st_ino != stat_src.st_ino) {
2642                         g_free (utf8_name);
2643                         g_free (utf8_dest_name);
2644                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2645                         return FALSE;
2646                 }
2647         }
2648
2649         /* Check to make that we have delete sharing permission.
2650          * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
2651          *
2652          * Do the checks that don't need an open file descriptor, for
2653          * simplicity's sake.  If we really have to do the full checks
2654          * then we can implement that later.
2655          */
2656         if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
2657                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2658                 return FALSE;
2659         }
2660         if (shareinfo)
2661                 file_share_release (shareinfo);
2662
2663         result = _wapi_rename (utf8_name, utf8_dest_name);
2664         errno_copy = errno;
2665         
2666         if (result == -1) {
2667                 switch(errno_copy) {
2668                 case EEXIST:
2669                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2670                         break;
2671
2672                 case EXDEV:
2673                         /* Ignore here, it is dealt with below */
2674                         break;
2675
2676                 case ENOENT:
2677                         /* We already know src exists. Must be dest that doesn't exist. */
2678                         _wapi_set_last_path_error_from_errno (NULL, utf8_dest_name);
2679                         break;
2680
2681                 default:
2682                         _wapi_set_last_error_from_errno ();
2683                 }
2684         }
2685         
2686         g_free (utf8_name);
2687         g_free (utf8_dest_name);
2688
2689         if (result != 0 && errno_copy == EXDEV) {
2690                 gint32 copy_error;
2691
2692                 if (S_ISDIR (stat_src.st_mode)) {
2693                         mono_w32error_set_last (ERROR_NOT_SAME_DEVICE);
2694                         return FALSE;
2695                 }
2696                 /* Try a copy to the new location, and delete the source */
2697                 if (!mono_w32file_copy (name, dest_name, FALSE, &copy_error)) {
2698                         /* mono_w32file_copy will set the error */
2699                         return(FALSE);
2700                 }
2701                 
2702                 return(mono_w32file_delete (name));
2703         }
2704
2705         if (result == 0) {
2706                 ret = TRUE;
2707         }
2708
2709         return(ret);
2710 }
2711
2712 static gboolean
2713 write_file (gint src_fd, gint dest_fd, struct stat *st_src, gboolean report_errors)
2714 {
2715         gint remain, n;
2716         gchar *buf, *wbuf;
2717         gint buf_size = st_src->st_blksize;
2718         MonoThreadInfo *info = mono_thread_info_current ();
2719
2720         buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
2721         buf = (gchar *) g_malloc (buf_size);
2722
2723         for (;;) {
2724                 MONO_ENTER_GC_SAFE;
2725                 remain = read (src_fd, buf, buf_size);
2726                 MONO_EXIT_GC_SAFE;
2727                 if (remain < 0) {
2728                         if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2729                                 continue;
2730
2731                         if (report_errors)
2732                                 _wapi_set_last_error_from_errno ();
2733
2734                         g_free (buf);
2735                         return FALSE;
2736                 }
2737                 if (remain == 0) {
2738                         break;
2739                 }
2740
2741                 wbuf = buf;
2742                 while (remain > 0) {
2743                         MONO_ENTER_GC_SAFE;
2744                         n = write (dest_fd, wbuf, remain);
2745                         MONO_EXIT_GC_SAFE;
2746                         if (n < 0) {
2747                                 if (errno == EINTR && !mono_thread_info_is_interrupt_state (info))
2748                                         continue;
2749
2750                                 if (report_errors)
2751                                         _wapi_set_last_error_from_errno ();
2752                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
2753                                 g_free (buf);
2754                                 return FALSE;
2755                         }
2756
2757                         remain -= n;
2758                         wbuf += n;
2759                 }
2760         }
2761
2762         g_free (buf);
2763         return TRUE ;
2764 }
2765
2766 static gboolean
2767 CopyFile (const gunichar2 *name, const gunichar2 *dest_name, gboolean fail_if_exists)
2768 {
2769         gchar *utf8_src, *utf8_dest;
2770         gint src_fd, dest_fd;
2771         struct stat st, dest_st;
2772         struct utimbuf dest_time;
2773         gboolean ret = TRUE;
2774         gint ret_utime;
2775         gint syscall_res;
2776         
2777         if(name==NULL) {
2778                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2779
2780                 mono_w32error_set_last (ERROR_INVALID_NAME);
2781                 return(FALSE);
2782         }
2783         
2784         utf8_src = mono_unicode_to_external (name);
2785         if (utf8_src == NULL) {
2786                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
2787                            __func__);
2788
2789                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2790                 return(FALSE);
2791         }
2792         
2793         if(dest_name==NULL) {
2794                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
2795
2796                 g_free (utf8_src);
2797                 mono_w32error_set_last (ERROR_INVALID_NAME);
2798                 return(FALSE);
2799         }
2800         
2801         utf8_dest = mono_unicode_to_external (dest_name);
2802         if (utf8_dest == NULL) {
2803                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
2804                            __func__);
2805
2806                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2807
2808                 g_free (utf8_src);
2809                 
2810                 return(FALSE);
2811         }
2812         
2813         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
2814         if (src_fd < 0) {
2815                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
2816                 
2817                 g_free (utf8_src);
2818                 g_free (utf8_dest);
2819                 
2820                 return(FALSE);
2821         }
2822
2823         MONO_ENTER_GC_SAFE;
2824         syscall_res = fstat (src_fd, &st);
2825         MONO_EXIT_GC_SAFE;
2826         if (syscall_res < 0) {
2827                 _wapi_set_last_error_from_errno ();
2828
2829                 g_free (utf8_src);
2830                 g_free (utf8_dest);
2831                 MONO_ENTER_GC_SAFE;
2832                 close (src_fd);
2833                 MONO_EXIT_GC_SAFE;
2834                 
2835                 return(FALSE);
2836         }
2837
2838         /* Before trying to open/create the dest, we need to report a 'file busy'
2839          * error if src and dest are actually the same file. We do the check here to take
2840          * advantage of the IOMAP capability */
2841         if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev && 
2842                         st.st_ino == dest_st.st_ino) {
2843
2844                 g_free (utf8_src);
2845                 g_free (utf8_dest);
2846                 MONO_ENTER_GC_SAFE;
2847                 close (src_fd);
2848                 MONO_EXIT_GC_SAFE;
2849
2850                 mono_w32error_set_last (ERROR_SHARING_VIOLATION);
2851                 return (FALSE);
2852         }
2853         
2854         if (fail_if_exists) {
2855                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2856         } else {
2857                 /* FIXME: it kinda sucks that this code path potentially scans
2858                  * the directory twice due to the weird mono_w32error_set_last()
2859                  * behavior. */
2860                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2861                 if (dest_fd < 0) {
2862                         /* The file does not exist, try creating it */
2863                         dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2864                 } else {
2865                         /* Apparently this error is set if we
2866                          * overwrite the dest file
2867                          */
2868                         mono_w32error_set_last (ERROR_ALREADY_EXISTS);
2869                 }
2870         }
2871         if (dest_fd < 0) {
2872                 _wapi_set_last_error_from_errno ();
2873
2874                 g_free (utf8_src);
2875                 g_free (utf8_dest);
2876                 MONO_ENTER_GC_SAFE;
2877                 close (src_fd);
2878                 MONO_EXIT_GC_SAFE;
2879
2880                 return(FALSE);
2881         }
2882
2883         if (!write_file (src_fd, dest_fd, &st, TRUE))
2884                 ret = FALSE;
2885
2886         close (src_fd);
2887         close (dest_fd);
2888         
2889         dest_time.modtime = st.st_mtime;
2890         dest_time.actime = st.st_atime;
2891         MONO_ENTER_GC_SAFE;
2892         ret_utime = utime (utf8_dest, &dest_time);
2893         MONO_EXIT_GC_SAFE;
2894         if (ret_utime == -1)
2895                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2896         
2897         g_free (utf8_src);
2898         g_free (utf8_dest);
2899
2900         return ret;
2901 }
2902
2903 static gchar*
2904 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2905 {
2906         gchar *utf8_ret;
2907
2908         if (arg == NULL) {
2909                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2910                 mono_w32error_set_last (ERROR_INVALID_NAME);
2911                 return NULL;
2912         }
2913
2914         utf8_ret = mono_unicode_to_external (arg);
2915         if (utf8_ret == NULL) {
2916                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2917                            __func__, arg_name);
2918                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
2919                 return NULL;
2920         }
2921
2922         return utf8_ret;
2923 }
2924
2925 static gboolean
2926 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName, const gunichar2 *backupFileName, guint32 replaceFlags, gpointer exclude, gpointer reserved)
2927 {
2928         gint result, backup_fd = -1,replaced_fd = -1;
2929         gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2930         struct stat stBackup;
2931         gboolean ret = FALSE;
2932
2933         if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2934                 return FALSE;
2935         if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2936                 goto replace_cleanup;
2937         if (backupFileName != NULL) {
2938                 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2939                         goto replace_cleanup;
2940         }
2941
2942         if (utf8_backupFileName) {
2943                 // Open the backup file for read so we can restore the file if an error occurs.
2944                 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2945                 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2946                 if (result == -1)
2947                         goto replace_cleanup;
2948         }
2949
2950         result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2951         if (result == -1) {
2952                 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2953                 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2954                 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2955                         replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2956                                                   stBackup.st_mode);
2957                         
2958                         if (replaced_fd == -1)
2959                                 goto replace_cleanup;
2960
2961                         write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2962                 }
2963
2964                 goto replace_cleanup;
2965         }
2966
2967         ret = TRUE;
2968
2969 replace_cleanup:
2970         g_free (utf8_replacedFileName);
2971         g_free (utf8_replacementFileName);
2972         g_free (utf8_backupFileName);
2973         if (backup_fd != -1) {
2974                 MONO_ENTER_GC_SAFE;
2975                 close (backup_fd);
2976                 MONO_EXIT_GC_SAFE;
2977         }
2978         if (replaced_fd != -1) {
2979                 MONO_ENTER_GC_SAFE;
2980                 close (replaced_fd);
2981                 MONO_EXIT_GC_SAFE;
2982         }
2983         return ret;
2984 }
2985
2986 static MonoCoopMutex stdhandle_mutex;
2987
2988 static gpointer
2989 _wapi_stdhandle_create (gint fd, const gchar *name)
2990 {
2991         gpointer handle;
2992         gint flags;
2993         MonoW32HandleFile file_handle = {0};
2994
2995         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: creating standard handle type %s, fd %d", __func__, name, fd);
2996
2997 #if !defined(__native_client__)
2998         /* Check if fd is valid */
2999         do {
3000                 flags = fcntl(fd, F_GETFL);
3001         } while (flags == -1 && errno == EINTR);
3002
3003         if (flags == -1) {
3004                 /* Invalid fd.  Not really much point checking for EBADF
3005                  * specifically
3006                  */
3007                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fcntl error on fd %d: %s", __func__, fd, strerror(errno));
3008
3009                 mono_w32error_set_last (mono_w32error_unix_to_win32 (errno));
3010                 return INVALID_HANDLE_VALUE;
3011         }
3012
3013         switch (flags & (O_RDONLY|O_WRONLY|O_RDWR)) {
3014         case O_RDONLY:
3015                 file_handle.fileaccess = GENERIC_READ;
3016                 break;
3017         case O_WRONLY:
3018                 file_handle.fileaccess = GENERIC_WRITE;
3019                 break;
3020         case O_RDWR:
3021                 file_handle.fileaccess = GENERIC_READ | GENERIC_WRITE;
3022                 break;
3023         default:
3024                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Can't figure out flags 0x%x", __func__, flags);
3025                 file_handle.fileaccess = 0;
3026                 break;
3027         }
3028 #else
3029         /*
3030          * fcntl will return -1 in nacl, as there is no real file system API.
3031          * Yet, standard streams are available.
3032          */
3033         file_handle.fileaccess = (fd == STDIN_FILENO) ? GENERIC_READ : GENERIC_WRITE;
3034 #endif
3035
3036         file_handle.fd = fd;
3037         file_handle.filename = g_strdup(name);
3038         /* some default security attributes might be needed */
3039         file_handle.security_attributes = 0;
3040
3041         /* Apparently input handles can't be written to.  (I don't
3042          * know if output or error handles can't be read from.)
3043          */
3044         if (fd == 0)
3045                 file_handle.fileaccess &= ~GENERIC_WRITE;
3046
3047         file_handle.sharemode = 0;
3048         file_handle.attrs = 0;
3049
3050         handle = mono_w32handle_new_fd (MONO_W32HANDLE_CONSOLE, fd, &file_handle);
3051         if (handle == INVALID_HANDLE_VALUE) {
3052                 g_warning ("%s: error creating file handle", __func__);
3053                 mono_w32error_set_last (ERROR_GEN_FAILURE);
3054                 return INVALID_HANDLE_VALUE;
3055         }
3056
3057         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
3058
3059         return handle;
3060 }
3061
3062 enum {
3063         STD_INPUT_HANDLE  = -10,
3064         STD_OUTPUT_HANDLE = -11,
3065         STD_ERROR_HANDLE  = -12,
3066 };
3067
3068 static gpointer
3069 mono_w32file_get_std_handle (gint stdhandle)
3070 {
3071         MonoW32HandleFile *file_handle;
3072         gpointer handle;
3073         gint fd;
3074         const gchar *name;
3075         gboolean ok;
3076         
3077         switch(stdhandle) {
3078         case STD_INPUT_HANDLE:
3079                 fd = 0;
3080                 name = "<stdin>";
3081                 break;
3082
3083         case STD_OUTPUT_HANDLE:
3084                 fd = 1;
3085                 name = "<stdout>";
3086                 break;
3087
3088         case STD_ERROR_HANDLE:
3089                 fd = 2;
3090                 name = "<stderr>";
3091                 break;
3092
3093         default:
3094                 g_assert_not_reached ();
3095         }
3096
3097         handle = GINT_TO_POINTER (fd);
3098
3099         mono_coop_mutex_lock (&stdhandle_mutex);
3100
3101         ok = mono_w32handle_lookup (handle, MONO_W32HANDLE_CONSOLE,
3102                                   (gpointer *)&file_handle);
3103         if (ok == FALSE) {
3104                 /* Need to create this console handle */
3105                 handle = _wapi_stdhandle_create (fd, name);
3106                 
3107                 if (handle == INVALID_HANDLE_VALUE) {
3108                         mono_w32error_set_last (ERROR_NO_MORE_FILES);
3109                         goto done;
3110                 }
3111         } else {
3112                 /* Add a reference to this handle */
3113                 mono_w32handle_ref (handle);
3114         }
3115         
3116   done:
3117         mono_coop_mutex_unlock (&stdhandle_mutex);
3118
3119         return(handle);
3120 }
3121
3122 gboolean
3123 mono_w32file_read (gpointer handle, gpointer buffer, guint32 numbytes, guint32 *bytesread)
3124 {
3125         MonoW32HandleType type;
3126
3127         type = mono_w32handle_get_type (handle);
3128         
3129         if(io_ops[type].readfile==NULL) {
3130                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3131                 return(FALSE);
3132         }
3133         
3134         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread));
3135 }
3136
3137 gboolean
3138 mono_w32file_write (gpointer handle, gconstpointer buffer, guint32 numbytes, guint32 *byteswritten)
3139 {
3140         MonoW32HandleType type;
3141
3142         type = mono_w32handle_get_type (handle);
3143         
3144         if(io_ops[type].writefile==NULL) {
3145                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3146                 return(FALSE);
3147         }
3148         
3149         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten));
3150 }
3151
3152 gboolean
3153 mono_w32file_flush (gpointer handle)
3154 {
3155         MonoW32HandleType type;
3156
3157         type = mono_w32handle_get_type (handle);
3158         
3159         if(io_ops[type].flushfile==NULL) {
3160                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3161                 return(FALSE);
3162         }
3163         
3164         return(io_ops[type].flushfile (handle));
3165 }
3166
3167 gboolean
3168 mono_w32file_truncate (gpointer handle)
3169 {
3170         MonoW32HandleType type;
3171
3172         type = mono_w32handle_get_type (handle);
3173         
3174         if (io_ops[type].setendoffile == NULL) {
3175                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3176                 return(FALSE);
3177         }
3178         
3179         return(io_ops[type].setendoffile (handle));
3180 }
3181
3182 guint32
3183 mono_w32file_seek (gpointer handle, gint32 movedistance, gint32 *highmovedistance, guint32 method)
3184 {
3185         MonoW32HandleType type;
3186
3187         type = mono_w32handle_get_type (handle);
3188         
3189         if (io_ops[type].seek == NULL) {
3190                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3191                 return(INVALID_SET_FILE_POINTER);
3192         }
3193         
3194         return(io_ops[type].seek (handle, movedistance, highmovedistance,
3195                                   method));
3196 }
3197
3198 gint
3199 mono_w32file_get_type(gpointer handle)
3200 {
3201         MonoW32HandleType type;
3202
3203         type = mono_w32handle_get_type (handle);
3204         
3205         if (io_ops[type].getfiletype == NULL) {
3206                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3207                 return(FILE_TYPE_UNKNOWN);
3208         }
3209         
3210         return(io_ops[type].getfiletype ());
3211 }
3212
3213 static guint32
3214 GetFileSize(gpointer handle, guint32 *highsize)
3215 {
3216         MonoW32HandleType type;
3217
3218         type = mono_w32handle_get_type (handle);
3219         
3220         if (io_ops[type].getfilesize == NULL) {
3221                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3222                 return(INVALID_FILE_SIZE);
3223         }
3224         
3225         return(io_ops[type].getfilesize (handle, highsize));
3226 }
3227
3228 gboolean
3229 mono_w32file_get_times(gpointer handle, FILETIME *create_time, FILETIME *access_time, FILETIME *write_time)
3230 {
3231         MonoW32HandleType type;
3232
3233         type = mono_w32handle_get_type (handle);
3234         
3235         if (io_ops[type].getfiletime == NULL) {
3236                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3237                 return(FALSE);
3238         }
3239         
3240         return(io_ops[type].getfiletime (handle, create_time, access_time,
3241                                          write_time));
3242 }
3243
3244 gboolean
3245 mono_w32file_set_times(gpointer handle, const FILETIME *create_time, const FILETIME *access_time, const FILETIME *write_time)
3246 {
3247         MonoW32HandleType type;
3248
3249         type = mono_w32handle_get_type (handle);
3250         
3251         if (io_ops[type].setfiletime == NULL) {
3252                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3253                 return(FALSE);
3254         }
3255         
3256         return(io_ops[type].setfiletime (handle, create_time, access_time,
3257                                          write_time));
3258 }
3259
3260 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
3261  * January 1 1601 GMT
3262  */
3263
3264 #define TICKS_PER_MILLISECOND 10000L
3265 #define TICKS_PER_SECOND 10000000L
3266 #define TICKS_PER_MINUTE 600000000L
3267 #define TICKS_PER_HOUR 36000000000LL
3268 #define TICKS_PER_DAY 864000000000LL
3269
3270 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
3271
3272 static const guint16 mon_yday[2][13]={
3273         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
3274         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
3275 };
3276
3277 gboolean
3278 mono_w32file_filetime_to_systemtime(const FILETIME *file_time, SYSTEMTIME *system_time)
3279 {
3280         gint64 file_ticks, totaldays, rem, y;
3281         const guint16 *ip;
3282         
3283         if(system_time==NULL) {
3284                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
3285
3286                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3287                 return(FALSE);
3288         }
3289         
3290         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
3291                 file_time->dwLowDateTime;
3292         
3293         /* Really compares if file_ticks>=0x8000000000000000
3294          * (LLONG_MAX+1) but we're working with a signed value for the
3295          * year and day calculation to work later
3296          */
3297         if(file_ticks<0) {
3298                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
3299
3300                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3301                 return(FALSE);
3302         }
3303
3304         totaldays=(file_ticks / TICKS_PER_DAY);
3305         rem = file_ticks % TICKS_PER_DAY;
3306         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
3307
3308         system_time->wHour=rem/TICKS_PER_HOUR;
3309         rem %= TICKS_PER_HOUR;
3310         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
3311         
3312         system_time->wMinute = rem / TICKS_PER_MINUTE;
3313         rem %= TICKS_PER_MINUTE;
3314         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
3315                   rem);
3316         
3317         system_time->wSecond = rem / TICKS_PER_SECOND;
3318         rem %= TICKS_PER_SECOND;
3319         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
3320                   rem);
3321         
3322         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
3323         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
3324                   system_time->wMilliseconds);
3325
3326         /* January 1, 1601 was a Monday, according to Emacs calendar */
3327         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
3328         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
3329         
3330         /* This algorithm to find year and month given days from epoch
3331          * from glibc
3332          */
3333         y=1601;
3334         
3335 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
3336 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
3337
3338         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
3339                 /* Guess a corrected year, assuming 365 days per year */
3340                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
3341                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
3342                           totaldays, yg,
3343                           y);
3344                 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
3345                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
3346                 
3347                 /* Adjust days and y to match the guessed year. */
3348                 totaldays -= ((yg - y) * 365
3349                               + LEAPS_THRU_END_OF (yg - 1)
3350                               - LEAPS_THRU_END_OF (y - 1));
3351                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
3352                 y = yg;
3353                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
3354         }
3355         
3356         system_time->wYear = y;
3357         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
3358
3359         ip = mon_yday[isleap(y)];
3360         
3361         for(y=11; totaldays < ip[y]; --y) {
3362                 continue;
3363         }
3364         totaldays-=ip[y];
3365         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
3366         
3367         system_time->wMonth = y + 1;
3368         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
3369
3370         system_time->wDay = totaldays + 1;
3371         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
3372         
3373         return(TRUE);
3374 }
3375
3376 gpointer
3377 mono_w32file_find_first (const gunichar2 *pattern, WIN32_FIND_DATA *find_data)
3378 {
3379         MonoW32HandleFind find_handle = {0};
3380         gpointer handle;
3381         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
3382         gint result;
3383         
3384         if (pattern == NULL) {
3385                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
3386
3387                 mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
3388                 return(INVALID_HANDLE_VALUE);
3389         }
3390
3391         utf8_pattern = mono_unicode_to_external (pattern);
3392         if (utf8_pattern == NULL) {
3393                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3394                 
3395                 mono_w32error_set_last (ERROR_INVALID_NAME);
3396                 return(INVALID_HANDLE_VALUE);
3397         }
3398
3399         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
3400         
3401         /* Figure out which bit of the pattern is the directory */
3402         dir_part = _wapi_dirname (utf8_pattern);
3403         entry_part = _wapi_basename (utf8_pattern);
3404
3405 #if 0
3406         /* Don't do this check for now, it breaks if directories
3407          * really do have metachars in their names (see bug 58116).
3408          * FIXME: Figure out a better solution to keep some checks...
3409          */
3410         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
3411                 mono_w32error_set_last (ERROR_INVALID_NAME);
3412                 g_free (dir_part);
3413                 g_free (entry_part);
3414                 g_free (utf8_pattern);
3415                 return(INVALID_HANDLE_VALUE);
3416         }
3417 #endif
3418
3419         /* The pattern can specify a directory or a set of files.
3420          *
3421          * The pattern can have wildcard characters ? and *, but only
3422          * in the section after the last directory delimiter.  (Return
3423          * ERROR_INVALID_NAME if there are wildcards in earlier path
3424          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
3425          * means "match one character", "??" seems to mean "match one
3426          * or two characters", "???" seems to mean "match one, two or
3427          * three characters", etc.  Windows will also try and match
3428          * the mangled "short name" of files, so 8 character patterns
3429          * with wildcards will show some surprising results.
3430          *
3431          * All the written documentation I can find says that '?' 
3432          * should only match one character, and doesn't mention '??',
3433          * '???' etc.  I'm going to assume that the strict behaviour
3434          * (ie '???' means three and only three characters) is the
3435          * correct one, because that lets me use fnmatch(3) rather
3436          * than mess around with regexes.
3437          */
3438
3439         find_handle.namelist = NULL;
3440         result = _wapi_io_scandir (dir_part, entry_part,
3441                                    &find_handle.namelist);
3442         
3443         if (result == 0) {
3444                 /* No files, which windows seems to call
3445                  * FILE_NOT_FOUND
3446                  */
3447                 mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
3448                 g_free (utf8_pattern);
3449                 g_free (entry_part);
3450                 g_free (dir_part);
3451                 return (INVALID_HANDLE_VALUE);
3452         }
3453         
3454         if (result < 0) {
3455                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
3456                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
3457                 g_free (utf8_pattern);
3458                 g_free (entry_part);
3459                 g_free (dir_part);
3460                 return (INVALID_HANDLE_VALUE);
3461         }
3462
3463         g_free (utf8_pattern);
3464         g_free (entry_part);
3465         
3466         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
3467
3468         find_handle.dir_part = dir_part;
3469         find_handle.num = result;
3470         find_handle.count = 0;
3471         
3472         handle = mono_w32handle_new (MONO_W32HANDLE_FIND, &find_handle);
3473         if (handle == INVALID_HANDLE_VALUE) {
3474                 g_warning ("%s: error creating find handle", __func__);
3475                 g_free (dir_part);
3476                 g_free (entry_part);
3477                 g_free (utf8_pattern);
3478                 mono_w32error_set_last (ERROR_GEN_FAILURE);
3479                 
3480                 return(INVALID_HANDLE_VALUE);
3481         }
3482
3483         if (handle != INVALID_HANDLE_VALUE &&
3484             !mono_w32file_find_next (handle, find_data)) {
3485                 mono_w32file_find_close (handle);
3486                 mono_w32error_set_last (ERROR_NO_MORE_FILES);
3487                 handle = INVALID_HANDLE_VALUE;
3488         }
3489
3490         return (handle);
3491 }
3492
3493 gboolean
3494 mono_w32file_find_next (gpointer handle, WIN32_FIND_DATA *find_data)
3495 {
3496         MonoW32HandleFind *find_handle;
3497         gboolean ok;
3498         struct stat buf, linkbuf;
3499         gint result;
3500         gchar *filename;
3501         gchar *utf8_filename, *utf8_basename;
3502         gunichar2 *utf16_basename;
3503         time_t create_time;
3504         glong bytes;
3505         gboolean ret = FALSE;
3506         
3507         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3508                                 (gpointer *)&find_handle);
3509         if(ok==FALSE) {
3510                 g_warning ("%s: error looking up find handle %p", __func__,
3511                            handle);
3512                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3513                 return(FALSE);
3514         }
3515
3516         mono_w32handle_lock_handle (handle);
3517         
3518 retry:
3519         if (find_handle->count >= find_handle->num) {
3520                 mono_w32error_set_last (ERROR_NO_MORE_FILES);
3521                 goto cleanup;
3522         }
3523
3524         /* stat next match */
3525
3526         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
3527
3528         result = _wapi_stat (filename, &buf);
3529         if (result == -1 && errno == ENOENT) {
3530                 /* Might be a dangling symlink */
3531                 result = _wapi_lstat (filename, &buf);
3532         }
3533         
3534         if (result != 0) {
3535                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
3536
3537                 g_free (filename);
3538                 goto retry;
3539         }
3540
3541 #ifndef __native_client__
3542         result = _wapi_lstat (filename, &linkbuf);
3543         if (result != 0) {
3544                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
3545
3546                 g_free (filename);
3547                 goto retry;
3548         }
3549 #endif
3550
3551         utf8_filename = mono_utf8_from_external (filename);
3552         if (utf8_filename == NULL) {
3553                 /* We couldn't turn this filename into utf8 (eg the
3554                  * encoding of the name wasn't convertible), so just
3555                  * ignore it.
3556                  */
3557                 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
3558                 
3559                 g_free (filename);
3560                 goto retry;
3561         }
3562         g_free (filename);
3563         
3564         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
3565         
3566         /* fill data block */
3567
3568         if (buf.st_mtime < buf.st_ctime)
3569                 create_time = buf.st_mtime;
3570         else
3571                 create_time = buf.st_ctime;
3572         
3573 #ifdef __native_client__
3574         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
3575 #else
3576         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
3577 #endif
3578
3579         time_t_to_filetime (create_time, &find_data->ftCreationTime);
3580         time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
3581         time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
3582
3583         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3584                 find_data->nFileSizeHigh = 0;
3585                 find_data->nFileSizeLow = 0;
3586         } else {
3587                 find_data->nFileSizeHigh = buf.st_size >> 32;
3588                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3589         }
3590
3591         find_data->dwReserved0 = 0;
3592         find_data->dwReserved1 = 0;
3593
3594         utf8_basename = _wapi_basename (utf8_filename);
3595         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
3596                                           NULL);
3597         if(utf16_basename==NULL) {
3598                 g_free (utf8_basename);
3599                 g_free (utf8_filename);
3600                 goto retry;
3601         }
3602         ret = TRUE;
3603         
3604         /* utf16 is 2 * utf8 */
3605         bytes *= 2;
3606
3607         memset (find_data->cFileName, '\0', (MAX_PATH*2));
3608
3609         /* Truncating a utf16 string like this might leave the last
3610          * gchar incomplete
3611          */
3612         memcpy (find_data->cFileName, utf16_basename,
3613                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3614
3615         find_data->cAlternateFileName [0] = 0;  /* not used */
3616
3617         g_free (utf8_basename);
3618         g_free (utf8_filename);
3619         g_free (utf16_basename);
3620
3621 cleanup:
3622         mono_w32handle_unlock_handle (handle);
3623         
3624         return(ret);
3625 }
3626
3627 gboolean
3628 mono_w32file_find_close (gpointer handle)
3629 {
3630         MonoW32HandleFind *find_handle;
3631         gboolean ok;
3632
3633         if (handle == NULL) {
3634                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3635                 return(FALSE);
3636         }
3637         
3638         ok=mono_w32handle_lookup (handle, MONO_W32HANDLE_FIND,
3639                                 (gpointer *)&find_handle);
3640         if(ok==FALSE) {
3641                 g_warning ("%s: error looking up find handle %p", __func__,
3642                            handle);
3643                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
3644                 return(FALSE);
3645         }
3646
3647         mono_w32handle_lock_handle (handle);
3648         
3649         g_strfreev (find_handle->namelist);
3650         g_free (find_handle->dir_part);
3651
3652         mono_w32handle_unlock_handle (handle);
3653         
3654         MONO_ENTER_GC_SAFE;
3655         mono_w32handle_unref (handle);
3656         MONO_EXIT_GC_SAFE;
3657         
3658         return(TRUE);
3659 }
3660
3661 gboolean
3662 mono_w32file_create_directory (const gunichar2 *name)
3663 {
3664         gchar *utf8_name;
3665         gint result;
3666         
3667         if (name == NULL) {
3668                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3669
3670                 mono_w32error_set_last (ERROR_INVALID_NAME);
3671                 return(FALSE);
3672         }
3673         
3674         utf8_name = mono_unicode_to_external (name);
3675         if (utf8_name == NULL) {
3676                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3677         
3678                 mono_w32error_set_last (ERROR_INVALID_NAME);
3679                 return FALSE;
3680         }
3681
3682         result = _wapi_mkdir (utf8_name, 0777);
3683
3684         if (result == 0) {
3685                 g_free (utf8_name);
3686                 return TRUE;
3687         }
3688
3689         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3690         g_free (utf8_name);
3691         return FALSE;
3692 }
3693
3694 gboolean
3695 mono_w32file_remove_directory (const gunichar2 *name)
3696 {
3697         gchar *utf8_name;
3698         gint result;
3699         
3700         if (name == NULL) {
3701                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3702
3703                 mono_w32error_set_last (ERROR_INVALID_NAME);
3704                 return(FALSE);
3705         }
3706
3707         utf8_name = mono_unicode_to_external (name);
3708         if (utf8_name == NULL) {
3709                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3710                 
3711                 mono_w32error_set_last (ERROR_INVALID_NAME);
3712                 return FALSE;
3713         }
3714
3715         result = _wapi_rmdir (utf8_name);
3716         if (result == -1) {
3717                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3718                 g_free (utf8_name);
3719                 
3720                 return(FALSE);
3721         }
3722         g_free (utf8_name);
3723
3724         return(TRUE);
3725 }
3726
3727 guint32
3728 mono_w32file_get_attributes (const gunichar2 *name)
3729 {
3730         gchar *utf8_name;
3731         struct stat buf, linkbuf;
3732         gint result;
3733         guint32 ret;
3734         
3735         if (name == NULL) {
3736                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3737
3738                 mono_w32error_set_last (ERROR_INVALID_NAME);
3739                 return(FALSE);
3740         }
3741         
3742         utf8_name = mono_unicode_to_external (name);
3743         if (utf8_name == NULL) {
3744                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3745
3746                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3747                 return (INVALID_FILE_ATTRIBUTES);
3748         }
3749
3750         result = _wapi_stat (utf8_name, &buf);
3751         if (result == -1 && errno == ENOENT) {
3752                 /* Might be a dangling symlink... */
3753                 result = _wapi_lstat (utf8_name, &buf);
3754         }
3755
3756         if (result != 0) {
3757                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3758                 g_free (utf8_name);
3759                 return (INVALID_FILE_ATTRIBUTES);
3760         }
3761
3762 #ifndef __native_client__
3763         result = _wapi_lstat (utf8_name, &linkbuf);
3764         if (result != 0) {
3765                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3766                 g_free (utf8_name);
3767                 return (INVALID_FILE_ATTRIBUTES);
3768         }
3769 #endif
3770         
3771 #ifdef __native_client__
3772         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3773 #else
3774         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3775 #endif
3776         
3777         g_free (utf8_name);
3778
3779         return(ret);
3780 }
3781
3782 gboolean
3783 mono_w32file_get_attributes_ex (const gunichar2 *name, MonoIOStat *stat)
3784 {
3785         gchar *utf8_name;
3786
3787         struct stat buf, linkbuf;
3788         gint result;
3789         
3790         if (name == NULL) {
3791                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3792
3793                 mono_w32error_set_last (ERROR_INVALID_NAME);
3794                 return(FALSE);
3795         }
3796
3797         utf8_name = mono_unicode_to_external (name);
3798         if (utf8_name == NULL) {
3799                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3800
3801                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3802                 return FALSE;
3803         }
3804
3805         result = _wapi_stat (utf8_name, &buf);
3806         if (result == -1 && errno == ENOENT) {
3807                 /* Might be a dangling symlink... */
3808                 result = _wapi_lstat (utf8_name, &buf);
3809         }
3810         
3811         if (result != 0) {
3812                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3813                 g_free (utf8_name);
3814                 return FALSE;
3815         }
3816
3817         result = _wapi_lstat (utf8_name, &linkbuf);
3818         if (result != 0) {
3819                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3820                 g_free (utf8_name);
3821                 return(FALSE);
3822         }
3823
3824         /* fill stat block */
3825
3826         stat->attributes = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3827         stat->creation_time = (((guint64) (buf.st_mtime < buf.st_ctime ? buf.st_mtime : buf.st_ctime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3828         stat->last_access_time = (((guint64) (buf.st_atime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3829         stat->last_write_time = (((guint64) (buf.st_mtime)) * 10 * 1000 * 1000) + 116444736000000000ULL;
3830         stat->length = (stat->attributes & FILE_ATTRIBUTE_DIRECTORY) ? 0 : buf.st_size;
3831
3832         g_free (utf8_name);
3833         return TRUE;
3834 }
3835
3836 gboolean
3837 mono_w32file_set_attributes (const gunichar2 *name, guint32 attrs)
3838 {
3839         /* FIXME: think of something clever to do on unix */
3840         gchar *utf8_name;
3841         struct stat buf;
3842         gint result;
3843
3844         /*
3845          * Currently we only handle one *internal* case, with a value that is
3846          * not standard: 0x80000000, which means `set executable bit'
3847          */
3848         
3849         if (name == NULL) {
3850                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3851
3852                 mono_w32error_set_last (ERROR_INVALID_NAME);
3853                 return(FALSE);
3854         }
3855
3856         utf8_name = mono_unicode_to_external (name);
3857         if (utf8_name == NULL) {
3858                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3859
3860                 mono_w32error_set_last (ERROR_INVALID_NAME);
3861                 return FALSE;
3862         }
3863
3864         result = _wapi_stat (utf8_name, &buf);
3865         if (result == -1 && errno == ENOENT) {
3866                 /* Might be a dangling symlink... */
3867                 result = _wapi_lstat (utf8_name, &buf);
3868         }
3869
3870         if (result != 0) {
3871                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3872                 g_free (utf8_name);
3873                 return FALSE;
3874         }
3875
3876         /* Contrary to the documentation, ms allows NORMAL to be
3877          * specified along with other attributes, so dont bother to
3878          * catch that case here.
3879          */
3880         if (attrs & FILE_ATTRIBUTE_READONLY) {
3881                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3882         } else {
3883                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3884         }
3885
3886         /* Ignore the other attributes for now */
3887
3888         if (attrs & 0x80000000){
3889                 mode_t exec_mask = 0;
3890
3891                 if ((buf.st_mode & S_IRUSR) != 0)
3892                         exec_mask |= S_IXUSR;
3893
3894                 if ((buf.st_mode & S_IRGRP) != 0)
3895                         exec_mask |= S_IXGRP;
3896
3897                 if ((buf.st_mode & S_IROTH) != 0)
3898                         exec_mask |= S_IXOTH;
3899
3900                 MONO_ENTER_GC_SAFE;
3901                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3902                 MONO_EXIT_GC_SAFE;
3903         }
3904         /* Don't bother to reset executable (might need to change this
3905          * policy)
3906          */
3907         
3908         g_free (utf8_name);
3909
3910         return(TRUE);
3911 }
3912
3913 guint32
3914 mono_w32file_get_cwd (guint32 length, gunichar2 *buffer)
3915 {
3916         gunichar2 *utf16_path;
3917         glong count;
3918         gsize bytes;
3919
3920 #ifdef __native_client__
3921         gchar *path = g_get_current_dir ();
3922         if (length < strlen(path) + 1 || path == NULL)
3923                 return 0;
3924         memcpy (buffer, path, strlen(path) + 1);
3925 #else
3926         if (getcwd ((gchar*)buffer, length) == NULL) {
3927                 if (errno == ERANGE) { /*buffer length is not big enough */ 
3928                         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*/
3929                         if (path == NULL)
3930                                 return 0;
3931                         utf16_path = mono_unicode_from_external (path, &bytes);
3932                         g_free (utf16_path);
3933                         g_free (path);
3934                         return (bytes/2)+1;
3935                 }
3936                 _wapi_set_last_error_from_errno ();
3937                 return 0;
3938         }
3939 #endif
3940
3941         utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3942         count = (bytes/2)+1;
3943         g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3944
3945         /* Add the terminator */
3946         memset (buffer, '\0', bytes+2);
3947         memcpy (buffer, utf16_path, bytes);
3948         
3949         g_free (utf16_path);
3950
3951         return count;
3952 }
3953
3954 gboolean
3955 mono_w32file_set_cwd (const gunichar2 *path)
3956 {
3957         gchar *utf8_path;
3958         gboolean result;
3959
3960         if (path == NULL) {
3961                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
3962                 return(FALSE);
3963         }
3964         
3965         utf8_path = mono_unicode_to_external (path);
3966         if (_wapi_chdir (utf8_path) != 0) {
3967                 _wapi_set_last_error_from_errno ();
3968                 result = FALSE;
3969         }
3970         else
3971                 result = TRUE;
3972
3973         g_free (utf8_path);
3974         return result;
3975 }
3976
3977 gboolean
3978 mono_w32file_create_pipe (gpointer *readpipe, gpointer *writepipe, guint32 size)
3979 {
3980         MonoW32HandleFile pipe_read_handle = {0};
3981         MonoW32HandleFile pipe_write_handle = {0};
3982         gpointer read_handle;
3983         gpointer write_handle;
3984         gint filedes[2];
3985         gint ret;
3986         
3987         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3988
3989         MONO_ENTER_GC_SAFE;
3990         ret=pipe (filedes);
3991         MONO_EXIT_GC_SAFE;
3992         if(ret==-1) {
3993                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3994                            strerror (errno));
3995                 
3996                 _wapi_set_last_error_from_errno ();
3997                 return(FALSE);
3998         }
3999
4000         if (filedes[0] >= mono_w32handle_fd_reserve ||
4001             filedes[1] >= mono_w32handle_fd_reserve) {
4002                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
4003
4004                 mono_w32error_set_last (ERROR_TOO_MANY_OPEN_FILES);
4005                 
4006                 MONO_ENTER_GC_SAFE;
4007                 close (filedes[0]);
4008                 close (filedes[1]);
4009                 MONO_EXIT_GC_SAFE;
4010                 
4011                 return(FALSE);
4012         }
4013         
4014         /* filedes[0] is open for reading, filedes[1] for writing */
4015
4016         pipe_read_handle.fd = filedes [0];
4017         pipe_read_handle.fileaccess = GENERIC_READ;
4018         read_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[0],
4019                                            &pipe_read_handle);
4020         if (read_handle == INVALID_HANDLE_VALUE) {
4021                 g_warning ("%s: error creating pipe read handle", __func__);
4022                 MONO_ENTER_GC_SAFE;
4023                 close (filedes[0]);
4024                 close (filedes[1]);
4025                 MONO_EXIT_GC_SAFE;
4026                 mono_w32error_set_last (ERROR_GEN_FAILURE);
4027                 
4028                 return(FALSE);
4029         }
4030         
4031         pipe_write_handle.fd = filedes [1];
4032         pipe_write_handle.fileaccess = GENERIC_WRITE;
4033         write_handle = mono_w32handle_new_fd (MONO_W32HANDLE_PIPE, filedes[1],
4034                                             &pipe_write_handle);
4035         if (write_handle == INVALID_HANDLE_VALUE) {
4036                 g_warning ("%s: error creating pipe write handle", __func__);
4037
4038                 MONO_ENTER_GC_SAFE;
4039                 mono_w32handle_unref (read_handle);
4040                 
4041                 close (filedes[0]);
4042                 close (filedes[1]);
4043                 MONO_EXIT_GC_SAFE;
4044                 mono_w32error_set_last (ERROR_GEN_FAILURE);
4045                 
4046                 return(FALSE);
4047         }
4048         
4049         *readpipe = read_handle;
4050         *writepipe = write_handle;
4051
4052         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
4053                    __func__, read_handle, write_handle);
4054
4055         return(TRUE);
4056 }
4057
4058 #ifdef HAVE_GETFSSTAT
4059 /* Darwin has getfsstat */
4060 gint32
4061 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4062 {
4063         struct statfs *stats;
4064         gint size, n, i;
4065         gunichar2 *dir;
4066         glong length, total = 0;
4067         gint syscall_res;
4068
4069         MONO_ENTER_GC_SAFE;
4070         n = getfsstat (NULL, 0, MNT_NOWAIT);
4071         MONO_EXIT_GC_SAFE;
4072         if (n == -1)
4073                 return 0;
4074         size = n * sizeof (struct statfs);
4075         stats = (struct statfs *) g_malloc (size);
4076         if (stats == NULL)
4077                 return 0;
4078         MONO_ENTER_GC_SAFE;
4079         syscall_res = getfsstat (stats, size, MNT_NOWAIT);
4080         MONO_EXIT_GC_SAFE;
4081         if (syscall_res == -1){
4082                 g_free (stats);
4083                 return 0;
4084         }
4085         for (i = 0; i < n; i++){
4086                 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
4087                 if (total + length < len){
4088                         memcpy (buf + total, dir, sizeof (gunichar2) * length);
4089                         buf [total+length] = 0;
4090                 } 
4091                 g_free (dir);
4092                 total += length + 1;
4093         }
4094         if (total < len)
4095                 buf [total] = 0;
4096         total++;
4097         g_free (stats);
4098         return total;
4099 }
4100 #else
4101 /* In-place octal sequence replacement */
4102 static void
4103 unescape_octal (gchar *str)
4104 {
4105         gchar *rptr;
4106         gchar *wptr;
4107
4108         if (str == NULL)
4109                 return;
4110
4111         rptr = wptr = str;
4112         while (*rptr != '\0') {
4113                 if (*rptr == '\\') {
4114                         gchar c;
4115                         rptr++;
4116                         c = (*(rptr++) - '0') << 6;
4117                         c += (*(rptr++) - '0') << 3;
4118                         c += *(rptr++) - '0';
4119                         *wptr++ = c;
4120                 } else if (wptr != rptr) {
4121                         *wptr++ = *rptr++;
4122                 } else {
4123                         rptr++; wptr++;
4124                 }
4125         }
4126         *wptr = '\0';
4127 }
4128 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
4129
4130 #if __linux__
4131 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
4132 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
4133 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
4134
4135 typedef struct 
4136 {
4137         glong total;
4138         guint32 buffer_index;
4139         guint32 mountpoint_index;
4140         guint32 field_number;
4141         guint32 allocated_size;
4142         guint32 fsname_index;
4143         guint32 fstype_index;
4144         gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
4145         gchar *mountpoint_allocated;
4146         gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
4147         gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
4148         gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
4149         ssize_t nbytes;
4150         gchar delimiter;
4151         gboolean check_mount_source;
4152 } LinuxMountInfoParseState;
4153
4154 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4155 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4156 static void append_to_mountpoint (LinuxMountInfoParseState *state);
4157 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
4158
4159 gint32
4160 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4161 {
4162         gint fd;
4163         gint32 ret = 0;
4164         LinuxMountInfoParseState state;
4165         gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
4166
4167         memset (buf, 0, len * sizeof (gunichar2));
4168         MONO_ENTER_GC_SAFE;
4169         fd = open ("/proc/self/mountinfo", O_RDONLY);
4170         MONO_EXIT_GC_SAFE;
4171         if (fd != -1)
4172                 parser = GetLogicalDriveStrings_MountInfo;
4173         else {
4174                 MONO_ENTER_GC_SAFE;
4175                 fd = open ("/proc/mounts", O_RDONLY);
4176                 MONO_EXIT_GC_SAFE;
4177                 if (fd != -1)
4178                         parser = GetLogicalDriveStrings_Mounts;
4179         }
4180
4181         if (!parser) {
4182                 ret = GetLogicalDriveStrings_Mtab (len, buf);
4183                 goto done_and_out;
4184         }
4185
4186         memset (&state, 0, sizeof (LinuxMountInfoParseState));
4187         state.field_number = 1;
4188         state.delimiter = ' ';
4189
4190         while (1) {
4191                 MONO_ENTER_GC_SAFE;
4192                 state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER);
4193                 MONO_EXIT_GC_SAFE;
4194                 if (!(state.nbytes > 0))
4195                         break;
4196                 state.buffer_index = 0;
4197
4198                 while ((*parser)(len, buf, &state)) {
4199                         if (state.buffer [state.buffer_index] == '\n') {
4200                                 gboolean quit = add_drive_string (len, buf, &state);
4201                                 state.field_number = 1;
4202                                 state.buffer_index++;
4203                                 if (state.mountpoint_allocated) {
4204                                         g_free (state.mountpoint_allocated);
4205                                         state.mountpoint_allocated = NULL;
4206                                 }
4207                                 if (quit) {
4208                                         ret = state.total;
4209                                         goto done_and_out;
4210                                 }
4211                         }
4212                 }
4213         };
4214         ret = state.total;
4215
4216   done_and_out:
4217         if (fd != -1) {
4218                 MONO_ENTER_GC_SAFE;
4219                 close (fd);
4220                 MONO_EXIT_GC_SAFE;
4221         }
4222         return ret;
4223 }
4224
4225 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4226 {
4227         gchar *ptr;
4228
4229         if (state->field_number == 1)
4230                 state->check_mount_source = TRUE;
4231
4232         while (state->buffer_index < (guint32)state->nbytes) {
4233                 if (state->buffer [state->buffer_index] == state->delimiter) {
4234                         state->field_number++;
4235                         switch (state->field_number) {
4236                                 case 2:
4237                                         state->mountpoint_index = 0;
4238                                         break;
4239
4240                                 case 3:
4241                                         if (state->mountpoint_allocated)
4242                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
4243                                         else
4244                                                 state->mountpoint [state->mountpoint_index] = 0;
4245                                         break;
4246
4247                                 default:
4248                                         ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
4249                                         if (ptr)
4250                                                 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
4251                                         else
4252                                                 state->buffer_index = state->nbytes;
4253                                         return TRUE;
4254                         }
4255                         state->buffer_index++;
4256                         continue;
4257                 } else if (state->buffer [state->buffer_index] == '\n')
4258                         return TRUE;
4259
4260                 switch (state->field_number) {
4261                         case 1:
4262                                 if (state->check_mount_source) {
4263                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
4264                                                 /* We can ignore the rest, it's a device
4265                                                  * path */
4266                                                 state->check_mount_source = FALSE;
4267                                                 state->fsname [state->fsname_index++] = '/';
4268                                                 break;
4269                                         }
4270                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4271                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
4272                                 }
4273                                 break;
4274
4275                         case 2:
4276                                 append_to_mountpoint (state);
4277                                 break;
4278
4279                         case 3:
4280                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4281                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
4282                                 break;
4283                 }
4284
4285                 state->buffer_index++;
4286         }
4287
4288         return FALSE;
4289 }
4290
4291 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4292 {
4293         while (state->buffer_index < (guint32)state->nbytes) {
4294                 if (state->buffer [state->buffer_index] == state->delimiter) {
4295                         state->field_number++;
4296                         switch (state->field_number) {
4297                                 case 5:
4298                                         state->mountpoint_index = 0;
4299                                         break;
4300
4301                                 case 6:
4302                                         if (state->mountpoint_allocated)
4303                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
4304                                         else
4305                                                 state->mountpoint [state->mountpoint_index] = 0;
4306                                         break;
4307
4308                                 case 7:
4309                                         state->delimiter = '-';
4310                                         break;
4311
4312                                 case 8:
4313                                         state->delimiter = ' ';
4314                                         break;
4315
4316                                 case 10:
4317                                         state->check_mount_source = TRUE;
4318                                         break;
4319                         }
4320                         state->buffer_index++;
4321                         continue;
4322                 } else if (state->buffer [state->buffer_index] == '\n')
4323                         return TRUE;
4324
4325                 switch (state->field_number) {
4326                         case 5:
4327                                 append_to_mountpoint (state);
4328                                 break;
4329
4330                         case 9:
4331                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4332                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
4333                                 break;
4334
4335                         case 10:
4336                                 if (state->check_mount_source) {
4337                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
4338                                                 /* We can ignore the rest, it's a device
4339                                                  * path */
4340                                                 state->check_mount_source = FALSE;
4341                                                 state->fsname [state->fsname_index++] = '/';
4342                                                 break;
4343                                         }
4344                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
4345                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
4346                                 }
4347                                 break;
4348                 }
4349
4350                 state->buffer_index++;
4351         }
4352
4353         return FALSE;
4354 }
4355
4356 static void
4357 append_to_mountpoint (LinuxMountInfoParseState *state)
4358 {
4359         gchar ch = state->buffer [state->buffer_index];
4360         if (state->mountpoint_allocated) {
4361                 if (state->mountpoint_index >= state->allocated_size) {
4362                         guint32 newsize = (state->allocated_size << 1) + 1;
4363                         gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
4364
4365                         memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
4366                         g_free (state->mountpoint_allocated);
4367                         state->mountpoint_allocated = newbuf;
4368                         state->allocated_size = newsize;
4369                 }
4370                 state->mountpoint_allocated [state->mountpoint_index++] = ch;
4371         } else {
4372                 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
4373                         state->allocated_size = (state->mountpoint_index << 1) + 1;
4374                         state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
4375                         memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
4376                         state->mountpoint_allocated [state->mountpoint_index++] = ch;
4377                 } else
4378                         state->mountpoint [state->mountpoint_index++] = ch;
4379         }
4380 }
4381
4382 static gboolean
4383 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
4384 {
4385         gboolean quit = FALSE;
4386         gboolean ignore_entry;
4387
4388         if (state->fsname_index == 1 && state->fsname [0] == '/')
4389                 ignore_entry = FALSE;
4390         else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
4391                 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
4392                 /* Don't ignore overlayfs and aufs - these might be used on Docker
4393                  * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
4394                 ignore_entry = FALSE;
4395         } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
4396                 ignore_entry = TRUE;
4397         } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
4398                 /* Ignore GNOME's gvfs */
4399                 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
4400                         ignore_entry = TRUE;
4401                 else
4402                         ignore_entry = FALSE;
4403         } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
4404                 ignore_entry = FALSE;
4405         else
4406                 ignore_entry = TRUE;
4407
4408         if (!ignore_entry) {
4409                 gunichar2 *dir;
4410                 glong length;
4411                 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
4412
4413                 unescape_octal (mountpoint);
4414                 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
4415                 if (state->total + length + 1 > len) {
4416                         quit = TRUE;
4417                         state->total = len * 2;
4418                 } else {
4419                         length++;
4420                         memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
4421                         state->total += length;
4422                 }
4423                 g_free (dir);
4424         }
4425         state->fsname_index = 0;
4426         state->fstype_index = 0;
4427
4428         return quit;
4429 }
4430 #else
4431 gint32
4432 mono_w32file_get_logical_drive (guint32 len, gunichar2 *buf)
4433 {
4434         return GetLogicalDriveStrings_Mtab (len, buf);
4435 }
4436 #endif
4437 static gint32
4438 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
4439 {
4440         FILE *fp;
4441         gunichar2 *ptr, *dir;
4442         glong length, total = 0;
4443         gchar buffer [512];
4444         gchar **splitted;
4445
4446         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
4447         buf [0] = '/';
4448         buf [1] = 0;
4449         buf [2] = 0;
4450
4451         /* Sigh, mntent and friends don't work well.
4452          * It stops on the first line that doesn't begin with a '/'.
4453          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
4454         MONO_ENTER_GC_SAFE;
4455         fp = fopen ("/etc/mtab", "rt");
4456         MONO_EXIT_GC_SAFE;
4457         if (fp == NULL) {
4458                 MONO_ENTER_GC_SAFE;
4459                 fp = fopen ("/etc/mnttab", "rt");
4460                 MONO_EXIT_GC_SAFE;
4461                 if (fp == NULL)
4462                         return 1;
4463         }
4464
4465         ptr = buf;
4466         while (1) {
4467                 gchar *fgets_res;
4468                 MONO_ENTER_GC_SAFE;
4469                 fgets_res = fgets (buffer, 512, fp);
4470                 MONO_EXIT_GC_SAFE;
4471                 if (!fgets_res)
4472                         break;
4473                 if (*buffer != '/')
4474                         continue;
4475
4476                 splitted = g_strsplit (buffer, " ", 0);
4477                 if (!*splitted || !*(splitted + 1)) {
4478                         g_strfreev (splitted);
4479                         continue;
4480                 }
4481
4482                 unescape_octal (*(splitted + 1));
4483                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
4484                 g_strfreev (splitted);
4485                 if (total + length + 1 > len) {
4486                         MONO_ENTER_GC_SAFE;
4487                         fclose (fp);
4488                         MONO_EXIT_GC_SAFE;
4489                         g_free (dir);
4490                         return len * 2; /* guess */
4491                 }
4492
4493                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
4494                 g_free (dir);
4495                 total += length + 1;
4496         }
4497
4498         MONO_ENTER_GC_SAFE;
4499         fclose (fp);
4500         MONO_EXIT_GC_SAFE;
4501         return total;
4502 /* Commented out, does not work with my mtab!!! - Gonz */
4503 #ifdef NOTENABLED /* HAVE_MNTENT_H */
4504 {
4505         FILE *fp;
4506         struct mntent *mnt;
4507         gunichar2 *ptr, *dir;
4508         glong len, total = 0;
4509         
4510
4511         MONO_ENTER_GC_SAFE;
4512         fp = setmntent ("/etc/mtab", "rt");
4513         MONO_EXIT_GC_SAFE;
4514         if (fp == NULL) {
4515                 MONO_ENTER_GC_SAFE;
4516                 fp = setmntent ("/etc/mnttab", "rt");
4517                 MONO_EXIT_GC_SAFE;
4518                 if (fp == NULL)
4519                         return;
4520         }
4521
4522         ptr = buf;
4523         while (1) {
4524                 MONO_ENTER_GC_SAFE;
4525                 mnt = getmntent (fp);
4526                 MONO_EXIT_GC_SAFE;
4527                 if (mnt == NULL)
4528                         break;
4529                 g_print ("GOT %s\n", mnt->mnt_dir);
4530                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
4531                 if (total + len + 1 > len) {
4532                         MONO_ENTER_GC_SAFE;
4533                         endmntent (fp);
4534                         MONO_EXIT_GC_SAFE;
4535                         return len * 2; /* guess */
4536                 }
4537
4538                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
4539                 g_free (dir);
4540                 total += len + 1;
4541         }
4542
4543         MONO_ENTER_GC_SAFE;
4544         endmntent (fp);
4545         MONO_EXIT_GC_SAFE;
4546         return total;
4547 }
4548 #endif
4549 }
4550 #endif
4551
4552 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
4553 gboolean
4554 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)
4555 {
4556 #ifdef HAVE_STATVFS
4557         struct statvfs fsstat;
4558 #elif defined(HAVE_STATFS)
4559         struct statfs fsstat;
4560 #endif
4561         gboolean isreadonly;
4562         gchar *utf8_path_name;
4563         gint ret;
4564         unsigned long block_size;
4565
4566         if (path_name == NULL) {
4567                 utf8_path_name = g_strdup (g_get_current_dir());
4568                 if (utf8_path_name == NULL) {
4569                         mono_w32error_set_last (ERROR_DIRECTORY);
4570                         return(FALSE);
4571                 }
4572         }
4573         else {
4574                 utf8_path_name = mono_unicode_to_external (path_name);
4575                 if (utf8_path_name == NULL) {
4576                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4577
4578                         mono_w32error_set_last (ERROR_INVALID_NAME);
4579                         return(FALSE);
4580                 }
4581         }
4582
4583         do {
4584 #ifdef HAVE_STATVFS
4585                 MONO_ENTER_GC_SAFE;
4586                 ret = statvfs (utf8_path_name, &fsstat);
4587                 MONO_EXIT_GC_SAFE;
4588                 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
4589                 block_size = fsstat.f_frsize;
4590 #elif defined(HAVE_STATFS)
4591                 MONO_ENTER_GC_SAFE;
4592                 ret = statfs (utf8_path_name, &fsstat);
4593                 MONO_EXIT_GC_SAFE;
4594 #if defined (MNT_RDONLY)
4595                 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
4596 #elif defined (MS_RDONLY)
4597                 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
4598 #endif
4599                 block_size = fsstat.f_bsize;
4600 #endif
4601         } while(ret == -1 && errno == EINTR);
4602
4603         g_free(utf8_path_name);
4604
4605         if (ret == -1) {
4606                 _wapi_set_last_error_from_errno ();
4607                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
4608                 return(FALSE);
4609         }
4610
4611         /* total number of free bytes for non-root */
4612         if (free_bytes_avail != NULL) {
4613                 if (isreadonly) {
4614                         *free_bytes_avail = 0;
4615                 }
4616                 else {
4617                         *free_bytes_avail = block_size * (guint64)fsstat.f_bavail;
4618                 }
4619         }
4620
4621         /* total number of bytes available for non-root */
4622         if (total_number_of_bytes != NULL) {
4623                 *total_number_of_bytes = block_size * (guint64)fsstat.f_blocks;
4624         }
4625
4626         /* total number of bytes available for root */
4627         if (total_number_of_free_bytes != NULL) {
4628                 if (isreadonly) {
4629                         *total_number_of_free_bytes = 0;
4630                 }
4631                 else {
4632                         *total_number_of_free_bytes = block_size * (guint64)fsstat.f_bfree;
4633                 }
4634         }
4635         
4636         return(TRUE);
4637 }
4638 #else
4639 gboolean
4640 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)
4641 {
4642         if (free_bytes_avail != NULL) {
4643                 *free_bytes_avail = (guint64) -1;
4644         }
4645
4646         if (total_number_of_bytes != NULL) {
4647                 *total_number_of_bytes = (guint64) -1;
4648         }
4649
4650         if (total_number_of_free_bytes != NULL) {
4651                 *total_number_of_free_bytes = (guint64) -1;
4652         }
4653
4654         return(TRUE);
4655 }
4656 #endif
4657
4658 /*
4659  * General Unix support
4660  */
4661 typedef struct {
4662         guint32 drive_type;
4663 #if __linux__
4664         const long fstypeid;
4665 #endif
4666         const gchar* fstype;
4667 } _wapi_drive_type;
4668
4669 static _wapi_drive_type _wapi_drive_types[] = {
4670 #if PLATFORM_MACOSX
4671         { DRIVE_REMOTE, "afp" },
4672         { DRIVE_REMOTE, "autofs" },
4673         { DRIVE_CDROM, "cddafs" },
4674         { DRIVE_CDROM, "cd9660" },
4675         { DRIVE_RAMDISK, "devfs" },
4676         { DRIVE_FIXED, "exfat" },
4677         { DRIVE_RAMDISK, "fdesc" },
4678         { DRIVE_REMOTE, "ftp" },
4679         { DRIVE_FIXED, "hfs" },
4680         { DRIVE_FIXED, "msdos" },
4681         { DRIVE_REMOTE, "nfs" },
4682         { DRIVE_FIXED, "ntfs" },
4683         { DRIVE_REMOTE, "smbfs" },
4684         { DRIVE_FIXED, "udf" },
4685         { DRIVE_REMOTE, "webdav" },
4686         { DRIVE_UNKNOWN, NULL }
4687 #elif __linux__
4688         { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
4689         { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
4690         { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
4691         { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
4692         { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
4693         { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
4694         { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
4695         { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
4696         { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
4697         { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
4698         { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
4699         { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4700         { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4701         { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4702         { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4703         { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4704         { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4705         { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4706         { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4707         { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4708         { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4709         { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4710         { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4711         { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4712         { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4713         { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4714         { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4715         { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4716         { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4717         { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4718         { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4719         { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4720         { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4721         { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4722         { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4723         { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4724         { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4725         { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4726         { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4727         { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4728         { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4729         { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4730         { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4731         { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4732         { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4733         { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4734         { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4735         { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4736         { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4737         { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4738         { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4739         { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4740         { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4741         { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4742         { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4743         { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4744         { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4745         { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4746         { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4747         { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4748         { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4749         { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4750         { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4751         { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4752         { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4753         { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4754         { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4755         { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4756         { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4757         { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4758         { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4759         { DRIVE_UNKNOWN, 0, NULL}
4760 #else
4761         { DRIVE_RAMDISK, "ramfs"      },
4762         { DRIVE_RAMDISK, "tmpfs"      },
4763         { DRIVE_RAMDISK, "proc"       },
4764         { DRIVE_RAMDISK, "sysfs"      },
4765         { DRIVE_RAMDISK, "debugfs"    },
4766         { DRIVE_RAMDISK, "devpts"     },
4767         { DRIVE_RAMDISK, "securityfs" },
4768         { DRIVE_CDROM,   "iso9660"    },
4769         { DRIVE_FIXED,   "ext2"       },
4770         { DRIVE_FIXED,   "ext3"       },
4771         { DRIVE_FIXED,   "ext4"       },
4772         { DRIVE_FIXED,   "sysv"       },
4773         { DRIVE_FIXED,   "reiserfs"   },
4774         { DRIVE_FIXED,   "ufs"        },
4775         { DRIVE_FIXED,   "vfat"       },
4776         { DRIVE_FIXED,   "msdos"      },
4777         { DRIVE_FIXED,   "udf"        },
4778         { DRIVE_FIXED,   "hfs"        },
4779         { DRIVE_FIXED,   "hpfs"       },
4780         { DRIVE_FIXED,   "qnx4"       },
4781         { DRIVE_FIXED,   "ntfs"       },
4782         { DRIVE_FIXED,   "ntfs-3g"    },
4783         { DRIVE_REMOTE,  "smbfs"      },
4784         { DRIVE_REMOTE,  "fuse"       },
4785         { DRIVE_REMOTE,  "nfs"        },
4786         { DRIVE_REMOTE,  "nfs4"       },
4787         { DRIVE_REMOTE,  "cifs"       },
4788         { DRIVE_REMOTE,  "ncpfs"      },
4789         { DRIVE_REMOTE,  "coda"       },
4790         { DRIVE_REMOTE,  "afs"        },
4791         { DRIVE_UNKNOWN, NULL         }
4792 #endif
4793 };
4794
4795 #if __linux__
4796 static guint32 _wapi_get_drive_type(long f_type)
4797 {
4798         _wapi_drive_type *current;
4799
4800         current = &_wapi_drive_types[0];
4801         while (current->drive_type != DRIVE_UNKNOWN) {
4802                 if (current->fstypeid == f_type)
4803                         return current->drive_type;
4804                 current++;
4805         }
4806
4807         return DRIVE_UNKNOWN;
4808 }
4809 #else
4810 static guint32 _wapi_get_drive_type(const gchar* fstype)
4811 {
4812         _wapi_drive_type *current;
4813
4814         current = &_wapi_drive_types[0];
4815         while (current->drive_type != DRIVE_UNKNOWN) {
4816                 if (strcmp (current->fstype, fstype) == 0)
4817                         break;
4818
4819                 current++;
4820         }
4821         
4822         return current->drive_type;
4823 }
4824 #endif
4825
4826 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4827 static guint32
4828 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4829 {
4830         struct statfs buf;
4831         gint res;
4832
4833         MONO_ENTER_GC_SAFE;
4834         res = statfs (utf8_root_path_name, &buf);
4835         MONO_EXIT_GC_SAFE;
4836         if (res == -1)
4837                 return DRIVE_UNKNOWN;
4838 #if PLATFORM_MACOSX
4839         return _wapi_get_drive_type (buf.f_fstypename);
4840 #else
4841         return _wapi_get_drive_type (buf.f_type);
4842 #endif
4843 }
4844 #else
4845 static guint32
4846 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4847 {
4848         guint32 drive_type;
4849         FILE *fp;
4850         gchar buffer [512];
4851         gchar **splitted;
4852
4853         MONO_ENTER_GC_SAFE;
4854         fp = fopen ("/etc/mtab", "rt");
4855         MONO_EXIT_GC_SAFE;
4856         if (fp == NULL) {
4857                 MONO_ENTER_GC_SAFE;
4858                 fp = fopen ("/etc/mnttab", "rt");
4859                 MONO_EXIT_GC_SAFE;
4860                 if (fp == NULL) 
4861                         return(DRIVE_UNKNOWN);
4862         }
4863
4864         drive_type = DRIVE_NO_ROOT_DIR;
4865         while (1) {
4866                 gchar *fgets_res;
4867                 MONO_ENTER_GC_SAFE;
4868                 fgets_res = fgets (buffer, 512, fp);
4869                 MONO_EXIT_GC_SAFE;
4870                 if (fgets_res == NULL)
4871                         break;
4872                 splitted = g_strsplit (buffer, " ", 0);
4873                 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4874                         g_strfreev (splitted);
4875                         continue;
4876                 }
4877
4878                 /* compare given root_path_name with the one from mtab, 
4879                   if length of utf8_root_path_name is zero it must be the root dir */
4880                 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4881                     (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4882                         drive_type = _wapi_get_drive_type (*(splitted + 2));
4883                         /* it is possible this path might be mounted again with
4884                            a known type...keep looking */
4885                         if (drive_type != DRIVE_UNKNOWN) {
4886                                 g_strfreev (splitted);
4887                                 break;
4888                         }
4889                 }
4890
4891                 g_strfreev (splitted);
4892         }
4893
4894         MONO_ENTER_GC_SAFE;
4895         fclose (fp);
4896         MONO_EXIT_GC_SAFE;
4897         return drive_type;
4898 }
4899 #endif
4900
4901 guint32
4902 mono_w32file_get_drive_type(const gunichar2 *root_path_name)
4903 {
4904         gchar *utf8_root_path_name;
4905         guint32 drive_type;
4906
4907         if (root_path_name == NULL) {
4908                 utf8_root_path_name = g_strdup (g_get_current_dir());
4909                 if (utf8_root_path_name == NULL) {
4910                         return(DRIVE_NO_ROOT_DIR);
4911                 }
4912         }
4913         else {
4914                 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4915                 if (utf8_root_path_name == NULL) {
4916                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4917                         return(DRIVE_NO_ROOT_DIR);
4918                 }
4919                 
4920                 /* strip trailing slash for compare below */
4921                 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4922                         utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4923                 }
4924         }
4925         drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4926         g_free (utf8_root_path_name);
4927
4928         return (drive_type);
4929 }
4930
4931 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4932 static gchar*
4933 get_fstypename (gchar *utfpath)
4934 {
4935 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4936         struct statfs stat;
4937 #if __linux__
4938         _wapi_drive_type *current;
4939 #endif
4940         gint statfs_res;
4941         MONO_ENTER_GC_SAFE;
4942         statfs_res = statfs (utfpath, &stat);
4943         MONO_EXIT_GC_SAFE;
4944         if (statfs_res == -1)
4945                 return NULL;
4946 #if PLATFORM_MACOSX
4947         return g_strdup (stat.f_fstypename);
4948 #else
4949         current = &_wapi_drive_types[0];
4950         while (current->drive_type != DRIVE_UNKNOWN) {
4951                 if (stat.f_type == current->fstypeid)
4952                         return g_strdup (current->fstype);
4953                 current++;
4954         }
4955         return NULL;
4956 #endif
4957 #else
4958         return NULL;
4959 #endif
4960 }
4961
4962 /* Linux has struct statfs which has a different layout */
4963 gboolean
4964 mono_w32file_get_volume_information (const gunichar2 *path, gunichar2 *volumename, gint volumesize, gint *outserial, gint *maxcomp, gint *fsflags, gunichar2 *fsbuffer, gint fsbuffersize)
4965 {
4966         gchar *utfpath;
4967         gchar *fstypename;
4968         gboolean status = FALSE;
4969         glong len;
4970         
4971         // We only support getting the file system type
4972         if (fsbuffer == NULL)
4973                 return 0;
4974         
4975         utfpath = mono_unicode_to_external (path);
4976         if ((fstypename = get_fstypename (utfpath)) != NULL){
4977                 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4978                 if (ret != NULL && len < fsbuffersize){
4979                         memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4980                         fsbuffer [len] = 0;
4981                         status = TRUE;
4982                 }
4983                 if (ret != NULL)
4984                         g_free (ret);
4985                 g_free (fstypename);
4986         }
4987         g_free (utfpath);
4988         return status;
4989 }
4990 #endif
4991
4992 static gboolean
4993 LockFile (gpointer handle, guint32 offset_low, guint32 offset_high, guint32 length_low, guint32 length_high)
4994 {
4995         MonoW32HandleFile *file_handle;
4996         off_t offset, length;
4997
4998         if (!mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE, (gpointer *)&file_handle)) {
4999                 g_warning ("%s: error looking up file handle %p", __func__, handle);
5000                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
5001                 return FALSE;
5002         }
5003
5004         if (!(file_handle->fileaccess & GENERIC_READ) && !(file_handle->fileaccess & GENERIC_WRITE) && !(file_handle->fileaccess & GENERIC_ALL)) {
5005                 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);
5006                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
5007                 return FALSE;
5008         }
5009
5010 #ifdef HAVE_LARGE_FILE_SUPPORT
5011         offset = ((gint64)offset_high << 32) | offset_low;
5012         length = ((gint64)length_high << 32) | length_low;
5013
5014         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Locking handle %p, offset %lld, length %lld", __func__, handle, offset, length);
5015 #else
5016         if (offset_high > 0 || length_high > 0) {
5017                 mono_w32error_set_last (ERROR_INVALID_PARAMETER);
5018                 return FALSE;
5019         }
5020         offset = offset_low;
5021         length = length_low;
5022
5023         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Locking handle %p, offset %ld, length %ld", __func__, handle, offset, length);
5024 #endif
5025
5026         return _wapi_lock_file_region (GPOINTER_TO_UINT(handle), offset, length);
5027 }
5028
5029 static gboolean
5030 UnlockFile (gpointer handle, guint32 offset_low, guint32 offset_high, guint32 length_low, guint32 length_high)
5031 {
5032         MonoW32HandleFile *file_handle;
5033         off_t offset, length;
5034
5035         if (!mono_w32handle_lookup (handle, MONO_W32HANDLE_FILE, (gpointer *)&file_handle)) {
5036                 g_warning ("%s: error looking up file handle %p", __func__, handle);
5037                 mono_w32error_set_last (ERROR_INVALID_HANDLE);
5038                 return FALSE;
5039         }
5040
5041         if (!(file_handle->fileaccess & GENERIC_READ) && !(file_handle->fileaccess & GENERIC_WRITE) && !(file_handle->fileaccess & GENERIC_ALL)) {
5042                 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);
5043                 mono_w32error_set_last (ERROR_ACCESS_DENIED);
5044                 return FALSE;
5045         }
5046
5047 #ifdef HAVE_LARGE_FILE_SUPPORT
5048         offset = ((gint64)offset_high << 32) | offset_low;
5049         length = ((gint64)length_high << 32) | length_low;
5050
5051         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unlocking handle %p, offset %lld, length %lld", __func__, handle, offset, length);
5052 #else
5053         offset = offset_low;
5054         length = length_low;
5055
5056         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Unlocking handle %p, offset %ld, length %ld", __func__, handle, offset, length);
5057 #endif
5058
5059         return _wapi_unlock_file_region (GPOINTER_TO_UINT(handle), offset, length);
5060 }
5061
5062 void
5063 mono_w32file_init (void)
5064 {
5065         mono_coop_mutex_init (&stdhandle_mutex);
5066         mono_coop_mutex_init (&file_share_mutex);
5067
5068         mono_w32handle_register_ops (MONO_W32HANDLE_FILE,    &_wapi_file_ops);
5069         mono_w32handle_register_ops (MONO_W32HANDLE_CONSOLE, &_wapi_console_ops);
5070         mono_w32handle_register_ops (MONO_W32HANDLE_FIND,    &_wapi_find_ops);
5071         mono_w32handle_register_ops (MONO_W32HANDLE_PIPE,    &_wapi_pipe_ops);
5072
5073 /*      mono_w32handle_register_capabilities (MONO_W32HANDLE_FILE, */
5074 /*                                          MONO_W32HANDLE_CAP_WAIT); */
5075 /*      mono_w32handle_register_capabilities (MONO_W32HANDLE_CONSOLE, */
5076 /*                                          MONO_W32HANDLE_CAP_WAIT); */
5077
5078         if (g_getenv ("MONO_STRICT_IO_EMULATION"))
5079                 lock_while_writing = TRUE;
5080 }
5081
5082 void
5083 mono_w32file_cleanup (void)
5084 {
5085         mono_coop_mutex_destroy (&file_share_mutex);
5086
5087         if (file_share_table)
5088                 g_hash_table_destroy (file_share_table);
5089 }
5090
5091 gboolean
5092 mono_w32file_move (gunichar2 *path, gunichar2 *dest, gint32 *error)
5093 {
5094         gboolean result;
5095
5096         result = MoveFile (path, dest);
5097         if (!result)
5098                 *error = mono_w32error_get_last ();
5099         return result;
5100 }
5101
5102 gboolean
5103 mono_w32file_copy (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
5104 {
5105         gboolean result;
5106
5107         result = CopyFile (path, dest, !overwrite);
5108         if (!result)
5109                 *error = mono_w32error_get_last ();
5110
5111         return result;
5112 }
5113
5114 gboolean
5115 mono_w32file_replace (gunichar2 *destinationFileName, gunichar2 *sourceFileName, gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
5116 {
5117         gboolean result;
5118
5119         result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
5120         if (!result)
5121                 *error = mono_w32error_get_last ();
5122         return result;
5123 }
5124
5125 gint64
5126 mono_w32file_get_file_size (gpointer handle, gint32 *error)
5127 {
5128         gint64 length;
5129         guint32 length_hi;
5130
5131         length = GetFileSize (handle, &length_hi);
5132         if(length==INVALID_FILE_SIZE) {
5133                 *error=mono_w32error_get_last ();
5134         }
5135
5136         return length | ((gint64)length_hi << 32);
5137 }
5138
5139 gboolean
5140 mono_w32file_lock (gpointer handle, gint64 position, gint64 length, gint32 *error)
5141 {
5142         gboolean result;
5143
5144         result = LockFile (handle, position & 0xFFFFFFFF, position >> 32, length & 0xFFFFFFFF, length >> 32);
5145         if (!result)
5146                 *error = mono_w32error_get_last ();
5147         return result;
5148 }
5149
5150 gboolean
5151 mono_w32file_unlock (gpointer handle, gint64 position, gint64 length, gint32 *error)
5152 {
5153         gboolean result;
5154
5155         result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32, length & 0xFFFFFFFF, length >> 32);
5156         if (!result)
5157                 *error = mono_w32error_get_last ();
5158         return result;
5159 }
5160
5161 gpointer
5162 mono_w32file_get_console_input (void)
5163 {
5164         return mono_w32file_get_std_handle (STD_INPUT_HANDLE);
5165 }
5166
5167 gpointer
5168 mono_w32file_get_console_output (void)
5169 {
5170         return mono_w32file_get_std_handle (STD_OUTPUT_HANDLE);
5171 }
5172
5173 gpointer
5174 mono_w32file_get_console_error (void)
5175 {
5176         return mono_w32file_get_std_handle (STD_ERROR_HANDLE);
5177 }