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