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