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