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