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