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