[io-layer] Make _WapiHandleUnshared definition private
[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 fd %d", __func__, handle, fd);
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
1458 /**
1459  * CreateFile:
1460  * @name: a pointer to a NULL-terminated unicode string, that names
1461  * the file or other object to create.
1462  * @fileaccess: specifies the file access mode
1463  * @sharemode: whether the file should be shared.  This parameter is
1464  * currently ignored.
1465  * @security: Ignored for now.
1466  * @createmode: specifies whether to create a new file, whether to
1467  * overwrite an existing file, whether to truncate the file, etc.
1468  * @attrs: specifies file attributes and flags.  On win32 attributes
1469  * are characteristics of the file, not the handle, and are ignored
1470  * when an existing file is opened.  Flags give the library hints on
1471  * how to process a file to optimise performance.
1472  * @template: the handle of an open %GENERIC_READ file that specifies
1473  * attributes to apply to a newly created file, ignoring @attrs.
1474  * Normally this parameter is NULL.  This parameter is ignored when an
1475  * existing file is opened.
1476  *
1477  * Creates a new file handle.  This only applies to normal files:
1478  * pipes are handled by CreatePipe(), and console handles are created
1479  * with GetStdHandle().
1480  *
1481  * Return value: the new handle, or %INVALID_HANDLE_VALUE on error.
1482  */
1483 gpointer CreateFile(const gunichar2 *name, guint32 fileaccess,
1484                     guint32 sharemode, WapiSecurityAttributes *security,
1485                     guint32 createmode, guint32 attrs,
1486                     gpointer template_ G_GNUC_UNUSED)
1487 {
1488         struct _WapiHandle_file file_handle = {0};
1489         gpointer handle;
1490         int flags=convert_flags(fileaccess, createmode);
1491         /*mode_t perms=convert_perms(sharemode);*/
1492         /* we don't use sharemode, because that relates to sharing of
1493          * the file when the file is open and is already handled by
1494          * other code, perms instead are the on-disk permissions and
1495          * this is a sane default.
1496          */
1497         mode_t perms=0666;
1498         gchar *filename;
1499         int fd, ret;
1500         WapiHandleType handle_type;
1501         struct stat statbuf;
1502         
1503         mono_once (&io_ops_once, io_ops_init);
1504
1505         if (attrs & FILE_ATTRIBUTE_TEMPORARY)
1506                 perms = 0600;
1507         
1508         if (attrs & FILE_ATTRIBUTE_ENCRYPTED){
1509                 SetLastError (ERROR_ENCRYPTION_FAILED);
1510                 return INVALID_HANDLE_VALUE;
1511         }
1512         
1513         if (name == NULL) {
1514                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1515
1516                 SetLastError (ERROR_INVALID_NAME);
1517                 return(INVALID_HANDLE_VALUE);
1518         }
1519
1520         filename = mono_unicode_to_external (name);
1521         if (filename == NULL) {
1522                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1523
1524                 SetLastError (ERROR_INVALID_NAME);
1525                 return(INVALID_HANDLE_VALUE);
1526         }
1527         
1528         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Opening %s with share 0x%x and access 0x%x", __func__,
1529                    filename, sharemode, fileaccess);
1530         
1531         fd = _wapi_open (filename, flags, perms);
1532     
1533         /* If we were trying to open a directory with write permissions
1534          * (e.g. O_WRONLY or O_RDWR), this call will fail with
1535          * EISDIR. However, this is a bit bogus because calls to
1536          * manipulate the directory (e.g. SetFileTime) will still work on
1537          * the directory because they use other API calls
1538          * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1539          * to open the directory again without write permission.
1540          */
1541         if (fd == -1 && errno == EISDIR)
1542         {
1543                 /* Try again but don't try to make it writable */
1544                 fd = _wapi_open (filename, flags & ~(O_RDWR|O_WRONLY), perms);
1545         }
1546         
1547         if (fd == -1) {
1548                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error opening file %s: %s", __func__, filename,
1549                           strerror(errno));
1550                 _wapi_set_last_path_error_from_errno (NULL, filename);
1551                 g_free (filename);
1552
1553                 return(INVALID_HANDLE_VALUE);
1554         }
1555
1556         if (fd >= _wapi_fd_reserve) {
1557                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
1558
1559                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1560                 
1561                 close (fd);
1562                 g_free (filename);
1563                 
1564                 return(INVALID_HANDLE_VALUE);
1565         }
1566
1567         ret = fstat (fd, &statbuf);
1568         if (ret == -1) {
1569                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: fstat error of file %s: %s", __func__,
1570                            filename, strerror (errno));
1571                 _wapi_set_last_error_from_errno ();
1572                 g_free (filename);
1573                 close (fd);
1574                 
1575                 return(INVALID_HANDLE_VALUE);
1576         }
1577 #ifdef __native_client__
1578         /* Workaround: Native Client currently returns the same fake inode
1579          * for all files, so do a simple hash on the filename so we don't
1580          * use the same share info for each file.
1581          */
1582         statbuf.st_ino = g_str_hash(filename);
1583 #endif
1584
1585         if (share_allows_open (&statbuf, sharemode, fileaccess,
1586                          &file_handle.share_info) == FALSE) {
1587                 SetLastError (ERROR_SHARING_VIOLATION);
1588                 g_free (filename);
1589                 close (fd);
1590                 
1591                 return (INVALID_HANDLE_VALUE);
1592         }
1593         if (file_handle.share_info == NULL) {
1594                 /* No space, so no more files can be opened */
1595                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: No space in the share table", __func__);
1596
1597                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1598                 close (fd);
1599                 g_free (filename);
1600                 
1601                 return(INVALID_HANDLE_VALUE);
1602         }
1603         
1604         file_handle.filename = filename;
1605
1606         if(security!=NULL) {
1607                 //file_handle->security_attributes=_wapi_handle_scratch_store (
1608                 //security, sizeof(WapiSecurityAttributes));
1609         }
1610         
1611         file_handle.fd = fd;
1612         file_handle.fileaccess=fileaccess;
1613         file_handle.sharemode=sharemode;
1614         file_handle.attrs=attrs;
1615
1616 #ifdef HAVE_POSIX_FADVISE
1617         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1618                 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1619         if (attrs & FILE_FLAG_RANDOM_ACCESS)
1620                 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1621 #endif
1622         
1623 #ifndef S_ISFIFO
1624 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1625 #endif
1626         if (S_ISFIFO (statbuf.st_mode)) {
1627                 handle_type = WAPI_HANDLE_PIPE;
1628                 /* maintain invariant that pipes have no filename */
1629                 file_handle.filename = NULL;
1630                 g_free (filename);
1631                 filename = NULL;
1632         } else if (S_ISCHR (statbuf.st_mode)) {
1633                 handle_type = WAPI_HANDLE_CONSOLE;
1634         } else {
1635                 handle_type = WAPI_HANDLE_FILE;
1636         }
1637
1638         handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1639         if (handle == _WAPI_HANDLE_INVALID) {
1640                 g_warning ("%s: error creating file handle", __func__);
1641                 g_free (filename);
1642                 close (fd);
1643                 
1644                 SetLastError (ERROR_GEN_FAILURE);
1645                 return(INVALID_HANDLE_VALUE);
1646         }
1647         
1648         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: returning handle %p", __func__, handle);
1649         
1650         return(handle);
1651 }
1652
1653 /**
1654  * DeleteFile:
1655  * @name: a pointer to a NULL-terminated unicode string, that names
1656  * the file to be deleted.
1657  *
1658  * Deletes file @name.
1659  *
1660  * Return value: %TRUE on success, %FALSE otherwise.
1661  */
1662 gboolean DeleteFile(const gunichar2 *name)
1663 {
1664         gchar *filename;
1665         int retval;
1666         gboolean ret = FALSE;
1667         guint32 attrs;
1668 #if 0
1669         struct stat statbuf;
1670         struct _WapiFileShare *shareinfo;
1671 #endif
1672         
1673         if(name==NULL) {
1674                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1675
1676                 SetLastError (ERROR_INVALID_NAME);
1677                 return(FALSE);
1678         }
1679
1680         filename=mono_unicode_to_external(name);
1681         if(filename==NULL) {
1682                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1683
1684                 SetLastError (ERROR_INVALID_NAME);
1685                 return(FALSE);
1686         }
1687
1688         attrs = GetFileAttributes (name);
1689         if (attrs == INVALID_FILE_ATTRIBUTES) {
1690                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file attributes error", __func__);
1691                 /* Error set by GetFileAttributes() */
1692                 g_free (filename);
1693                 return(FALSE);
1694         }
1695
1696 #if 0
1697         /* Check to make sure sharing allows us to open the file for
1698          * writing.  See bug 323389.
1699          *
1700          * Do the checks that don't need an open file descriptor, for
1701          * simplicity's sake.  If we really have to do the full checks
1702          * then we can implement that later.
1703          */
1704         if (_wapi_stat (filename, &statbuf) < 0) {
1705                 _wapi_set_last_path_error_from_errno (NULL, filename);
1706                 g_free (filename);
1707                 return(FALSE);
1708         }
1709         
1710         if (share_allows_open (&statbuf, 0, GENERIC_WRITE,
1711                                &shareinfo) == FALSE) {
1712                 SetLastError (ERROR_SHARING_VIOLATION);
1713                 g_free (filename);
1714                 return FALSE;
1715         }
1716         if (shareinfo)
1717                 _wapi_handle_share_release (shareinfo);
1718 #endif
1719
1720         retval = _wapi_unlink (filename);
1721         
1722         if (retval == -1) {
1723                 _wapi_set_last_path_error_from_errno (NULL, filename);
1724         } else {
1725                 ret = TRUE;
1726         }
1727
1728         g_free(filename);
1729
1730         return(ret);
1731 }
1732
1733 /**
1734  * MoveFile:
1735  * @name: a pointer to a NULL-terminated unicode string, that names
1736  * the file to be moved.
1737  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1738  * new name for the file.
1739  *
1740  * Renames file @name to @dest_name.
1741  * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1742  * when it is the same file as the source.  In that case it silently succeeds.
1743  *
1744  * Return value: %TRUE on success, %FALSE otherwise.
1745  */
1746 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1747 {
1748         gchar *utf8_name, *utf8_dest_name;
1749         int result, errno_copy;
1750         struct stat stat_src, stat_dest;
1751         gboolean ret = FALSE;
1752         struct _WapiFileShare *shareinfo;
1753         
1754         if(name==NULL) {
1755                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1756
1757                 SetLastError (ERROR_INVALID_NAME);
1758                 return(FALSE);
1759         }
1760
1761         utf8_name = mono_unicode_to_external (name);
1762         if (utf8_name == NULL) {
1763                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1764                 
1765                 SetLastError (ERROR_INVALID_NAME);
1766                 return FALSE;
1767         }
1768         
1769         if(dest_name==NULL) {
1770                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1771
1772                 g_free (utf8_name);
1773                 SetLastError (ERROR_INVALID_NAME);
1774                 return(FALSE);
1775         }
1776
1777         utf8_dest_name = mono_unicode_to_external (dest_name);
1778         if (utf8_dest_name == NULL) {
1779                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
1780
1781                 g_free (utf8_name);
1782                 SetLastError (ERROR_INVALID_NAME);
1783                 return FALSE;
1784         }
1785
1786         /*
1787          * In C# land we check for the existence of src, but not for dest.
1788          * We check it here and return the failure if dest exists and is not
1789          * the same file as src.
1790          */
1791         if (_wapi_stat (utf8_name, &stat_src) < 0) {
1792                 if (errno != ENOENT || _wapi_lstat (utf8_name, &stat_src) < 0) {
1793                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1794                         g_free (utf8_name);
1795                         g_free (utf8_dest_name);
1796                         return FALSE;
1797                 }
1798         }
1799         
1800         if (!_wapi_stat (utf8_dest_name, &stat_dest)) {
1801                 if (stat_dest.st_dev != stat_src.st_dev ||
1802                     stat_dest.st_ino != stat_src.st_ino) {
1803                         g_free (utf8_name);
1804                         g_free (utf8_dest_name);
1805                         SetLastError (ERROR_ALREADY_EXISTS);
1806                         return FALSE;
1807                 }
1808         }
1809
1810         /* Check to make that we have delete sharing permission.
1811          * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
1812          *
1813          * Do the checks that don't need an open file descriptor, for
1814          * simplicity's sake.  If we really have to do the full checks
1815          * then we can implement that later.
1816          */
1817         if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
1818                 SetLastError (ERROR_SHARING_VIOLATION);
1819                 return FALSE;
1820         }
1821         if (shareinfo)
1822                 _wapi_handle_share_release (shareinfo);
1823
1824         result = _wapi_rename (utf8_name, utf8_dest_name);
1825         errno_copy = errno;
1826         
1827         if (result == -1) {
1828                 switch(errno_copy) {
1829                 case EEXIST:
1830                         SetLastError (ERROR_ALREADY_EXISTS);
1831                         break;
1832
1833                 case EXDEV:
1834                         /* Ignore here, it is dealt with below */
1835                         break;
1836                         
1837                 default:
1838                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1839                 }
1840         }
1841         
1842         g_free (utf8_name);
1843         g_free (utf8_dest_name);
1844
1845         if (result != 0 && errno_copy == EXDEV) {
1846                 if (S_ISDIR (stat_src.st_mode)) {
1847                         SetLastError (ERROR_NOT_SAME_DEVICE);
1848                         return FALSE;
1849                 }
1850                 /* Try a copy to the new location, and delete the source */
1851                 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1852                         /* CopyFile will set the error */
1853                         return(FALSE);
1854                 }
1855                 
1856                 return(DeleteFile (name));
1857         }
1858
1859         if (result == 0) {
1860                 ret = TRUE;
1861         }
1862
1863         return(ret);
1864 }
1865
1866 static gboolean
1867 write_file (int src_fd, int dest_fd, struct stat *st_src, gboolean report_errors)
1868 {
1869         int remain, n;
1870         char *buf, *wbuf;
1871         int buf_size = st_src->st_blksize;
1872
1873         buf_size = buf_size < 8192 ? 8192 : (buf_size > 65536 ? 65536 : buf_size);
1874         buf = (char *) malloc (buf_size);
1875
1876         for (;;) {
1877                 remain = read (src_fd, buf, buf_size);
1878                 if (remain < 0) {
1879                         if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1880                                 continue;
1881
1882                         if (report_errors)
1883                                 _wapi_set_last_error_from_errno ();
1884
1885                         free (buf);
1886                         return FALSE;
1887                 }
1888                 if (remain == 0) {
1889                         break;
1890                 }
1891
1892                 wbuf = buf;
1893                 while (remain > 0) {
1894                         if ((n = write (dest_fd, wbuf, remain)) < 0) {
1895                                 if (errno == EINTR && !_wapi_thread_cur_apc_pending ())
1896                                         continue;
1897
1898                                 if (report_errors)
1899                                         _wapi_set_last_error_from_errno ();
1900                                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: write failed.", __func__);
1901                                 free (buf);
1902                                 return FALSE;
1903                         }
1904
1905                         remain -= n;
1906                         wbuf += n;
1907                 }
1908         }
1909
1910         free (buf);
1911         return TRUE ;
1912 }
1913
1914 /**
1915  * CopyFile:
1916  * @name: a pointer to a NULL-terminated unicode string, that names
1917  * the file to be copied.
1918  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1919  * new name for the file.
1920  * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1921  *
1922  * Copies file @name to @dest_name
1923  *
1924  * Return value: %TRUE on success, %FALSE otherwise.
1925  */
1926 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1927                    gboolean fail_if_exists)
1928 {
1929         gchar *utf8_src, *utf8_dest;
1930         int src_fd, dest_fd;
1931         struct stat st, dest_st;
1932         struct utimbuf dest_time;
1933         gboolean ret = TRUE;
1934         int ret_utime;
1935         
1936         if(name==NULL) {
1937                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
1938
1939                 SetLastError (ERROR_INVALID_NAME);
1940                 return(FALSE);
1941         }
1942         
1943         utf8_src = mono_unicode_to_external (name);
1944         if (utf8_src == NULL) {
1945                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of source returned NULL",
1946                            __func__);
1947
1948                 SetLastError (ERROR_INVALID_PARAMETER);
1949                 return(FALSE);
1950         }
1951         
1952         if(dest_name==NULL) {
1953                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: dest is NULL", __func__);
1954
1955                 g_free (utf8_src);
1956                 SetLastError (ERROR_INVALID_NAME);
1957                 return(FALSE);
1958         }
1959         
1960         utf8_dest = mono_unicode_to_external (dest_name);
1961         if (utf8_dest == NULL) {
1962                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of dest returned NULL",
1963                            __func__);
1964
1965                 SetLastError (ERROR_INVALID_PARAMETER);
1966
1967                 g_free (utf8_src);
1968                 
1969                 return(FALSE);
1970         }
1971         
1972         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1973         if (src_fd < 0) {
1974                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1975                 
1976                 g_free (utf8_src);
1977                 g_free (utf8_dest);
1978                 
1979                 return(FALSE);
1980         }
1981
1982         if (fstat (src_fd, &st) < 0) {
1983                 _wapi_set_last_error_from_errno ();
1984
1985                 g_free (utf8_src);
1986                 g_free (utf8_dest);
1987                 close (src_fd);
1988                 
1989                 return(FALSE);
1990         }
1991
1992         /* Before trying to open/create the dest, we need to report a 'file busy'
1993          * error if src and dest are actually the same file. We do the check here to take
1994          * advantage of the IOMAP capability */
1995         if (!_wapi_stat (utf8_dest, &dest_st) && st.st_dev == dest_st.st_dev && 
1996                         st.st_ino == dest_st.st_ino) {
1997
1998                 g_free (utf8_src);
1999                 g_free (utf8_dest);
2000                 close (src_fd);
2001
2002                 SetLastError (ERROR_SHARING_VIOLATION);
2003                 return (FALSE);
2004         }
2005         
2006         if (fail_if_exists) {
2007                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL, st.st_mode);
2008         } else {
2009                 /* FIXME: it kinda sucks that this code path potentially scans
2010                  * the directory twice due to the weird SetLastError()
2011                  * behavior. */
2012                 dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
2013                 if (dest_fd < 0) {
2014                         /* The file does not exist, try creating it */
2015                         dest_fd = _wapi_open (utf8_dest, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode);
2016                 } else {
2017                         /* Apparently this error is set if we
2018                          * overwrite the dest file
2019                          */
2020                         SetLastError (ERROR_ALREADY_EXISTS);
2021                 }
2022         }
2023         if (dest_fd < 0) {
2024                 _wapi_set_last_error_from_errno ();
2025
2026                 g_free (utf8_src);
2027                 g_free (utf8_dest);
2028                 close (src_fd);
2029
2030                 return(FALSE);
2031         }
2032
2033         if (!write_file (src_fd, dest_fd, &st, TRUE))
2034                 ret = FALSE;
2035
2036         close (src_fd);
2037         close (dest_fd);
2038         
2039         dest_time.modtime = st.st_mtime;
2040         dest_time.actime = st.st_atime;
2041         ret_utime = utime (utf8_dest, &dest_time);
2042         if (ret_utime == -1)
2043                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file [%s] utime failed: %s", __func__, utf8_dest, strerror(errno));
2044         
2045         g_free (utf8_src);
2046         g_free (utf8_dest);
2047
2048         return ret;
2049 }
2050
2051 static gchar*
2052 convert_arg_to_utf8 (const gunichar2 *arg, const gchar *arg_name)
2053 {
2054         gchar *utf8_ret;
2055
2056         if (arg == NULL) {
2057                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s is NULL", __func__, arg_name);
2058                 SetLastError (ERROR_INVALID_NAME);
2059                 return NULL;
2060         }
2061
2062         utf8_ret = mono_unicode_to_external (arg);
2063         if (utf8_ret == NULL) {
2064                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion of %s returned NULL",
2065                            __func__, arg_name);
2066                 SetLastError (ERROR_INVALID_PARAMETER);
2067                 return NULL;
2068         }
2069
2070         return utf8_ret;
2071 }
2072
2073 gboolean
2074 ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFileName,
2075                       const gunichar2 *backupFileName, guint32 replaceFlags, 
2076                       gpointer exclude, gpointer reserved)
2077 {
2078         int result, backup_fd = -1,replaced_fd = -1;
2079         gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
2080         struct stat stBackup;
2081         gboolean ret = FALSE;
2082
2083         if (!(utf8_replacedFileName = convert_arg_to_utf8 (replacedFileName, "replacedFileName")))
2084                 return FALSE;
2085         if (!(utf8_replacementFileName = convert_arg_to_utf8 (replacementFileName, "replacementFileName")))
2086                 goto replace_cleanup;
2087         if (backupFileName != NULL) {
2088                 if (!(utf8_backupFileName = convert_arg_to_utf8 (backupFileName, "backupFileName")))
2089                         goto replace_cleanup;
2090         }
2091
2092         if (utf8_backupFileName) {
2093                 // Open the backup file for read so we can restore the file if an error occurs.
2094                 backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
2095                 result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
2096                 if (result == -1)
2097                         goto replace_cleanup;
2098         }
2099
2100         result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
2101         if (result == -1) {
2102                 _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
2103                 _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
2104                 if (backup_fd != -1 && !fstat (backup_fd, &stBackup)) {
2105                         replaced_fd = _wapi_open (utf8_backupFileName, O_WRONLY | O_CREAT | O_TRUNC,
2106                                                   stBackup.st_mode);
2107                         
2108                         if (replaced_fd == -1)
2109                                 goto replace_cleanup;
2110
2111                         write_file (backup_fd, replaced_fd, &stBackup, FALSE);
2112                 }
2113
2114                 goto replace_cleanup;
2115         }
2116
2117         ret = TRUE;
2118
2119 replace_cleanup:
2120         g_free (utf8_replacedFileName);
2121         g_free (utf8_replacementFileName);
2122         g_free (utf8_backupFileName);
2123         if (backup_fd != -1)
2124                 close (backup_fd);
2125         if (replaced_fd != -1)
2126                 close (replaced_fd);
2127         return ret;
2128 }
2129
2130 /**
2131  * GetStdHandle:
2132  * @stdhandle: specifies the file descriptor
2133  *
2134  * Returns a handle for stdin, stdout, or stderr.  Always returns the
2135  * same handle for the same @stdhandle.
2136  *
2137  * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2138  */
2139
2140 static mono_mutex_t stdhandle_mutex;
2141
2142 gpointer GetStdHandle(WapiStdHandle stdhandle)
2143 {
2144         struct _WapiHandle_file *file_handle;
2145         gpointer handle;
2146         int thr_ret, fd;
2147         const gchar *name;
2148         gboolean ok;
2149         
2150         switch(stdhandle) {
2151         case STD_INPUT_HANDLE:
2152                 fd = 0;
2153                 name = "<stdin>";
2154                 break;
2155
2156         case STD_OUTPUT_HANDLE:
2157                 fd = 1;
2158                 name = "<stdout>";
2159                 break;
2160
2161         case STD_ERROR_HANDLE:
2162                 fd = 2;
2163                 name = "<stderr>";
2164                 break;
2165
2166         default:
2167                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unknown standard handle type", __func__);
2168
2169                 SetLastError (ERROR_INVALID_PARAMETER);
2170                 return(INVALID_HANDLE_VALUE);
2171         }
2172
2173         handle = GINT_TO_POINTER (fd);
2174
2175         thr_ret = mono_os_mutex_lock (&stdhandle_mutex);
2176         g_assert (thr_ret == 0);
2177
2178         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2179                                   (gpointer *)&file_handle);
2180         if (ok == FALSE) {
2181                 /* Need to create this console handle */
2182                 handle = _wapi_stdhandle_create (fd, name);
2183                 
2184                 if (handle == INVALID_HANDLE_VALUE) {
2185                         SetLastError (ERROR_NO_MORE_FILES);
2186                         goto done;
2187                 }
2188         } else {
2189                 /* Add a reference to this handle */
2190                 _wapi_handle_ref (handle);
2191         }
2192         
2193   done:
2194         thr_ret = mono_os_mutex_unlock (&stdhandle_mutex);
2195         g_assert (thr_ret == 0);
2196         
2197         return(handle);
2198 }
2199
2200 /**
2201  * ReadFile:
2202  * @handle: The file handle to read from.  The handle must have
2203  * %GENERIC_READ access.
2204  * @buffer: The buffer to store read data in
2205  * @numbytes: The maximum number of bytes to read
2206  * @bytesread: The actual number of bytes read is stored here.  This
2207  * value can be zero if the handle is positioned at the end of the
2208  * file.
2209  * @overlapped: points to a required %WapiOverlapped structure if
2210  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2211  * otherwise.
2212  *
2213  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2214  * function reads up to @numbytes bytes from the file from the current
2215  * file position, and stores them in @buffer.  If there are not enough
2216  * bytes left in the file, just the amount available will be read.
2217  * The actual number of bytes read is stored in @bytesread.
2218
2219  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2220  * file position is ignored and the read position is taken from data
2221  * in the @overlapped structure.
2222  *
2223  * Return value: %TRUE if the read succeeds (even if no bytes were
2224  * read due to an attempt to read past the end of the file), %FALSE on
2225  * error.
2226  */
2227 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2228                   guint32 *bytesread, WapiOverlapped *overlapped)
2229 {
2230         WapiHandleType type;
2231
2232         type = _wapi_handle_type (handle);
2233         
2234         if(io_ops[type].readfile==NULL) {
2235                 SetLastError (ERROR_INVALID_HANDLE);
2236                 return(FALSE);
2237         }
2238         
2239         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2240                                       overlapped));
2241 }
2242
2243 /**
2244  * WriteFile:
2245  * @handle: The file handle to write to.  The handle must have
2246  * %GENERIC_WRITE access.
2247  * @buffer: The buffer to read data from.
2248  * @numbytes: The maximum number of bytes to write.
2249  * @byteswritten: The actual number of bytes written is stored here.
2250  * If the handle is positioned at the file end, the length of the file
2251  * is extended.  This parameter may be %NULL.
2252  * @overlapped: points to a required %WapiOverlapped structure if
2253  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2254  * otherwise.
2255  *
2256  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2257  * function writes up to @numbytes bytes from @buffer to the file at
2258  * the current file position.  If @handle is positioned at the end of
2259  * the file, the file is extended.  The actual number of bytes written
2260  * is stored in @byteswritten.
2261  *
2262  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2263  * file position is ignored and the write position is taken from data
2264  * in the @overlapped structure.
2265  *
2266  * Return value: %TRUE if the write succeeds, %FALSE on error.
2267  */
2268 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2269                    guint32 *byteswritten, WapiOverlapped *overlapped)
2270 {
2271         WapiHandleType type;
2272
2273         type = _wapi_handle_type (handle);
2274         
2275         if(io_ops[type].writefile==NULL) {
2276                 SetLastError (ERROR_INVALID_HANDLE);
2277                 return(FALSE);
2278         }
2279         
2280         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2281                                        overlapped));
2282 }
2283
2284 /**
2285  * FlushFileBuffers:
2286  * @handle: Handle to open file.  The handle must have
2287  * %GENERIC_WRITE access.
2288  *
2289  * Flushes buffers of the file and causes all unwritten data to
2290  * be written.
2291  *
2292  * Return value: %TRUE on success, %FALSE otherwise.
2293  */
2294 gboolean FlushFileBuffers(gpointer handle)
2295 {
2296         WapiHandleType type;
2297
2298         type = _wapi_handle_type (handle);
2299         
2300         if(io_ops[type].flushfile==NULL) {
2301                 SetLastError (ERROR_INVALID_HANDLE);
2302                 return(FALSE);
2303         }
2304         
2305         return(io_ops[type].flushfile (handle));
2306 }
2307
2308 /**
2309  * SetEndOfFile:
2310  * @handle: The file handle to set.  The handle must have
2311  * %GENERIC_WRITE access.
2312  *
2313  * Moves the end-of-file position to the current position of the file
2314  * pointer.  This function is used to truncate or extend a file.
2315  *
2316  * Return value: %TRUE on success, %FALSE otherwise.
2317  */
2318 gboolean SetEndOfFile(gpointer handle)
2319 {
2320         WapiHandleType type;
2321
2322         type = _wapi_handle_type (handle);
2323         
2324         if (io_ops[type].setendoffile == NULL) {
2325                 SetLastError (ERROR_INVALID_HANDLE);
2326                 return(FALSE);
2327         }
2328         
2329         return(io_ops[type].setendoffile (handle));
2330 }
2331
2332 /**
2333  * SetFilePointer:
2334  * @handle: The file handle to set.  The handle must have
2335  * %GENERIC_READ or %GENERIC_WRITE access.
2336  * @movedistance: Low 32 bits of a signed value that specifies the
2337  * number of bytes to move the file pointer.
2338  * @highmovedistance: Pointer to the high 32 bits of a signed value
2339  * that specifies the number of bytes to move the file pointer, or
2340  * %NULL.
2341  * @method: The starting point for the file pointer move.
2342  *
2343  * Sets the file pointer of an open file.
2344  *
2345  * The distance to move the file pointer is calculated from
2346  * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2347  * @movedistance is the 32-bit signed value; otherwise, @movedistance
2348  * is the low 32 bits and @highmovedistance a pointer to the high 32
2349  * bits of a 64 bit signed value.  A positive distance moves the file
2350  * pointer forward from the position specified by @method; a negative
2351  * distance moves the file pointer backward.
2352  *
2353  * If the library is compiled without large file support,
2354  * @highmovedistance is ignored and its value is set to zero on a
2355  * successful return.
2356  *
2357  * Return value: On success, the low 32 bits of the new file pointer.
2358  * If @highmovedistance is not %NULL, the high 32 bits of the new file
2359  * pointer are stored there.  On failure, %INVALID_SET_FILE_POINTER.
2360  */
2361 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2362                        gint32 *highmovedistance, WapiSeekMethod method)
2363 {
2364         WapiHandleType type;
2365
2366         type = _wapi_handle_type (handle);
2367         
2368         if (io_ops[type].seek == NULL) {
2369                 SetLastError (ERROR_INVALID_HANDLE);
2370                 return(INVALID_SET_FILE_POINTER);
2371         }
2372         
2373         return(io_ops[type].seek (handle, movedistance, highmovedistance,
2374                                   method));
2375 }
2376
2377 /**
2378  * GetFileType:
2379  * @handle: The file handle to test.
2380  *
2381  * Finds the type of file @handle.
2382  *
2383  * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2384  * unknown.  %FILE_TYPE_DISK - @handle is a disk file.
2385  * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2386  * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2387  */
2388 WapiFileType GetFileType(gpointer handle)
2389 {
2390         WapiHandleType type;
2391
2392         type = _wapi_handle_type (handle);
2393         
2394         if (io_ops[type].getfiletype == NULL) {
2395                 SetLastError (ERROR_INVALID_HANDLE);
2396                 return(FILE_TYPE_UNKNOWN);
2397         }
2398         
2399         return(io_ops[type].getfiletype ());
2400 }
2401
2402 /**
2403  * GetFileSize:
2404  * @handle: The file handle to query.  The handle must have
2405  * %GENERIC_READ or %GENERIC_WRITE access.
2406  * @highsize: If non-%NULL, the high 32 bits of the file size are
2407  * stored here.
2408  *
2409  * Retrieves the size of the file @handle.
2410  *
2411  * If the library is compiled without large file support, @highsize
2412  * has its value set to zero on a successful return.
2413  *
2414  * Return value: On success, the low 32 bits of the file size.  If
2415  * @highsize is non-%NULL then the high 32 bits of the file size are
2416  * stored here.  On failure %INVALID_FILE_SIZE is returned.
2417  */
2418 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2419 {
2420         WapiHandleType type;
2421
2422         type = _wapi_handle_type (handle);
2423         
2424         if (io_ops[type].getfilesize == NULL) {
2425                 SetLastError (ERROR_INVALID_HANDLE);
2426                 return(INVALID_FILE_SIZE);
2427         }
2428         
2429         return(io_ops[type].getfilesize (handle, highsize));
2430 }
2431
2432 /**
2433  * GetFileTime:
2434  * @handle: The file handle to query.  The handle must have
2435  * %GENERIC_READ access.
2436  * @create_time: Points to a %WapiFileTime structure to receive the
2437  * number of ticks since the epoch that file was created.  May be
2438  * %NULL.
2439  * @last_access: Points to a %WapiFileTime structure to receive the
2440  * number of ticks since the epoch when file was last accessed.  May be
2441  * %NULL.
2442  * @last_write: Points to a %WapiFileTime structure to receive the
2443  * number of ticks since the epoch when file was last written to.  May
2444  * be %NULL.
2445  *
2446  * Finds the number of ticks since the epoch that the file referenced
2447  * by @handle was created, last accessed and last modified.  A tick is
2448  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2449  * GMT.
2450  *
2451  * Create time isn't recorded on POSIX file systems or reported by
2452  * stat(2), so that time is guessed by returning the oldest of the
2453  * other times.
2454  *
2455  * Return value: %TRUE on success, %FALSE otherwise.
2456  */
2457 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2458                      WapiFileTime *last_access, WapiFileTime *last_write)
2459 {
2460         WapiHandleType type;
2461
2462         type = _wapi_handle_type (handle);
2463         
2464         if (io_ops[type].getfiletime == NULL) {
2465                 SetLastError (ERROR_INVALID_HANDLE);
2466                 return(FALSE);
2467         }
2468         
2469         return(io_ops[type].getfiletime (handle, create_time, last_access,
2470                                          last_write));
2471 }
2472
2473 /**
2474  * SetFileTime:
2475  * @handle: The file handle to set.  The handle must have
2476  * %GENERIC_WRITE access.
2477  * @create_time: Points to a %WapiFileTime structure that contains the
2478  * number of ticks since the epoch that the file was created.  May be
2479  * %NULL.
2480  * @last_access: Points to a %WapiFileTime structure that contains the
2481  * number of ticks since the epoch when the file was last accessed.
2482  * May be %NULL.
2483  * @last_write: Points to a %WapiFileTime structure that contains the
2484  * number of ticks since the epoch when the file was last written to.
2485  * May be %NULL.
2486  *
2487  * Sets the number of ticks since the epoch that the file referenced
2488  * by @handle was created, last accessed or last modified.  A tick is
2489  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2490  * GMT.
2491  *
2492  * Create time isn't recorded on POSIX file systems, and is ignored.
2493  *
2494  * Return value: %TRUE on success, %FALSE otherwise.
2495  */
2496 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2497                      const WapiFileTime *last_access,
2498                      const WapiFileTime *last_write)
2499 {
2500         WapiHandleType type;
2501
2502         type = _wapi_handle_type (handle);
2503         
2504         if (io_ops[type].setfiletime == NULL) {
2505                 SetLastError (ERROR_INVALID_HANDLE);
2506                 return(FALSE);
2507         }
2508         
2509         return(io_ops[type].setfiletime (handle, create_time, last_access,
2510                                          last_write));
2511 }
2512
2513 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
2514  * January 1 1601 GMT
2515  */
2516
2517 #define TICKS_PER_MILLISECOND 10000L
2518 #define TICKS_PER_SECOND 10000000L
2519 #define TICKS_PER_MINUTE 600000000L
2520 #define TICKS_PER_HOUR 36000000000LL
2521 #define TICKS_PER_DAY 864000000000LL
2522
2523 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2524
2525 static const guint16 mon_yday[2][13]={
2526         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2527         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2528 };
2529
2530 /**
2531  * FileTimeToSystemTime:
2532  * @file_time: Points to a %WapiFileTime structure that contains the
2533  * number of ticks to convert.
2534  * @system_time: Points to a %WapiSystemTime structure to receive the
2535  * broken-out time.
2536  *
2537  * Converts a tick count into broken-out time values.
2538  *
2539  * Return value: %TRUE on success, %FALSE otherwise.
2540  */
2541 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2542                               WapiSystemTime *system_time)
2543 {
2544         gint64 file_ticks, totaldays, rem, y;
2545         const guint16 *ip;
2546         
2547         if(system_time==NULL) {
2548                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: system_time NULL", __func__);
2549
2550                 SetLastError (ERROR_INVALID_PARAMETER);
2551                 return(FALSE);
2552         }
2553         
2554         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2555                 file_time->dwLowDateTime;
2556         
2557         /* Really compares if file_ticks>=0x8000000000000000
2558          * (LLONG_MAX+1) but we're working with a signed value for the
2559          * year and day calculation to work later
2560          */
2561         if(file_ticks<0) {
2562                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: file_time too big", __func__);
2563
2564                 SetLastError (ERROR_INVALID_PARAMETER);
2565                 return(FALSE);
2566         }
2567
2568         totaldays=(file_ticks / TICKS_PER_DAY);
2569         rem = file_ticks % TICKS_PER_DAY;
2570         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2571
2572         system_time->wHour=rem/TICKS_PER_HOUR;
2573         rem %= TICKS_PER_HOUR;
2574         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2575         
2576         system_time->wMinute = rem / TICKS_PER_MINUTE;
2577         rem %= TICKS_PER_MINUTE;
2578         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2579                   rem);
2580         
2581         system_time->wSecond = rem / TICKS_PER_SECOND;
2582         rem %= TICKS_PER_SECOND;
2583         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2584                   rem);
2585         
2586         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2587         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Milliseconds: %d", __func__,
2588                   system_time->wMilliseconds);
2589
2590         /* January 1, 1601 was a Monday, according to Emacs calendar */
2591         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2592         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2593         
2594         /* This algorithm to find year and month given days from epoch
2595          * from glibc
2596          */
2597         y=1601;
2598         
2599 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2600 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2601
2602         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2603                 /* Guess a corrected year, assuming 365 days per year */
2604                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2605                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld yg: %lld y: %lld", __func__,
2606                           totaldays, yg,
2607                           y);
2608                 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2609                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2610                 
2611                 /* Adjust days and y to match the guessed year. */
2612                 totaldays -= ((yg - y) * 365
2613                               + LEAPS_THRU_END_OF (yg - 1)
2614                               - LEAPS_THRU_END_OF (y - 1));
2615                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2616                 y = yg;
2617                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: y: %lld", __func__, y);
2618         }
2619         
2620         system_time->wYear = y;
2621         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Year: %d", __func__, system_time->wYear);
2622
2623         ip = mon_yday[isleap(y)];
2624         
2625         for(y=11; totaldays < ip[y]; --y) {
2626                 continue;
2627         }
2628         totaldays-=ip[y];
2629         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: totaldays: %lld", __func__, totaldays);
2630         
2631         system_time->wMonth = y + 1;
2632         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Month: %d", __func__, system_time->wMonth);
2633
2634         system_time->wDay = totaldays + 1;
2635         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Day: %d", __func__, system_time->wDay);
2636         
2637         return(TRUE);
2638 }
2639
2640 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2641 {
2642         struct _WapiHandle_find find_handle = {0};
2643         gpointer handle;
2644         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2645         int result;
2646         
2647         if (pattern == NULL) {
2648                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: pattern is NULL", __func__);
2649
2650                 SetLastError (ERROR_PATH_NOT_FOUND);
2651                 return(INVALID_HANDLE_VALUE);
2652         }
2653
2654         utf8_pattern = mono_unicode_to_external (pattern);
2655         if (utf8_pattern == NULL) {
2656                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2657                 
2658                 SetLastError (ERROR_INVALID_NAME);
2659                 return(INVALID_HANDLE_VALUE);
2660         }
2661
2662         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: looking for [%s]", __func__, utf8_pattern);
2663         
2664         /* Figure out which bit of the pattern is the directory */
2665         dir_part = _wapi_dirname (utf8_pattern);
2666         entry_part = _wapi_basename (utf8_pattern);
2667
2668 #if 0
2669         /* Don't do this check for now, it breaks if directories
2670          * really do have metachars in their names (see bug 58116).
2671          * FIXME: Figure out a better solution to keep some checks...
2672          */
2673         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2674                 SetLastError (ERROR_INVALID_NAME);
2675                 g_free (dir_part);
2676                 g_free (entry_part);
2677                 g_free (utf8_pattern);
2678                 return(INVALID_HANDLE_VALUE);
2679         }
2680 #endif
2681
2682         /* The pattern can specify a directory or a set of files.
2683          *
2684          * The pattern can have wildcard characters ? and *, but only
2685          * in the section after the last directory delimiter.  (Return
2686          * ERROR_INVALID_NAME if there are wildcards in earlier path
2687          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
2688          * means "match one character", "??" seems to mean "match one
2689          * or two characters", "???" seems to mean "match one, two or
2690          * three characters", etc.  Windows will also try and match
2691          * the mangled "short name" of files, so 8 character patterns
2692          * with wildcards will show some surprising results.
2693          *
2694          * All the written documentation I can find says that '?' 
2695          * should only match one character, and doesn't mention '??',
2696          * '???' etc.  I'm going to assume that the strict behaviour
2697          * (ie '???' means three and only three characters) is the
2698          * correct one, because that lets me use fnmatch(3) rather
2699          * than mess around with regexes.
2700          */
2701
2702         find_handle.namelist = NULL;
2703         result = _wapi_io_scandir (dir_part, entry_part,
2704                                    &find_handle.namelist);
2705         
2706         if (result == 0) {
2707                 /* No files, which windows seems to call
2708                  * FILE_NOT_FOUND
2709                  */
2710                 SetLastError (ERROR_FILE_NOT_FOUND);
2711                 g_free (utf8_pattern);
2712                 g_free (entry_part);
2713                 g_free (dir_part);
2714                 return (INVALID_HANDLE_VALUE);
2715         }
2716         
2717         if (result < 0) {
2718                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2719                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: scandir error: %s", __func__, g_strerror (errno));
2720                 g_free (utf8_pattern);
2721                 g_free (entry_part);
2722                 g_free (dir_part);
2723                 return (INVALID_HANDLE_VALUE);
2724         }
2725
2726         g_free (utf8_pattern);
2727         g_free (entry_part);
2728         
2729         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Got %d matches", __func__, result);
2730
2731         find_handle.dir_part = dir_part;
2732         find_handle.num = result;
2733         find_handle.count = 0;
2734         
2735         handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2736         if (handle == _WAPI_HANDLE_INVALID) {
2737                 g_warning ("%s: error creating find handle", __func__);
2738                 g_free (dir_part);
2739                 g_free (entry_part);
2740                 g_free (utf8_pattern);
2741                 SetLastError (ERROR_GEN_FAILURE);
2742                 
2743                 return(INVALID_HANDLE_VALUE);
2744         }
2745
2746         if (handle != INVALID_HANDLE_VALUE &&
2747             !FindNextFile (handle, find_data)) {
2748                 FindClose (handle);
2749                 SetLastError (ERROR_NO_MORE_FILES);
2750                 handle = INVALID_HANDLE_VALUE;
2751         }
2752
2753         return (handle);
2754 }
2755
2756 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2757 {
2758         struct _WapiHandle_find *find_handle;
2759         gboolean ok;
2760         struct stat buf, linkbuf;
2761         int result;
2762         gchar *filename;
2763         gchar *utf8_filename, *utf8_basename;
2764         gunichar2 *utf16_basename;
2765         time_t create_time;
2766         glong bytes;
2767         int thr_ret;
2768         gboolean ret = FALSE;
2769         
2770         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2771                                 (gpointer *)&find_handle);
2772         if(ok==FALSE) {
2773                 g_warning ("%s: error looking up find handle %p", __func__,
2774                            handle);
2775                 SetLastError (ERROR_INVALID_HANDLE);
2776                 return(FALSE);
2777         }
2778
2779         thr_ret = _wapi_handle_lock_handle (handle);
2780         g_assert (thr_ret == 0);
2781         
2782 retry:
2783         if (find_handle->count >= find_handle->num) {
2784                 SetLastError (ERROR_NO_MORE_FILES);
2785                 goto cleanup;
2786         }
2787
2788         /* stat next match */
2789
2790         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2791
2792         result = _wapi_stat (filename, &buf);
2793         if (result == -1 && errno == ENOENT) {
2794                 /* Might be a dangling symlink */
2795                 result = _wapi_lstat (filename, &buf);
2796         }
2797         
2798         if (result != 0) {
2799                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: stat failed: %s", __func__, filename);
2800
2801                 g_free (filename);
2802                 goto retry;
2803         }
2804
2805 #ifndef __native_client__
2806         result = _wapi_lstat (filename, &linkbuf);
2807         if (result != 0) {
2808                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: lstat failed: %s", __func__, filename);
2809
2810                 g_free (filename);
2811                 goto retry;
2812         }
2813 #endif
2814
2815         utf8_filename = mono_utf8_from_external (filename);
2816         if (utf8_filename == NULL) {
2817                 /* We couldn't turn this filename into utf8 (eg the
2818                  * encoding of the name wasn't convertible), so just
2819                  * ignore it.
2820                  */
2821                 g_warning ("%s: Bad encoding for '%s'\nConsider using MONO_EXTERNAL_ENCODINGS\n", __func__, filename);
2822                 
2823                 g_free (filename);
2824                 goto retry;
2825         }
2826         g_free (filename);
2827         
2828         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Found [%s]", __func__, utf8_filename);
2829         
2830         /* fill data block */
2831
2832         if (buf.st_mtime < buf.st_ctime)
2833                 create_time = buf.st_mtime;
2834         else
2835                 create_time = buf.st_ctime;
2836         
2837 #ifdef __native_client__
2838         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, NULL);
2839 #else
2840         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &linkbuf);
2841 #endif
2842
2843         _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2844         _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2845         _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2846
2847         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2848                 find_data->nFileSizeHigh = 0;
2849                 find_data->nFileSizeLow = 0;
2850         } else {
2851                 find_data->nFileSizeHigh = buf.st_size >> 32;
2852                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2853         }
2854
2855         find_data->dwReserved0 = 0;
2856         find_data->dwReserved1 = 0;
2857
2858         utf8_basename = _wapi_basename (utf8_filename);
2859         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2860                                           NULL);
2861         if(utf16_basename==NULL) {
2862                 g_free (utf8_basename);
2863                 g_free (utf8_filename);
2864                 goto retry;
2865         }
2866         ret = TRUE;
2867         
2868         /* utf16 is 2 * utf8 */
2869         bytes *= 2;
2870
2871         memset (find_data->cFileName, '\0', (MAX_PATH*2));
2872
2873         /* Truncating a utf16 string like this might leave the last
2874          * char incomplete
2875          */
2876         memcpy (find_data->cFileName, utf16_basename,
2877                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
2878
2879         find_data->cAlternateFileName [0] = 0;  /* not used */
2880
2881         g_free (utf8_basename);
2882         g_free (utf8_filename);
2883         g_free (utf16_basename);
2884
2885 cleanup:
2886         thr_ret = _wapi_handle_unlock_handle (handle);
2887         g_assert (thr_ret == 0);
2888         
2889         return(ret);
2890 }
2891
2892 /**
2893  * FindClose:
2894  * @wapi_handle: the find handle to close.
2895  *
2896  * Closes find handle @wapi_handle
2897  *
2898  * Return value: %TRUE on success, %FALSE otherwise.
2899  */
2900 gboolean FindClose (gpointer handle)
2901 {
2902         struct _WapiHandle_find *find_handle;
2903         gboolean ok;
2904         int thr_ret;
2905
2906         if (handle == NULL) {
2907                 SetLastError (ERROR_INVALID_HANDLE);
2908                 return(FALSE);
2909         }
2910         
2911         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2912                                 (gpointer *)&find_handle);
2913         if(ok==FALSE) {
2914                 g_warning ("%s: error looking up find handle %p", __func__,
2915                            handle);
2916                 SetLastError (ERROR_INVALID_HANDLE);
2917                 return(FALSE);
2918         }
2919
2920         thr_ret = _wapi_handle_lock_handle (handle);
2921         g_assert (thr_ret == 0);
2922         
2923         g_strfreev (find_handle->namelist);
2924         g_free (find_handle->dir_part);
2925
2926         thr_ret = _wapi_handle_unlock_handle (handle);
2927         g_assert (thr_ret == 0);
2928         
2929         _wapi_handle_unref (handle);
2930         
2931         return(TRUE);
2932 }
2933
2934 /**
2935  * CreateDirectory:
2936  * @name: a pointer to a NULL-terminated unicode string, that names
2937  * the directory to be created.
2938  * @security: ignored for now
2939  *
2940  * Creates directory @name
2941  *
2942  * Return value: %TRUE on success, %FALSE otherwise.
2943  */
2944 gboolean CreateDirectory (const gunichar2 *name,
2945                           WapiSecurityAttributes *security)
2946 {
2947         gchar *utf8_name;
2948         int result;
2949         
2950         if (name == NULL) {
2951                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2952
2953                 SetLastError (ERROR_INVALID_NAME);
2954                 return(FALSE);
2955         }
2956         
2957         utf8_name = mono_unicode_to_external (name);
2958         if (utf8_name == NULL) {
2959                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
2960         
2961                 SetLastError (ERROR_INVALID_NAME);
2962                 return FALSE;
2963         }
2964
2965         result = _wapi_mkdir (utf8_name, 0777);
2966
2967         if (result == 0) {
2968                 g_free (utf8_name);
2969                 return TRUE;
2970         }
2971
2972         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
2973         g_free (utf8_name);
2974         return FALSE;
2975 }
2976
2977 /**
2978  * RemoveDirectory:
2979  * @name: a pointer to a NULL-terminated unicode string, that names
2980  * the directory to be removed.
2981  *
2982  * Removes directory @name
2983  *
2984  * Return value: %TRUE on success, %FALSE otherwise.
2985  */
2986 gboolean RemoveDirectory (const gunichar2 *name)
2987 {
2988         gchar *utf8_name;
2989         int result;
2990         
2991         if (name == NULL) {
2992                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
2993
2994                 SetLastError (ERROR_INVALID_NAME);
2995                 return(FALSE);
2996         }
2997
2998         utf8_name = mono_unicode_to_external (name);
2999         if (utf8_name == NULL) {
3000                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3001                 
3002                 SetLastError (ERROR_INVALID_NAME);
3003                 return FALSE;
3004         }
3005
3006         result = _wapi_rmdir (utf8_name);
3007         if (result == -1) {
3008                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3009                 g_free (utf8_name);
3010                 
3011                 return(FALSE);
3012         }
3013         g_free (utf8_name);
3014
3015         return(TRUE);
3016 }
3017
3018 /**
3019  * GetFileAttributes:
3020  * @name: a pointer to a NULL-terminated unicode filename.
3021  *
3022  * Gets the attributes for @name;
3023  *
3024  * Return value: %INVALID_FILE_ATTRIBUTES on failure
3025  */
3026 guint32 GetFileAttributes (const gunichar2 *name)
3027 {
3028         gchar *utf8_name;
3029         struct stat buf, linkbuf;
3030         int result;
3031         guint32 ret;
3032         
3033         if (name == NULL) {
3034                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3035
3036                 SetLastError (ERROR_INVALID_NAME);
3037                 return(FALSE);
3038         }
3039         
3040         utf8_name = mono_unicode_to_external (name);
3041         if (utf8_name == NULL) {
3042                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3043
3044                 SetLastError (ERROR_INVALID_PARAMETER);
3045                 return (INVALID_FILE_ATTRIBUTES);
3046         }
3047
3048         result = _wapi_stat (utf8_name, &buf);
3049         if (result == -1 && errno == ENOENT) {
3050                 /* Might be a dangling symlink... */
3051                 result = _wapi_lstat (utf8_name, &buf);
3052         }
3053
3054         if (result != 0) {
3055                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3056                 g_free (utf8_name);
3057                 return (INVALID_FILE_ATTRIBUTES);
3058         }
3059
3060 #ifndef __native_client__
3061         result = _wapi_lstat (utf8_name, &linkbuf);
3062         if (result != 0) {
3063                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3064                 g_free (utf8_name);
3065                 return (INVALID_FILE_ATTRIBUTES);
3066         }
3067 #endif
3068         
3069 #ifdef __native_client__
3070         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, NULL);
3071 #else
3072         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3073 #endif
3074         
3075         g_free (utf8_name);
3076
3077         return(ret);
3078 }
3079
3080 /**
3081  * GetFileAttributesEx:
3082  * @name: a pointer to a NULL-terminated unicode filename.
3083  * @level: must be GetFileExInfoStandard
3084  * @info: pointer to a WapiFileAttributesData structure
3085  *
3086  * Gets attributes, size and filetimes for @name;
3087  *
3088  * Return value: %TRUE on success, %FALSE on failure
3089  */
3090 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3091 {
3092         gchar *utf8_name;
3093         WapiFileAttributesData *data;
3094
3095         struct stat buf, linkbuf;
3096         time_t create_time;
3097         int result;
3098         
3099         if (level != GetFileExInfoStandard) {
3100                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: info level %d not supported.", __func__,
3101                            level);
3102
3103                 SetLastError (ERROR_INVALID_PARAMETER);
3104                 return FALSE;
3105         }
3106         
3107         if (name == NULL) {
3108                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3109
3110                 SetLastError (ERROR_INVALID_NAME);
3111                 return(FALSE);
3112         }
3113
3114         utf8_name = mono_unicode_to_external (name);
3115         if (utf8_name == NULL) {
3116                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3117
3118                 SetLastError (ERROR_INVALID_PARAMETER);
3119                 return FALSE;
3120         }
3121
3122         result = _wapi_stat (utf8_name, &buf);
3123         if (result == -1 && errno == ENOENT) {
3124                 /* Might be a dangling symlink... */
3125                 result = _wapi_lstat (utf8_name, &buf);
3126         }
3127         
3128         if (result != 0) {
3129                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3130                 g_free (utf8_name);
3131                 return FALSE;
3132         }
3133
3134         result = _wapi_lstat (utf8_name, &linkbuf);
3135         if (result != 0) {
3136                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3137                 g_free (utf8_name);
3138                 return(FALSE);
3139         }
3140
3141         /* fill data block */
3142
3143         data = (WapiFileAttributesData *)info;
3144
3145         if (buf.st_mtime < buf.st_ctime)
3146                 create_time = buf.st_mtime;
3147         else
3148                 create_time = buf.st_ctime;
3149         
3150         data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3151                                                                 &buf,
3152                                                                 &linkbuf);
3153
3154         g_free (utf8_name);
3155
3156         _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3157         _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3158         _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3159
3160         if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3161                 data->nFileSizeHigh = 0;
3162                 data->nFileSizeLow = 0;
3163         }
3164         else {
3165                 data->nFileSizeHigh = buf.st_size >> 32;
3166                 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3167         }
3168
3169         return TRUE;
3170 }
3171
3172 /**
3173  * SetFileAttributes
3174  * @name: name of file
3175  * @attrs: attributes to set
3176  *
3177  * Changes the attributes on a named file.
3178  *
3179  * Return value: %TRUE on success, %FALSE on failure.
3180  */
3181 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3182 {
3183         /* FIXME: think of something clever to do on unix */
3184         gchar *utf8_name;
3185         struct stat buf;
3186         int result;
3187
3188         /*
3189          * Currently we only handle one *internal* case, with a value that is
3190          * not standard: 0x80000000, which means `set executable bit'
3191          */
3192         
3193         if (name == NULL) {
3194                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: name is NULL", __func__);
3195
3196                 SetLastError (ERROR_INVALID_NAME);
3197                 return(FALSE);
3198         }
3199
3200         utf8_name = mono_unicode_to_external (name);
3201         if (utf8_name == NULL) {
3202                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3203
3204                 SetLastError (ERROR_INVALID_NAME);
3205                 return FALSE;
3206         }
3207
3208         result = _wapi_stat (utf8_name, &buf);
3209         if (result == -1 && errno == ENOENT) {
3210                 /* Might be a dangling symlink... */
3211                 result = _wapi_lstat (utf8_name, &buf);
3212         }
3213
3214         if (result != 0) {
3215                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3216                 g_free (utf8_name);
3217                 return FALSE;
3218         }
3219
3220         /* Contrary to the documentation, ms allows NORMAL to be
3221          * specified along with other attributes, so dont bother to
3222          * catch that case here.
3223          */
3224         if (attrs & FILE_ATTRIBUTE_READONLY) {
3225                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWUSR | S_IWOTH | S_IWGRP));
3226         } else {
3227                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWUSR);
3228         }
3229
3230         /* Ignore the other attributes for now */
3231
3232         if (attrs & 0x80000000){
3233                 mode_t exec_mask = 0;
3234
3235                 if ((buf.st_mode & S_IRUSR) != 0)
3236                         exec_mask |= S_IXUSR;
3237
3238                 if ((buf.st_mode & S_IRGRP) != 0)
3239                         exec_mask |= S_IXGRP;
3240
3241                 if ((buf.st_mode & S_IROTH) != 0)
3242                         exec_mask |= S_IXOTH;
3243
3244                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3245         }
3246         /* Don't bother to reset executable (might need to change this
3247          * policy)
3248          */
3249         
3250         g_free (utf8_name);
3251
3252         return(TRUE);
3253 }
3254
3255 /**
3256  * GetCurrentDirectory
3257  * @length: size of the buffer
3258  * @buffer: pointer to buffer that recieves path
3259  *
3260  * Retrieves the current directory for the current process.
3261  *
3262  * Return value: number of characters in buffer on success, zero on failure
3263  */
3264 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3265 {
3266         gunichar2 *utf16_path;
3267         glong count;
3268         gsize bytes;
3269
3270 #ifdef __native_client__
3271         gchar *path = g_get_current_dir ();
3272         if (length < strlen(path) + 1 || path == NULL)
3273                 return 0;
3274         memcpy (buffer, path, strlen(path) + 1);
3275 #else
3276         if (getcwd ((char*)buffer, length) == NULL) {
3277                 if (errno == ERANGE) { /*buffer length is not big enough */ 
3278                         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*/
3279                         if (path == NULL)
3280                                 return 0;
3281                         utf16_path = mono_unicode_from_external (path, &bytes);
3282                         g_free (utf16_path);
3283                         g_free (path);
3284                         return (bytes/2)+1;
3285                 }
3286                 _wapi_set_last_error_from_errno ();
3287                 return 0;
3288         }
3289 #endif
3290
3291         utf16_path = mono_unicode_from_external ((gchar*)buffer, &bytes);
3292         count = (bytes/2)+1;
3293         g_assert (count <= length); /*getcwd must have failed before with ERANGE*/
3294
3295         /* Add the terminator */
3296         memset (buffer, '\0', bytes+2);
3297         memcpy (buffer, utf16_path, bytes);
3298         
3299         g_free (utf16_path);
3300
3301         return count;
3302 }
3303
3304 /**
3305  * SetCurrentDirectory
3306  * @path: path to new directory
3307  *
3308  * Changes the directory path for the current process.
3309  *
3310  * Return value: %TRUE on success, %FALSE on failure.
3311  */
3312 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3313 {
3314         gchar *utf8_path;
3315         gboolean result;
3316
3317         if (path == NULL) {
3318                 SetLastError (ERROR_INVALID_PARAMETER);
3319                 return(FALSE);
3320         }
3321         
3322         utf8_path = mono_unicode_to_external (path);
3323         if (_wapi_chdir (utf8_path) != 0) {
3324                 _wapi_set_last_error_from_errno ();
3325                 result = FALSE;
3326         }
3327         else
3328                 result = TRUE;
3329
3330         g_free (utf8_path);
3331         return result;
3332 }
3333
3334 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3335                      WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3336 {
3337         struct _WapiHandle_file pipe_read_handle = {0};
3338         struct _WapiHandle_file pipe_write_handle = {0};
3339         gpointer read_handle;
3340         gpointer write_handle;
3341         int filedes[2];
3342         int ret;
3343         
3344         mono_once (&io_ops_once, io_ops_init);
3345         
3346         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Creating pipe", __func__);
3347
3348         ret=pipe (filedes);
3349         if(ret==-1) {
3350                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Error creating pipe: %s", __func__,
3351                            strerror (errno));
3352                 
3353                 _wapi_set_last_error_from_errno ();
3354                 return(FALSE);
3355         }
3356
3357         if (filedes[0] >= _wapi_fd_reserve ||
3358             filedes[1] >= _wapi_fd_reserve) {
3359                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: File descriptor is too big", __func__);
3360
3361                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3362                 
3363                 close (filedes[0]);
3364                 close (filedes[1]);
3365                 
3366                 return(FALSE);
3367         }
3368         
3369         /* filedes[0] is open for reading, filedes[1] for writing */
3370
3371         pipe_read_handle.fd = filedes [0];
3372         pipe_read_handle.fileaccess = GENERIC_READ;
3373         read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3374                                            &pipe_read_handle);
3375         if (read_handle == _WAPI_HANDLE_INVALID) {
3376                 g_warning ("%s: error creating pipe read handle", __func__);
3377                 close (filedes[0]);
3378                 close (filedes[1]);
3379                 SetLastError (ERROR_GEN_FAILURE);
3380                 
3381                 return(FALSE);
3382         }
3383         
3384         pipe_write_handle.fd = filedes [1];
3385         pipe_write_handle.fileaccess = GENERIC_WRITE;
3386         write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3387                                             &pipe_write_handle);
3388         if (write_handle == _WAPI_HANDLE_INVALID) {
3389                 g_warning ("%s: error creating pipe write handle", __func__);
3390                 _wapi_handle_unref (read_handle);
3391                 
3392                 close (filedes[0]);
3393                 close (filedes[1]);
3394                 SetLastError (ERROR_GEN_FAILURE);
3395                 
3396                 return(FALSE);
3397         }
3398         
3399         *readpipe = read_handle;
3400         *writepipe = write_handle;
3401
3402         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Returning pipe: read handle %p, write handle %p",
3403                    __func__, read_handle, write_handle);
3404
3405         return(TRUE);
3406 }
3407
3408 #ifdef HAVE_GETFSSTAT
3409 /* Darwin has getfsstat */
3410 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3411 {
3412         struct statfs *stats;
3413         int size, n, i;
3414         gunichar2 *dir;
3415         glong length, total = 0;
3416         
3417         n = getfsstat (NULL, 0, MNT_NOWAIT);
3418         if (n == -1)
3419                 return 0;
3420         size = n * sizeof (struct statfs);
3421         stats = (struct statfs *) g_malloc (size);
3422         if (stats == NULL)
3423                 return 0;
3424         if (getfsstat (stats, size, MNT_NOWAIT) == -1){
3425                 g_free (stats);
3426                 return 0;
3427         }
3428         for (i = 0; i < n; i++){
3429                 dir = g_utf8_to_utf16 (stats [i].f_mntonname, -1, NULL, &length, NULL);
3430                 if (total + length < len){
3431                         memcpy (buf + total, dir, sizeof (gunichar2) * length);
3432                         buf [total+length] = 0;
3433                 } 
3434                 g_free (dir);
3435                 total += length + 1;
3436         }
3437         if (total < len)
3438                 buf [total] = 0;
3439         total++;
3440         g_free (stats);
3441         return total;
3442 }
3443 #else
3444 /* In-place octal sequence replacement */
3445 static void
3446 unescape_octal (gchar *str)
3447 {
3448         gchar *rptr;
3449         gchar *wptr;
3450
3451         if (str == NULL)
3452                 return;
3453
3454         rptr = wptr = str;
3455         while (*rptr != '\0') {
3456                 if (*rptr == '\\') {
3457                         char c;
3458                         rptr++;
3459                         c = (*(rptr++) - '0') << 6;
3460                         c += (*(rptr++) - '0') << 3;
3461                         c += *(rptr++) - '0';
3462                         *wptr++ = c;
3463                 } else if (wptr != rptr) {
3464                         *wptr++ = *rptr++;
3465                 } else {
3466                         rptr++; wptr++;
3467                 }
3468         }
3469         *wptr = '\0';
3470 }
3471 static gint32 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf);
3472
3473 #if __linux__
3474 #define GET_LOGICAL_DRIVE_STRINGS_BUFFER 512
3475 #define GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER 512
3476 #define GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER 64
3477
3478 typedef struct 
3479 {
3480         glong total;
3481         guint32 buffer_index;
3482         guint32 mountpoint_index;
3483         guint32 field_number;
3484         guint32 allocated_size;
3485         guint32 fsname_index;
3486         guint32 fstype_index;
3487         gchar mountpoint [GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER + 1];
3488         gchar *mountpoint_allocated;
3489         gchar buffer [GET_LOGICAL_DRIVE_STRINGS_BUFFER];
3490         gchar fsname [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3491         gchar fstype [GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER + 1];
3492         ssize_t nbytes;
3493         gchar delimiter;
3494         gboolean check_mount_source;
3495 } LinuxMountInfoParseState;
3496
3497 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3498 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3499 static void append_to_mountpoint (LinuxMountInfoParseState *state);
3500 static gboolean add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state);
3501
3502 gint32 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3503 {
3504         int fd;
3505         gint32 ret = 0;
3506         LinuxMountInfoParseState state;
3507         gboolean (*parser)(guint32, gunichar2*, LinuxMountInfoParseState*) = NULL;
3508
3509         memset (buf, 0, len * sizeof (gunichar2));
3510         fd = open ("/proc/self/mountinfo", O_RDONLY);
3511         if (fd != -1)
3512                 parser = GetLogicalDriveStrings_MountInfo;
3513         else {
3514                 fd = open ("/proc/mounts", O_RDONLY);
3515                 if (fd != -1)
3516                         parser = GetLogicalDriveStrings_Mounts;
3517         }
3518
3519         if (!parser) {
3520                 ret = GetLogicalDriveStrings_Mtab (len, buf);
3521                 goto done_and_out;
3522         }
3523
3524         memset (&state, 0, sizeof (LinuxMountInfoParseState));
3525         state.field_number = 1;
3526         state.delimiter = ' ';
3527
3528         while ((state.nbytes = read (fd, state.buffer, GET_LOGICAL_DRIVE_STRINGS_BUFFER)) > 0) {
3529                 state.buffer_index = 0;
3530
3531                 while ((*parser)(len, buf, &state)) {
3532                         if (state.buffer [state.buffer_index] == '\n') {
3533                                 gboolean quit = add_drive_string (len, buf, &state);
3534                                 state.field_number = 1;
3535                                 state.buffer_index++;
3536                                 if (state.mountpoint_allocated) {
3537                                         g_free (state.mountpoint_allocated);
3538                                         state.mountpoint_allocated = NULL;
3539                                 }
3540                                 if (quit) {
3541                                         ret = state.total;
3542                                         goto done_and_out;
3543                                 }
3544                         }
3545                 }
3546         };
3547         ret = state.total;
3548
3549   done_and_out:
3550         if (fd != -1)
3551                 close (fd);
3552         return ret;
3553 }
3554
3555 static gboolean GetLogicalDriveStrings_Mounts (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3556 {
3557         gchar *ptr;
3558
3559         if (state->field_number == 1)
3560                 state->check_mount_source = TRUE;
3561
3562         while (state->buffer_index < (guint32)state->nbytes) {
3563                 if (state->buffer [state->buffer_index] == state->delimiter) {
3564                         state->field_number++;
3565                         switch (state->field_number) {
3566                                 case 2:
3567                                         state->mountpoint_index = 0;
3568                                         break;
3569
3570                                 case 3:
3571                                         if (state->mountpoint_allocated)
3572                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3573                                         else
3574                                                 state->mountpoint [state->mountpoint_index] = 0;
3575                                         break;
3576
3577                                 default:
3578                                         ptr = (gchar*)memchr (state->buffer + state->buffer_index, '\n', GET_LOGICAL_DRIVE_STRINGS_BUFFER - state->buffer_index);
3579                                         if (ptr)
3580                                                 state->buffer_index = (ptr - (gchar*)state->buffer) - 1;
3581                                         else
3582                                                 state->buffer_index = state->nbytes;
3583                                         return TRUE;
3584                         }
3585                         state->buffer_index++;
3586                         continue;
3587                 } else if (state->buffer [state->buffer_index] == '\n')
3588                         return TRUE;
3589
3590                 switch (state->field_number) {
3591                         case 1:
3592                                 if (state->check_mount_source) {
3593                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3594                                                 /* We can ignore the rest, it's a device
3595                                                  * path */
3596                                                 state->check_mount_source = FALSE;
3597                                                 state->fsname [state->fsname_index++] = '/';
3598                                                 break;
3599                                         }
3600                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3601                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3602                                 }
3603                                 break;
3604
3605                         case 2:
3606                                 append_to_mountpoint (state);
3607                                 break;
3608
3609                         case 3:
3610                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3611                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3612                                 break;
3613                 }
3614
3615                 state->buffer_index++;
3616         }
3617
3618         return FALSE;
3619 }
3620
3621 static gboolean GetLogicalDriveStrings_MountInfo (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3622 {
3623         while (state->buffer_index < (guint32)state->nbytes) {
3624                 if (state->buffer [state->buffer_index] == state->delimiter) {
3625                         state->field_number++;
3626                         switch (state->field_number) {
3627                                 case 5:
3628                                         state->mountpoint_index = 0;
3629                                         break;
3630
3631                                 case 6:
3632                                         if (state->mountpoint_allocated)
3633                                                 state->mountpoint_allocated [state->mountpoint_index] = 0;
3634                                         else
3635                                                 state->mountpoint [state->mountpoint_index] = 0;
3636                                         break;
3637
3638                                 case 7:
3639                                         state->delimiter = '-';
3640                                         break;
3641
3642                                 case 8:
3643                                         state->delimiter = ' ';
3644                                         break;
3645
3646                                 case 10:
3647                                         state->check_mount_source = TRUE;
3648                                         break;
3649                         }
3650                         state->buffer_index++;
3651                         continue;
3652                 } else if (state->buffer [state->buffer_index] == '\n')
3653                         return TRUE;
3654
3655                 switch (state->field_number) {
3656                         case 5:
3657                                 append_to_mountpoint (state);
3658                                 break;
3659
3660                         case 9:
3661                                 if (state->fstype_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3662                                         state->fstype [state->fstype_index++] = state->buffer [state->buffer_index];
3663                                 break;
3664
3665                         case 10:
3666                                 if (state->check_mount_source) {
3667                                         if (state->fsname_index == 0 && state->buffer [state->buffer_index] == '/') {
3668                                                 /* We can ignore the rest, it's a device
3669                                                  * path */
3670                                                 state->check_mount_source = FALSE;
3671                                                 state->fsname [state->fsname_index++] = '/';
3672                                                 break;
3673                                         }
3674                                         if (state->fsname_index < GET_LOGICAL_DRIVE_STRINGS_FSNAME_BUFFER)
3675                                                 state->fsname [state->fsname_index++] = state->buffer [state->buffer_index];
3676                                 }
3677                                 break;
3678                 }
3679
3680                 state->buffer_index++;
3681         }
3682
3683         return FALSE;
3684 }
3685
3686 static void
3687 append_to_mountpoint (LinuxMountInfoParseState *state)
3688 {
3689         gchar ch = state->buffer [state->buffer_index];
3690         if (state->mountpoint_allocated) {
3691                 if (state->mountpoint_index >= state->allocated_size) {
3692                         guint32 newsize = (state->allocated_size << 1) + 1;
3693                         gchar *newbuf = (gchar *)g_malloc0 (newsize * sizeof (gchar));
3694
3695                         memcpy (newbuf, state->mountpoint_allocated, state->mountpoint_index);
3696                         g_free (state->mountpoint_allocated);
3697                         state->mountpoint_allocated = newbuf;
3698                         state->allocated_size = newsize;
3699                 }
3700                 state->mountpoint_allocated [state->mountpoint_index++] = ch;
3701         } else {
3702                 if (state->mountpoint_index >= GET_LOGICAL_DRIVE_STRINGS_MOUNTPOINT_BUFFER) {
3703                         state->allocated_size = (state->mountpoint_index << 1) + 1;
3704                         state->mountpoint_allocated = (gchar *)g_malloc0 (state->allocated_size * sizeof (gchar));
3705                         memcpy (state->mountpoint_allocated, state->mountpoint, state->mountpoint_index);
3706                         state->mountpoint_allocated [state->mountpoint_index++] = ch;
3707                 } else
3708                         state->mountpoint [state->mountpoint_index++] = ch;
3709         }
3710 }
3711
3712 static gboolean
3713 add_drive_string (guint32 len, gunichar2 *buf, LinuxMountInfoParseState *state)
3714 {
3715         gboolean quit = FALSE;
3716         gboolean ignore_entry;
3717
3718         if (state->fsname_index == 1 && state->fsname [0] == '/')
3719                 ignore_entry = FALSE;
3720         else if (memcmp ("overlay", state->fsname, state->fsname_index) == 0 ||
3721                 memcmp ("aufs", state->fstype, state->fstype_index) == 0) {
3722                 /* Don't ignore overlayfs and aufs - these might be used on Docker
3723                  * (https://bugzilla.xamarin.com/show_bug.cgi?id=31021) */
3724                 ignore_entry = FALSE;
3725         } else if (state->fsname_index == 0 || memcmp ("none", state->fsname, state->fsname_index) == 0) {
3726                 ignore_entry = TRUE;
3727         } else if (state->fstype_index >= 5 && memcmp ("fuse.", state->fstype, 5) == 0) {
3728                 /* Ignore GNOME's gvfs */
3729                 if (state->fstype_index == 21 && memcmp ("fuse.gvfs-fuse-daemon", state->fstype, state->fstype_index) == 0)
3730                         ignore_entry = TRUE;
3731                 else
3732                         ignore_entry = FALSE;
3733         } else if (state->fstype_index == 3 && memcmp ("nfs", state->fstype, state->fstype_index) == 0)
3734                 ignore_entry = FALSE;
3735         else
3736                 ignore_entry = TRUE;
3737
3738         if (!ignore_entry) {
3739                 gunichar2 *dir;
3740                 glong length;
3741                 gchar *mountpoint = state->mountpoint_allocated ? state->mountpoint_allocated : state->mountpoint;
3742
3743                 unescape_octal (mountpoint);
3744                 dir = g_utf8_to_utf16 (mountpoint, -1, NULL, &length, NULL);
3745                 if (state->total + length + 1 > len) {
3746                         quit = TRUE;
3747                         state->total = len * 2;
3748                 } else {
3749                         length++;
3750                         memcpy (buf + state->total, dir, sizeof (gunichar2) * length);
3751                         state->total += length;
3752                 }
3753                 g_free (dir);
3754         }
3755         state->fsname_index = 0;
3756         state->fstype_index = 0;
3757
3758         return quit;
3759 }
3760 #else
3761 gint32
3762 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3763 {
3764         return GetLogicalDriveStrings_Mtab (len, buf);
3765 }
3766 #endif
3767 static gint32
3768 GetLogicalDriveStrings_Mtab (guint32 len, gunichar2 *buf)
3769 {
3770         FILE *fp;
3771         gunichar2 *ptr, *dir;
3772         glong length, total = 0;
3773         gchar buffer [512];
3774         gchar **splitted;
3775
3776         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
3777         buf [0] = '/';
3778         buf [1] = 0;
3779         buf [2] = 0;
3780
3781         /* Sigh, mntent and friends don't work well.
3782          * It stops on the first line that doesn't begin with a '/'.
3783          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3784         fp = fopen ("/etc/mtab", "rt");
3785         if (fp == NULL) {
3786                 fp = fopen ("/etc/mnttab", "rt");
3787                 if (fp == NULL)
3788                         return 1;
3789         }
3790
3791         ptr = buf;
3792         while (fgets (buffer, 512, fp) != NULL) {
3793                 if (*buffer != '/')
3794                         continue;
3795
3796                 splitted = g_strsplit (buffer, " ", 0);
3797                 if (!*splitted || !*(splitted + 1)) {
3798                         g_strfreev (splitted);
3799                         continue;
3800                 }
3801
3802                 unescape_octal (*(splitted + 1));
3803                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, NULL, &length, NULL);
3804                 g_strfreev (splitted);
3805                 if (total + length + 1 > len) {
3806                         fclose (fp);
3807                         g_free (dir);
3808                         return len * 2; /* guess */
3809                 }
3810
3811                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3812                 g_free (dir);
3813                 total += length + 1;
3814         }
3815
3816         fclose (fp);
3817         return total;
3818 /* Commented out, does not work with my mtab!!! - Gonz */
3819 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3820 {
3821         FILE *fp;
3822         struct mntent *mnt;
3823         gunichar2 *ptr, *dir;
3824         glong len, total = 0;
3825         
3826
3827         fp = setmntent ("/etc/mtab", "rt");
3828         if (fp == NULL) {
3829                 fp = setmntent ("/etc/mnttab", "rt");
3830                 if (fp == NULL)
3831                         return;
3832         }
3833
3834         ptr = buf;
3835         while ((mnt = getmntent (fp)) != NULL) {
3836                 g_print ("GOT %s\n", mnt->mnt_dir);
3837                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3838                 if (total + len + 1 > len) {
3839                         return len * 2; /* guess */
3840                 }
3841
3842                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3843                 g_free (dir);
3844                 total += len + 1;
3845         }
3846
3847         endmntent (fp);
3848         return total;
3849 }
3850 #endif
3851 }
3852 #endif
3853
3854 #if defined(HAVE_STATVFS) || defined(HAVE_STATFS)
3855 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3856                             WapiULargeInteger *total_number_of_bytes,
3857                             WapiULargeInteger *total_number_of_free_bytes)
3858 {
3859 #ifdef HAVE_STATVFS
3860         struct statvfs fsstat;
3861 #elif defined(HAVE_STATFS)
3862         struct statfs fsstat;
3863 #endif
3864         gboolean isreadonly;
3865         gchar *utf8_path_name;
3866         int ret;
3867         unsigned long block_size;
3868
3869         if (path_name == NULL) {
3870                 utf8_path_name = g_strdup (g_get_current_dir());
3871                 if (utf8_path_name == NULL) {
3872                         SetLastError (ERROR_DIRECTORY);
3873                         return(FALSE);
3874                 }
3875         }
3876         else {
3877                 utf8_path_name = mono_unicode_to_external (path_name);
3878                 if (utf8_path_name == NULL) {
3879                         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
3880
3881                         SetLastError (ERROR_INVALID_NAME);
3882                         return(FALSE);
3883                 }
3884         }
3885
3886         do {
3887 #ifdef HAVE_STATVFS
3888                 ret = statvfs (utf8_path_name, &fsstat);
3889                 isreadonly = ((fsstat.f_flag & ST_RDONLY) == ST_RDONLY);
3890                 block_size = fsstat.f_frsize;
3891 #elif defined(HAVE_STATFS)
3892                 ret = statfs (utf8_path_name, &fsstat);
3893 #if defined (MNT_RDONLY)
3894                 isreadonly = ((fsstat.f_flags & MNT_RDONLY) == MNT_RDONLY);
3895 #elif defined (MS_RDONLY)
3896                 isreadonly = ((fsstat.f_flags & MS_RDONLY) == MS_RDONLY);
3897 #endif
3898                 block_size = fsstat.f_bsize;
3899 #endif
3900         } while(ret == -1 && errno == EINTR);
3901
3902         g_free(utf8_path_name);
3903
3904         if (ret == -1) {
3905                 _wapi_set_last_error_from_errno ();
3906                 MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: statvfs failed: %s", __func__, strerror (errno));
3907                 return(FALSE);
3908         }
3909
3910         /* total number of free bytes for non-root */
3911         if (free_bytes_avail != NULL) {
3912                 if (isreadonly) {
3913                         free_bytes_avail->QuadPart = 0;
3914                 }
3915                 else {
3916                         free_bytes_avail->QuadPart = block_size * (guint64)fsstat.f_bavail;
3917                 }
3918         }
3919
3920         /* total number of bytes available for non-root */
3921         if (total_number_of_bytes != NULL) {
3922                 total_number_of_bytes->QuadPart = block_size * (guint64)fsstat.f_blocks;
3923         }
3924
3925         /* total number of bytes available for root */
3926         if (total_number_of_free_bytes != NULL) {
3927                 if (isreadonly) {
3928                         total_number_of_free_bytes->QuadPart = 0;
3929                 }
3930                 else {
3931                         total_number_of_free_bytes->QuadPart = block_size * (guint64)fsstat.f_bfree;
3932                 }
3933         }
3934         
3935         return(TRUE);
3936 }
3937 #else
3938 gboolean GetDiskFreeSpaceEx(const gunichar2 *path_name, WapiULargeInteger *free_bytes_avail,
3939                             WapiULargeInteger *total_number_of_bytes,
3940                             WapiULargeInteger *total_number_of_free_bytes)
3941 {
3942         if (free_bytes_avail != NULL) {
3943                 free_bytes_avail->QuadPart = (guint64) -1;
3944         }
3945
3946         if (total_number_of_bytes != NULL) {
3947                 total_number_of_bytes->QuadPart = (guint64) -1;
3948         }
3949
3950         if (total_number_of_free_bytes != NULL) {
3951                 total_number_of_free_bytes->QuadPart = (guint64) -1;
3952         }
3953
3954         return(TRUE);
3955 }
3956 #endif
3957
3958 /*
3959  * General Unix support
3960  */
3961 typedef struct {
3962         guint32 drive_type;
3963 #if __linux__
3964         const long fstypeid;
3965 #endif
3966         const gchar* fstype;
3967 } _wapi_drive_type;
3968
3969 static _wapi_drive_type _wapi_drive_types[] = {
3970 #if PLATFORM_MACOSX
3971         { DRIVE_REMOTE, "afp" },
3972         { DRIVE_REMOTE, "autofs" },
3973         { DRIVE_CDROM, "cddafs" },
3974         { DRIVE_CDROM, "cd9660" },
3975         { DRIVE_RAMDISK, "devfs" },
3976         { DRIVE_FIXED, "exfat" },
3977         { DRIVE_RAMDISK, "fdesc" },
3978         { DRIVE_REMOTE, "ftp" },
3979         { DRIVE_FIXED, "hfs" },
3980         { DRIVE_FIXED, "msdos" },
3981         { DRIVE_REMOTE, "nfs" },
3982         { DRIVE_FIXED, "ntfs" },
3983         { DRIVE_REMOTE, "smbfs" },
3984         { DRIVE_FIXED, "udf" },
3985         { DRIVE_REMOTE, "webdav" },
3986         { DRIVE_UNKNOWN, NULL }
3987 #elif __linux__
3988         { DRIVE_FIXED, ADFS_SUPER_MAGIC, "adfs"},
3989         { DRIVE_FIXED, AFFS_SUPER_MAGIC, "affs"},
3990         { DRIVE_REMOTE, AFS_SUPER_MAGIC, "afs"},
3991         { DRIVE_RAMDISK, AUTOFS_SUPER_MAGIC, "autofs"},
3992         { DRIVE_RAMDISK, AUTOFS_SBI_MAGIC, "autofs4"},
3993         { DRIVE_REMOTE, CODA_SUPER_MAGIC, "coda" },
3994         { DRIVE_RAMDISK, CRAMFS_MAGIC, "cramfs"},
3995         { DRIVE_RAMDISK, CRAMFS_MAGIC_WEND, "cramfs"},
3996         { DRIVE_REMOTE, CIFS_MAGIC_NUMBER, "cifs"},
3997         { DRIVE_RAMDISK, DEBUGFS_MAGIC, "debugfs"},
3998         { DRIVE_RAMDISK, SYSFS_MAGIC, "sysfs"},
3999         { DRIVE_RAMDISK, SECURITYFS_MAGIC, "securityfs"},
4000         { DRIVE_RAMDISK, SELINUX_MAGIC, "selinuxfs"},
4001         { DRIVE_RAMDISK, RAMFS_MAGIC, "ramfs"},
4002         { DRIVE_FIXED, SQUASHFS_MAGIC, "squashfs"},
4003         { DRIVE_FIXED, EFS_SUPER_MAGIC, "efs"},
4004         { DRIVE_FIXED, EXT2_SUPER_MAGIC, "ext"},
4005         { DRIVE_FIXED, EXT3_SUPER_MAGIC, "ext"},
4006         { DRIVE_FIXED, EXT4_SUPER_MAGIC, "ext"},
4007         { DRIVE_REMOTE, XENFS_SUPER_MAGIC, "xenfs"},
4008         { DRIVE_FIXED, BTRFS_SUPER_MAGIC, "btrfs"},
4009         { DRIVE_FIXED, HFS_SUPER_MAGIC, "hfs"},
4010         { DRIVE_FIXED, HFSPLUS_SUPER_MAGIC, "hfsplus"},
4011         { DRIVE_FIXED, HPFS_SUPER_MAGIC, "hpfs"},
4012         { DRIVE_RAMDISK, HUGETLBFS_MAGIC, "hugetlbfs"},
4013         { DRIVE_CDROM, ISOFS_SUPER_MAGIC, "iso"},
4014         { DRIVE_FIXED, JFFS2_SUPER_MAGIC, "jffs2"},
4015         { DRIVE_RAMDISK, ANON_INODE_FS_MAGIC, "anon_inode"},
4016         { DRIVE_FIXED, JFS_SUPER_MAGIC, "jfs"},
4017         { DRIVE_FIXED, MINIX_SUPER_MAGIC, "minix"},
4018         { DRIVE_FIXED, MINIX_SUPER_MAGIC2, "minix v2"},
4019         { DRIVE_FIXED, MINIX2_SUPER_MAGIC, "minix2"},
4020         { DRIVE_FIXED, MINIX2_SUPER_MAGIC2, "minix2 v2"},
4021         { DRIVE_FIXED, MINIX3_SUPER_MAGIC, "minix3"},
4022         { DRIVE_FIXED, MSDOS_SUPER_MAGIC, "msdos"},
4023         { DRIVE_REMOTE, NCP_SUPER_MAGIC, "ncp"},
4024         { DRIVE_REMOTE, NFS_SUPER_MAGIC, "nfs"},
4025         { DRIVE_FIXED, NTFS_SB_MAGIC, "ntfs"},
4026         { DRIVE_RAMDISK, OPENPROM_SUPER_MAGIC, "openpromfs"},
4027         { DRIVE_RAMDISK, PROC_SUPER_MAGIC, "proc"},
4028         { DRIVE_FIXED, QNX4_SUPER_MAGIC, "qnx4"},
4029         { DRIVE_FIXED, REISERFS_SUPER_MAGIC, "reiserfs"},
4030         { DRIVE_RAMDISK, ROMFS_MAGIC, "romfs"},
4031         { DRIVE_REMOTE, SMB_SUPER_MAGIC, "samba"},
4032         { DRIVE_RAMDISK, CGROUP_SUPER_MAGIC, "cgroupfs"},
4033         { DRIVE_RAMDISK, FUTEXFS_SUPER_MAGIC, "futexfs"},
4034         { DRIVE_FIXED, SYSV2_SUPER_MAGIC, "sysv2"},
4035         { DRIVE_FIXED, SYSV4_SUPER_MAGIC, "sysv4"},
4036         { DRIVE_RAMDISK, TMPFS_MAGIC, "tmpfs"},
4037         { DRIVE_RAMDISK, DEVPTS_SUPER_MAGIC, "devpts"},
4038         { DRIVE_CDROM, UDF_SUPER_MAGIC, "udf"},
4039         { DRIVE_FIXED, UFS_MAGIC, "ufs"},
4040         { DRIVE_FIXED, UFS_MAGIC_BW, "ufs"},
4041         { DRIVE_FIXED, UFS2_MAGIC, "ufs2"},
4042         { DRIVE_FIXED, UFS_CIGAM, "ufs"},
4043         { DRIVE_RAMDISK, USBDEVICE_SUPER_MAGIC, "usbdev"},
4044         { DRIVE_FIXED, XENIX_SUPER_MAGIC, "xenix"},
4045         { DRIVE_FIXED, XFS_SB_MAGIC, "xfs"},
4046         { DRIVE_RAMDISK, FUSE_SUPER_MAGIC, "fuse"},
4047         { DRIVE_FIXED, V9FS_MAGIC, "9p"},
4048         { DRIVE_REMOTE, CEPH_SUPER_MAGIC, "ceph"},
4049         { DRIVE_RAMDISK, CONFIGFS_MAGIC, "configfs"},
4050         { DRIVE_RAMDISK, ECRYPTFS_SUPER_MAGIC, "eCryptfs"},
4051         { DRIVE_FIXED, EXOFS_SUPER_MAGIC, "exofs"},
4052         { DRIVE_FIXED, VXFS_SUPER_MAGIC, "vxfs"},
4053         { DRIVE_FIXED, VXFS_OLT_MAGIC, "vxfs_olt"},
4054         { DRIVE_REMOTE, GFS2_MAGIC, "gfs2"},
4055         { DRIVE_FIXED, LOGFS_MAGIC_U32, "logfs"},
4056         { DRIVE_FIXED, OCFS2_SUPER_MAGIC, "ocfs2"},
4057         { DRIVE_FIXED, OMFS_MAGIC, "omfs"},
4058         { DRIVE_FIXED, UBIFS_SUPER_MAGIC, "ubifs"},
4059         { DRIVE_UNKNOWN, 0, NULL}
4060 #else
4061         { DRIVE_RAMDISK, "ramfs"      },
4062         { DRIVE_RAMDISK, "tmpfs"      },
4063         { DRIVE_RAMDISK, "proc"       },
4064         { DRIVE_RAMDISK, "sysfs"      },
4065         { DRIVE_RAMDISK, "debugfs"    },
4066         { DRIVE_RAMDISK, "devpts"     },
4067         { DRIVE_RAMDISK, "securityfs" },
4068         { DRIVE_CDROM,   "iso9660"    },
4069         { DRIVE_FIXED,   "ext2"       },
4070         { DRIVE_FIXED,   "ext3"       },
4071         { DRIVE_FIXED,   "ext4"       },
4072         { DRIVE_FIXED,   "sysv"       },
4073         { DRIVE_FIXED,   "reiserfs"   },
4074         { DRIVE_FIXED,   "ufs"        },
4075         { DRIVE_FIXED,   "vfat"       },
4076         { DRIVE_FIXED,   "msdos"      },
4077         { DRIVE_FIXED,   "udf"        },
4078         { DRIVE_FIXED,   "hfs"        },
4079         { DRIVE_FIXED,   "hpfs"       },
4080         { DRIVE_FIXED,   "qnx4"       },
4081         { DRIVE_FIXED,   "ntfs"       },
4082         { DRIVE_FIXED,   "ntfs-3g"    },
4083         { DRIVE_REMOTE,  "smbfs"      },
4084         { DRIVE_REMOTE,  "fuse"       },
4085         { DRIVE_REMOTE,  "nfs"        },
4086         { DRIVE_REMOTE,  "nfs4"       },
4087         { DRIVE_REMOTE,  "cifs"       },
4088         { DRIVE_REMOTE,  "ncpfs"      },
4089         { DRIVE_REMOTE,  "coda"       },
4090         { DRIVE_REMOTE,  "afs"        },
4091         { DRIVE_UNKNOWN, NULL         }
4092 #endif
4093 };
4094
4095 #if __linux__
4096 static guint32 _wapi_get_drive_type(long f_type)
4097 {
4098         _wapi_drive_type *current;
4099
4100         current = &_wapi_drive_types[0];
4101         while (current->drive_type != DRIVE_UNKNOWN) {
4102                 if (current->fstypeid == f_type)
4103                         return current->drive_type;
4104                 current++;
4105         }
4106
4107         return DRIVE_UNKNOWN;
4108 }
4109 #else
4110 static guint32 _wapi_get_drive_type(const gchar* fstype)
4111 {
4112         _wapi_drive_type *current;
4113
4114         current = &_wapi_drive_types[0];
4115         while (current->drive_type != DRIVE_UNKNOWN) {
4116                 if (strcmp (current->fstype, fstype) == 0)
4117                         break;
4118
4119                 current++;
4120         }
4121         
4122         return current->drive_type;
4123 }
4124 #endif
4125
4126 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4127 static guint32
4128 GetDriveTypeFromPath (const char *utf8_root_path_name)
4129 {
4130         struct statfs buf;
4131         
4132         if (statfs (utf8_root_path_name, &buf) == -1)
4133                 return DRIVE_UNKNOWN;
4134 #if PLATFORM_MACOSX
4135         return _wapi_get_drive_type (buf.f_fstypename);
4136 #else
4137         return _wapi_get_drive_type (buf.f_type);
4138 #endif
4139 }
4140 #else
4141 static guint32
4142 GetDriveTypeFromPath (const gchar *utf8_root_path_name)
4143 {
4144         guint32 drive_type;
4145         FILE *fp;
4146         gchar buffer [512];
4147         gchar **splitted;
4148
4149         fp = fopen ("/etc/mtab", "rt");
4150         if (fp == NULL) {
4151                 fp = fopen ("/etc/mnttab", "rt");
4152                 if (fp == NULL) 
4153                         return(DRIVE_UNKNOWN);
4154         }
4155
4156         drive_type = DRIVE_NO_ROOT_DIR;
4157         while (fgets (buffer, 512, fp) != NULL) {
4158                 splitted = g_strsplit (buffer, " ", 0);
4159                 if (!*splitted || !*(splitted + 1) || !*(splitted + 2)) {
4160                         g_strfreev (splitted);
4161                         continue;
4162                 }
4163
4164                 /* compare given root_path_name with the one from mtab, 
4165                   if length of utf8_root_path_name is zero it must be the root dir */
4166                 if (strcmp (*(splitted + 1), utf8_root_path_name) == 0 ||
4167                     (strcmp (*(splitted + 1), "/") == 0 && strlen (utf8_root_path_name) == 0)) {
4168                         drive_type = _wapi_get_drive_type (*(splitted + 2));
4169                         /* it is possible this path might be mounted again with
4170                            a known type...keep looking */
4171                         if (drive_type != DRIVE_UNKNOWN) {
4172                                 g_strfreev (splitted);
4173                                 break;
4174                         }
4175                 }
4176
4177                 g_strfreev (splitted);
4178         }
4179
4180         fclose (fp);
4181         return drive_type;
4182 }
4183 #endif
4184
4185 guint32 GetDriveType(const gunichar2 *root_path_name)
4186 {
4187         gchar *utf8_root_path_name;
4188         guint32 drive_type;
4189
4190         if (root_path_name == NULL) {
4191                 utf8_root_path_name = g_strdup (g_get_current_dir());
4192                 if (utf8_root_path_name == NULL) {
4193                         return(DRIVE_NO_ROOT_DIR);
4194                 }
4195         }
4196         else {
4197                 utf8_root_path_name = mono_unicode_to_external (root_path_name);
4198                 if (utf8_root_path_name == NULL) {
4199                         MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
4200                         return(DRIVE_NO_ROOT_DIR);
4201                 }
4202                 
4203                 /* strip trailing slash for compare below */
4204                 if (g_str_has_suffix(utf8_root_path_name, "/") && utf8_root_path_name [1] != 0) {
4205                         utf8_root_path_name[strlen(utf8_root_path_name) - 1] = 0;
4206                 }
4207         }
4208         drive_type = GetDriveTypeFromPath (utf8_root_path_name);
4209         g_free (utf8_root_path_name);
4210
4211         return (drive_type);
4212 }
4213
4214 #if defined (PLATFORM_MACOSX) || defined (__linux__) || defined(PLATFORM_BSD) || defined(__native_client__) || defined(__FreeBSD_kernel__)
4215 static gchar*
4216 get_fstypename (gchar *utfpath)
4217 {
4218 #if defined (PLATFORM_MACOSX) || defined (__linux__)
4219         struct statfs stat;
4220 #if __linux__
4221         _wapi_drive_type *current;
4222 #endif
4223         if (statfs (utfpath, &stat) == -1)
4224                 return NULL;
4225 #if PLATFORM_MACOSX
4226         return g_strdup (stat.f_fstypename);
4227 #else
4228         current = &_wapi_drive_types[0];
4229         while (current->drive_type != DRIVE_UNKNOWN) {
4230                 if (stat.f_type == current->fstypeid)
4231                         return g_strdup (current->fstype);
4232                 current++;
4233         }
4234         return NULL;
4235 #endif
4236 #else
4237         return NULL;
4238 #endif
4239 }
4240
4241 /* Linux has struct statfs which has a different layout */
4242 gboolean
4243 GetVolumeInformation (const gunichar2 *path, gunichar2 *volumename, int volumesize, int *outserial, int *maxcomp, int *fsflags, gunichar2 *fsbuffer, int fsbuffersize)
4244 {
4245         gchar *utfpath;
4246         gchar *fstypename;
4247         gboolean status = FALSE;
4248         glong len;
4249         
4250         // We only support getting the file system type
4251         if (fsbuffer == NULL)
4252                 return 0;
4253         
4254         utfpath = mono_unicode_to_external (path);
4255         if ((fstypename = get_fstypename (utfpath)) != NULL){
4256                 gunichar2 *ret = g_utf8_to_utf16 (fstypename, -1, NULL, &len, NULL);
4257                 if (ret != NULL && len < fsbuffersize){
4258                         memcpy (fsbuffer, ret, len * sizeof (gunichar2));
4259                         fsbuffer [len] = 0;
4260                         status = TRUE;
4261                 }
4262                 if (ret != NULL)
4263                         g_free (ret);
4264                 g_free (fstypename);
4265         }
4266         g_free (utfpath);
4267         return status;
4268 }
4269 #endif
4270
4271
4272 void
4273 _wapi_io_init (void)
4274 {
4275         mono_os_mutex_init (&stdhandle_mutex);
4276 }