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