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