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