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