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