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