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