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