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