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