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