fixed tests
[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_ENCRYPTED){
1526                 SetLastError (ERROR_ENCRYPTION_FAILED);
1527                 return INVALID_HANDLE_VALUE;
1528         }
1529         
1530         if (name == NULL) {
1531 #ifdef DEBUG
1532                 g_message ("%s: name is NULL", __func__);
1533 #endif
1534
1535                 SetLastError (ERROR_INVALID_NAME);
1536                 return(INVALID_HANDLE_VALUE);
1537         }
1538
1539         filename = mono_unicode_to_external (name);
1540         if (filename == NULL) {
1541 #ifdef DEBUG
1542                 g_message("%s: unicode conversion returned NULL", __func__);
1543 #endif
1544
1545                 SetLastError (ERROR_INVALID_NAME);
1546                 return(INVALID_HANDLE_VALUE);
1547         }
1548         
1549 #ifdef DEBUG
1550         g_message ("%s: Opening %s with share 0x%x and access 0x%x", __func__,
1551                    filename, sharemode, fileaccess);
1552 #endif
1553         
1554         fd = _wapi_open (filename, flags, perms);
1555     
1556         /* If we were trying to open a directory with write permissions
1557          * (e.g. O_WRONLY or O_RDWR), this call will fail with
1558          * EISDIR. However, this is a bit bogus because calls to
1559          * manipulate the directory (e.g. SetFileTime) will still work on
1560          * the directory because they use other API calls
1561          * (e.g. utime()). Hence, if we failed with the EISDIR error, try
1562          * to open the directory again without write permission.
1563          */
1564         if (fd == -1 && errno == EISDIR)
1565         {
1566                 /* Try again but don't try to make it writable */
1567                 fd = open(filename, flags  & ~(O_RDWR|O_WRONLY), perms);
1568         }
1569         
1570         if (fd == -1) {
1571 #ifdef DEBUG
1572                 g_message("%s: Error opening file %s: %s", __func__, filename,
1573                           strerror(errno));
1574 #endif
1575                 _wapi_set_last_path_error_from_errno (NULL, filename);
1576                 g_free (filename);
1577
1578                 return(INVALID_HANDLE_VALUE);
1579         }
1580
1581         if (fd >= _wapi_fd_reserve) {
1582 #ifdef DEBUG
1583                 g_message ("%s: File descriptor is too big", __func__);
1584 #endif
1585
1586                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1587                 
1588                 close (fd);
1589                 g_free (filename);
1590                 
1591                 return(INVALID_HANDLE_VALUE);
1592         }
1593
1594         ret = fstat (fd, &statbuf);
1595         if (ret == -1) {
1596 #ifdef DEBUG
1597                 g_message ("%s: fstat error of file %s: %s", __func__,
1598                            filename, strerror (errno));
1599 #endif
1600                 _wapi_set_last_error_from_errno ();
1601                 g_free (filename);
1602                 close (fd);
1603                 
1604                 return(INVALID_HANDLE_VALUE);
1605         }
1606
1607         if (share_check (&statbuf, sharemode, fileaccess,
1608                          &file_handle.share_info, fd) == FALSE) {
1609                 SetLastError (ERROR_SHARING_VIOLATION);
1610                 g_free (filename);
1611                 close (fd);
1612                 
1613                 return (INVALID_HANDLE_VALUE);
1614         }
1615         if (file_handle.share_info == NULL) {
1616                 /* No space, so no more files can be opened */
1617 #ifdef DEBUG
1618                 g_message ("%s: No space in the share table", __func__);
1619 #endif
1620
1621                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
1622                 close (fd);
1623                 g_free (filename);
1624                 
1625                 return(INVALID_HANDLE_VALUE);
1626         }
1627         
1628         file_handle.filename = filename;
1629
1630         if(security!=NULL) {
1631                 //file_handle->security_attributes=_wapi_handle_scratch_store (
1632                 //security, sizeof(WapiSecurityAttributes));
1633         }
1634         
1635         file_handle.fileaccess=fileaccess;
1636         file_handle.sharemode=sharemode;
1637         file_handle.attrs=attrs;
1638
1639 #ifdef HAVE_POSIX_FADVISE
1640         if (attrs & FILE_FLAG_SEQUENTIAL_SCAN)
1641                 posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL);
1642         if (attrs & FILE_FLAG_RANDOM_ACCESS)
1643                 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM);
1644 #endif
1645         
1646 #ifndef S_ISFIFO
1647 #define S_ISFIFO(m) ((m & S_IFIFO) != 0)
1648 #endif
1649         if (S_ISFIFO (statbuf.st_mode)) {
1650                 handle_type = WAPI_HANDLE_PIPE;
1651         } else if (S_ISCHR (statbuf.st_mode)) {
1652                 handle_type = WAPI_HANDLE_CONSOLE;
1653         } else {
1654                 handle_type = WAPI_HANDLE_FILE;
1655         }
1656
1657         handle = _wapi_handle_new_fd (handle_type, fd, &file_handle);
1658         if (handle == _WAPI_HANDLE_INVALID) {
1659                 g_warning ("%s: error creating file handle", __func__);
1660                 g_free (filename);
1661                 close (fd);
1662                 
1663                 SetLastError (ERROR_GEN_FAILURE);
1664                 return(INVALID_HANDLE_VALUE);
1665         }
1666         
1667 #ifdef DEBUG
1668         g_message("%s: returning handle %p", __func__, handle);
1669 #endif
1670         
1671         return(handle);
1672 }
1673
1674 /**
1675  * DeleteFile:
1676  * @name: a pointer to a NULL-terminated unicode string, that names
1677  * the file to be deleted.
1678  *
1679  * Deletes file @name.
1680  *
1681  * Return value: %TRUE on success, %FALSE otherwise.
1682  */
1683 gboolean DeleteFile(const gunichar2 *name)
1684 {
1685         gchar *filename;
1686         int retval;
1687         gboolean ret = FALSE;
1688         
1689         if(name==NULL) {
1690 #ifdef DEBUG
1691                 g_message("%s: name is NULL", __func__);
1692 #endif
1693
1694                 SetLastError (ERROR_INVALID_NAME);
1695                 return(FALSE);
1696         }
1697
1698         filename=mono_unicode_to_external(name);
1699         if(filename==NULL) {
1700 #ifdef DEBUG
1701                 g_message("%s: unicode conversion returned NULL", __func__);
1702 #endif
1703
1704                 SetLastError (ERROR_INVALID_NAME);
1705                 return(FALSE);
1706         }
1707         
1708         retval = _wapi_unlink (filename);
1709         
1710         if (retval == -1) {
1711                 _wapi_set_last_path_error_from_errno (NULL, filename);
1712         } else {
1713                 ret = TRUE;
1714         }
1715
1716         g_free(filename);
1717
1718         return(ret);
1719 }
1720
1721 /**
1722  * MoveFile:
1723  * @name: a pointer to a NULL-terminated unicode string, that names
1724  * the file to be moved.
1725  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1726  * new name for the file.
1727  *
1728  * Renames file @name to @dest_name.
1729  * MoveFile sets ERROR_ALREADY_EXISTS if the destination exists, except
1730  * when it is the same file as the source.  In that case it silently succeeds.
1731  *
1732  * Return value: %TRUE on success, %FALSE otherwise.
1733  */
1734 gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
1735 {
1736         gchar *utf8_name, *utf8_dest_name;
1737         int result;
1738         struct stat stat_src, stat_dest;
1739         gboolean ret = FALSE;
1740         
1741         if(name==NULL) {
1742 #ifdef DEBUG
1743                 g_message("%s: name is NULL", __func__);
1744 #endif
1745
1746                 SetLastError (ERROR_INVALID_NAME);
1747                 return(FALSE);
1748         }
1749
1750         utf8_name = mono_unicode_to_external (name);
1751         if (utf8_name == NULL) {
1752 #ifdef DEBUG
1753                 g_message ("%s: unicode conversion returned NULL", __func__);
1754 #endif
1755                 
1756                 SetLastError (ERROR_INVALID_NAME);
1757                 return FALSE;
1758         }
1759         
1760         if(dest_name==NULL) {
1761 #ifdef DEBUG
1762                 g_message("%s: name is NULL", __func__);
1763 #endif
1764
1765                 g_free (utf8_name);
1766                 SetLastError (ERROR_INVALID_NAME);
1767                 return(FALSE);
1768         }
1769
1770         utf8_dest_name = mono_unicode_to_external (dest_name);
1771         if (utf8_dest_name == NULL) {
1772 #ifdef DEBUG
1773                 g_message ("%s: unicode conversion returned NULL", __func__);
1774 #endif
1775
1776                 g_free (utf8_name);
1777                 SetLastError (ERROR_INVALID_NAME);
1778                 return FALSE;
1779         }
1780
1781         /*
1782          * In C# land we check for the existence of src, but not for dest.
1783          * We check it here and return the failure if dest exists and is not
1784          * the same file as src.
1785          */
1786         if (!_wapi_stat (utf8_dest_name, &stat_dest) &&
1787             !_wapi_stat (utf8_name, &stat_src)) {
1788                 if (stat_dest.st_dev != stat_src.st_dev ||
1789                     stat_dest.st_ino != stat_src.st_ino) {
1790                         SetLastError (ERROR_ALREADY_EXISTS);
1791                         return FALSE;
1792                 }       
1793         }
1794
1795         result = _wapi_rename (utf8_name, utf8_dest_name);
1796
1797         if (result == -1) {
1798                 switch(errno) {
1799                 case EEXIST:
1800                         SetLastError (ERROR_ALREADY_EXISTS);
1801                         break;
1802                         
1803                 default:
1804                         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
1805                 }
1806         }
1807         
1808         g_free (utf8_name);
1809         g_free (utf8_dest_name);
1810
1811         if (result != 0 && errno == EXDEV) {
1812                 /* Try a copy to the new location, and delete the source */
1813                 if (CopyFile (name, dest_name, TRUE)==FALSE) {
1814                         /* CopyFile will set the error */
1815                         return(FALSE);
1816                 }
1817                 
1818                 return(DeleteFile (name));
1819         }
1820
1821         if (result == 0) {
1822                 ret = TRUE;
1823         }
1824
1825         return(ret);
1826 }
1827
1828 /**
1829  * CopyFile:
1830  * @name: a pointer to a NULL-terminated unicode string, that names
1831  * the file to be copied.
1832  * @dest_name: a pointer to a NULL-terminated unicode string, that is the
1833  * new name for the file.
1834  * @fail_if_exists: if TRUE and dest_name exists, the copy will fail.
1835  *
1836  * Copies file @name to @dest_name
1837  *
1838  * Return value: %TRUE on success, %FALSE otherwise.
1839  */
1840 gboolean CopyFile (const gunichar2 *name, const gunichar2 *dest_name,
1841                    gboolean fail_if_exists)
1842 {
1843         gchar *utf8_src, *utf8_dest;
1844         int src_fd, dest_fd;
1845         int buf_size;
1846         char *buf;
1847         int remain, n;
1848         struct stat st;
1849         
1850         if(name==NULL) {
1851 #ifdef DEBUG
1852                 g_message("%s: name is NULL", __func__);
1853 #endif
1854
1855                 SetLastError (ERROR_INVALID_NAME);
1856                 return(FALSE);
1857         }
1858         
1859         utf8_src = mono_unicode_to_external (name);
1860         if (utf8_src == NULL) {
1861 #ifdef DEBUG
1862                 g_message ("%s: unicode conversion of source returned NULL",
1863                            __func__);
1864 #endif
1865
1866                 SetLastError (ERROR_INVALID_PARAMETER);
1867                 return(FALSE);
1868         }
1869         
1870         if(dest_name==NULL) {
1871 #ifdef DEBUG
1872                 g_message("%s: name is NULL", __func__);
1873 #endif
1874
1875                 g_free (utf8_src);
1876                 SetLastError (ERROR_INVALID_NAME);
1877                 return(FALSE);
1878         }
1879         
1880         utf8_dest = mono_unicode_to_external (dest_name);
1881         if (utf8_dest == NULL) {
1882 #ifdef DEBUG
1883                 g_message ("%s: unicode conversion of dest returned NULL",
1884                            __func__);
1885 #endif
1886
1887                 SetLastError (ERROR_INVALID_PARAMETER);
1888
1889                 g_free (utf8_src);
1890                 
1891                 return(FALSE);
1892         }
1893         
1894         src_fd = _wapi_open (utf8_src, O_RDONLY, 0);
1895         if (src_fd < 0) {
1896                 _wapi_set_last_path_error_from_errno (NULL, utf8_src);
1897                 
1898                 g_free (utf8_src);
1899                 g_free (utf8_dest);
1900                 
1901                 return(FALSE);
1902         }
1903
1904         if (fstat (src_fd, &st) < 0) {
1905                 _wapi_set_last_error_from_errno ();
1906
1907                 g_free (utf8_src);
1908                 g_free (utf8_dest);
1909                 close (src_fd);
1910                 
1911                 return(FALSE);
1912         }
1913         
1914         if (fail_if_exists) {
1915                 dest_fd = open (utf8_dest, O_WRONLY | O_CREAT | O_EXCL,
1916                                 st.st_mode);
1917         } else {
1918                 dest_fd = open (utf8_dest, O_WRONLY | O_TRUNC, st.st_mode);
1919                 if (dest_fd < 0) {
1920                         /* O_TRUNC might cause a fail if the file
1921                          * doesn't exist
1922                          */
1923                         dest_fd = open (utf8_dest, O_WRONLY | O_CREAT,
1924                                         st.st_mode);
1925                 } else {
1926                         /* Apparently this error is set if we
1927                          * overwrite the dest file
1928                          */
1929                         SetLastError (ERROR_ALREADY_EXISTS);
1930                 }
1931         }
1932         if (dest_fd < 0) {
1933                 _wapi_set_last_error_from_errno ();
1934
1935                 g_free (utf8_src);
1936                 g_free (utf8_dest);
1937                 close (src_fd);
1938                 
1939                 return(FALSE);
1940         }
1941         
1942         buf_size = st.st_blksize;
1943         buf = (char *) alloca (buf_size);
1944         
1945         for (;;) {
1946                 remain = read (src_fd, buf, buf_size);
1947                 
1948                 if (remain < 0) {
1949                         if (errno == EINTR && !_wapi_thread_cur_apc_pending()) {
1950                                 continue;
1951                         }
1952                         
1953                         _wapi_set_last_error_from_errno ();
1954
1955                         g_free (utf8_src);
1956                         g_free (utf8_dest);
1957                         close (src_fd);
1958                         close (dest_fd);
1959                         
1960                         return(FALSE);
1961                 }
1962                 
1963                 if (remain == 0) {
1964                         break;
1965                 }
1966
1967                 while (remain > 0) {
1968                         if ((n = write (dest_fd, buf, remain)) < 0) {
1969                                 if (errno == EINTR && !_wapi_thread_cur_apc_pending())
1970                                         continue;
1971
1972                                 _wapi_set_last_error_from_errno ();
1973 #ifdef DEBUG
1974                                 g_message ("%s: write failed.", __func__);
1975 #endif
1976
1977                                 g_free (utf8_src);
1978                                 g_free (utf8_dest);
1979                                 close (src_fd);
1980                                 close (dest_fd);
1981
1982                                 return (FALSE);
1983                         }
1984
1985                         remain -= n;
1986                 }
1987         }
1988
1989         g_free (utf8_src);
1990         g_free (utf8_dest);
1991         close (src_fd);
1992         close (dest_fd);
1993
1994         return(TRUE);
1995 }
1996
1997 static gpointer stdhandle_create (int fd, const gchar *name)
1998 {
1999         struct _WapiHandle_file file_handle = {0};
2000         gpointer handle;
2001         int flags;
2002         
2003 #ifdef DEBUG
2004         g_message("%s: creating standard handle type %s, fd %d", __func__,
2005                   name, fd);
2006 #endif
2007         
2008         /* Check if fd is valid */
2009         do {
2010                 flags=fcntl(fd, F_GETFL);
2011         } while (flags == -1 && errno == EINTR);
2012
2013         if(flags==-1) {
2014                 /* Invalid fd.  Not really much point checking for EBADF
2015                  * specifically
2016                  */
2017 #ifdef DEBUG
2018                 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
2019                           strerror(errno));
2020 #endif
2021
2022                 _wapi_set_last_error_from_errno ();
2023                 return(INVALID_HANDLE_VALUE);
2024         }
2025
2026         file_handle.filename = g_strdup(name);
2027         /* some default security attributes might be needed */
2028         file_handle.security_attributes=0;
2029         file_handle.fileaccess=convert_from_flags(flags);
2030
2031         /* Apparently input handles can't be written to.  (I don't
2032          * know if output or error handles can't be read from.)
2033          */
2034         if (fd == 0) {
2035                 file_handle.fileaccess &= ~GENERIC_WRITE;
2036         }
2037         
2038         file_handle.sharemode=0;
2039         file_handle.attrs=0;
2040
2041         handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
2042         if (handle == _WAPI_HANDLE_INVALID) {
2043                 g_warning ("%s: error creating file handle", __func__);
2044                 SetLastError (ERROR_GEN_FAILURE);
2045                 return(INVALID_HANDLE_VALUE);
2046         }
2047         
2048 #ifdef DEBUG
2049         g_message("%s: returning handle %p", __func__, handle);
2050 #endif
2051
2052         return(handle);
2053 }
2054
2055 /**
2056  * GetStdHandle:
2057  * @stdhandle: specifies the file descriptor
2058  *
2059  * Returns a handle for stdin, stdout, or stderr.  Always returns the
2060  * same handle for the same @stdhandle.
2061  *
2062  * Return value: the handle, or %INVALID_HANDLE_VALUE on error
2063  */
2064
2065 static mono_mutex_t stdhandle_mutex = MONO_MUTEX_INITIALIZER;
2066
2067 gpointer GetStdHandle(WapiStdHandle stdhandle)
2068 {
2069         struct _WapiHandle_file *file_handle;
2070         gpointer handle;
2071         int thr_ret, fd;
2072         const gchar *name;
2073         gboolean ok;
2074         
2075         switch(stdhandle) {
2076         case STD_INPUT_HANDLE:
2077                 fd = 0;
2078                 name = "<stdin>";
2079                 break;
2080
2081         case STD_OUTPUT_HANDLE:
2082                 fd = 1;
2083                 name = "<stdout>";
2084                 break;
2085
2086         case STD_ERROR_HANDLE:
2087                 fd = 2;
2088                 name = "<stderr>";
2089                 break;
2090
2091         default:
2092 #ifdef DEBUG
2093                 g_message("%s: unknown standard handle type", __func__);
2094 #endif
2095
2096                 SetLastError (ERROR_INVALID_PARAMETER);
2097                 return(INVALID_HANDLE_VALUE);
2098         }
2099
2100         handle = GINT_TO_POINTER (fd);
2101
2102         pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
2103                               (void *)&stdhandle_mutex);
2104         thr_ret = mono_mutex_lock (&stdhandle_mutex);
2105         g_assert (thr_ret == 0);
2106
2107         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_CONSOLE,
2108                                   (gpointer *)&file_handle);
2109         if (ok == FALSE) {
2110                 /* Need to create this console handle */
2111                 handle = stdhandle_create (fd, name);
2112                 
2113                 if (handle == INVALID_HANDLE_VALUE) {
2114                         SetLastError (ERROR_NO_MORE_FILES);
2115                         goto done;
2116                 }
2117         } else {
2118                 /* Add a reference to this handle */
2119                 _wapi_handle_ref (handle);
2120         }
2121         
2122   done:
2123         thr_ret = mono_mutex_unlock (&stdhandle_mutex);
2124         g_assert (thr_ret == 0);
2125         pthread_cleanup_pop (0);
2126         
2127         return(handle);
2128 }
2129
2130 /**
2131  * ReadFile:
2132  * @handle: The file handle to read from.  The handle must have
2133  * %GENERIC_READ access.
2134  * @buffer: The buffer to store read data in
2135  * @numbytes: The maximum number of bytes to read
2136  * @bytesread: The actual number of bytes read is stored here.  This
2137  * value can be zero if the handle is positioned at the end of the
2138  * file.
2139  * @overlapped: points to a required %WapiOverlapped structure if
2140  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2141  * otherwise.
2142  *
2143  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2144  * function reads up to @numbytes bytes from the file from the current
2145  * file position, and stores them in @buffer.  If there are not enough
2146  * bytes left in the file, just the amount available will be read.
2147  * The actual number of bytes read is stored in @bytesread.
2148
2149  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2150  * file position is ignored and the read position is taken from data
2151  * in the @overlapped structure.
2152  *
2153  * Return value: %TRUE if the read succeeds (even if no bytes were
2154  * read due to an attempt to read past the end of the file), %FALSE on
2155  * error.
2156  */
2157 gboolean ReadFile(gpointer handle, gpointer buffer, guint32 numbytes,
2158                   guint32 *bytesread, WapiOverlapped *overlapped)
2159 {
2160         WapiHandleType type;
2161
2162         type = _wapi_handle_type (handle);
2163         
2164         if(io_ops[type].readfile==NULL) {
2165                 SetLastError (ERROR_INVALID_HANDLE);
2166                 return(FALSE);
2167         }
2168         
2169         return(io_ops[type].readfile (handle, buffer, numbytes, bytesread,
2170                                       overlapped));
2171 }
2172
2173 /**
2174  * WriteFile:
2175  * @handle: The file handle to write to.  The handle must have
2176  * %GENERIC_WRITE access.
2177  * @buffer: The buffer to read data from.
2178  * @numbytes: The maximum number of bytes to write.
2179  * @byteswritten: The actual number of bytes written is stored here.
2180  * If the handle is positioned at the file end, the length of the file
2181  * is extended.  This parameter may be %NULL.
2182  * @overlapped: points to a required %WapiOverlapped structure if
2183  * @handle has the %FILE_FLAG_OVERLAPPED option set, should be NULL
2184  * otherwise.
2185  *
2186  * If @handle does not have the %FILE_FLAG_OVERLAPPED option set, this
2187  * function writes up to @numbytes bytes from @buffer to the file at
2188  * the current file position.  If @handle is positioned at the end of
2189  * the file, the file is extended.  The actual number of bytes written
2190  * is stored in @byteswritten.
2191  *
2192  * If @handle has the %FILE_FLAG_OVERLAPPED option set, the current
2193  * file position is ignored and the write position is taken from data
2194  * in the @overlapped structure.
2195  *
2196  * Return value: %TRUE if the write succeeds, %FALSE on error.
2197  */
2198 gboolean WriteFile(gpointer handle, gconstpointer buffer, guint32 numbytes,
2199                    guint32 *byteswritten, WapiOverlapped *overlapped)
2200 {
2201         WapiHandleType type;
2202
2203         type = _wapi_handle_type (handle);
2204         
2205         if(io_ops[type].writefile==NULL) {
2206                 SetLastError (ERROR_INVALID_HANDLE);
2207                 return(FALSE);
2208         }
2209         
2210         return(io_ops[type].writefile (handle, buffer, numbytes, byteswritten,
2211                                        overlapped));
2212 }
2213
2214 /**
2215  * FlushFileBuffers:
2216  * @handle: Handle to open file.  The handle must have
2217  * %GENERIC_WRITE access.
2218  *
2219  * Flushes buffers of the file and causes all unwritten data to
2220  * be written.
2221  *
2222  * Return value: %TRUE on success, %FALSE otherwise.
2223  */
2224 gboolean FlushFileBuffers(gpointer handle)
2225 {
2226         WapiHandleType type;
2227
2228         type = _wapi_handle_type (handle);
2229         
2230         if(io_ops[type].flushfile==NULL) {
2231                 SetLastError (ERROR_INVALID_HANDLE);
2232                 return(FALSE);
2233         }
2234         
2235         return(io_ops[type].flushfile (handle));
2236 }
2237
2238 /**
2239  * SetEndOfFile:
2240  * @handle: The file handle to set.  The handle must have
2241  * %GENERIC_WRITE access.
2242  *
2243  * Moves the end-of-file position to the current position of the file
2244  * pointer.  This function is used to truncate or extend a file.
2245  *
2246  * Return value: %TRUE on success, %FALSE otherwise.
2247  */
2248 gboolean SetEndOfFile(gpointer handle)
2249 {
2250         WapiHandleType type;
2251
2252         type = _wapi_handle_type (handle);
2253         
2254         if (io_ops[type].setendoffile == NULL) {
2255                 SetLastError (ERROR_INVALID_HANDLE);
2256                 return(FALSE);
2257         }
2258         
2259         return(io_ops[type].setendoffile (handle));
2260 }
2261
2262 /**
2263  * SetFilePointer:
2264  * @handle: The file handle to set.  The handle must have
2265  * %GENERIC_READ or %GENERIC_WRITE access.
2266  * @movedistance: Low 32 bits of a signed value that specifies the
2267  * number of bytes to move the file pointer.
2268  * @highmovedistance: Pointer to the high 32 bits of a signed value
2269  * that specifies the number of bytes to move the file pointer, or
2270  * %NULL.
2271  * @method: The starting point for the file pointer move.
2272  *
2273  * Sets the file pointer of an open file.
2274  *
2275  * The distance to move the file pointer is calculated from
2276  * @movedistance and @highmovedistance: If @highmovedistance is %NULL,
2277  * @movedistance is the 32-bit signed value; otherwise, @movedistance
2278  * is the low 32 bits and @highmovedistance a pointer to the high 32
2279  * bits of a 64 bit signed value.  A positive distance moves the file
2280  * pointer forward from the position specified by @method; a negative
2281  * distance moves the file pointer backward.
2282  *
2283  * If the library is compiled without large file support,
2284  * @highmovedistance is ignored and its value is set to zero on a
2285  * successful return.
2286  *
2287  * Return value: On success, the low 32 bits of the new file pointer.
2288  * If @highmovedistance is not %NULL, the high 32 bits of the new file
2289  * pointer are stored there.  On failure, %INVALID_SET_FILE_POINTER.
2290  */
2291 guint32 SetFilePointer(gpointer handle, gint32 movedistance,
2292                        gint32 *highmovedistance, WapiSeekMethod method)
2293 {
2294         WapiHandleType type;
2295
2296         type = _wapi_handle_type (handle);
2297         
2298         if (io_ops[type].seek == NULL) {
2299                 SetLastError (ERROR_INVALID_HANDLE);
2300                 return(INVALID_SET_FILE_POINTER);
2301         }
2302         
2303         return(io_ops[type].seek (handle, movedistance, highmovedistance,
2304                                   method));
2305 }
2306
2307 /**
2308  * GetFileType:
2309  * @handle: The file handle to test.
2310  *
2311  * Finds the type of file @handle.
2312  *
2313  * Return value: %FILE_TYPE_UNKNOWN - the type of the file @handle is
2314  * unknown.  %FILE_TYPE_DISK - @handle is a disk file.
2315  * %FILE_TYPE_CHAR - @handle is a character device, such as a console.
2316  * %FILE_TYPE_PIPE - @handle is a named or anonymous pipe.
2317  */
2318 WapiFileType GetFileType(gpointer handle)
2319 {
2320         WapiHandleType type;
2321
2322         if (!_WAPI_PRIVATE_HAVE_SLOT (handle)) {
2323                 SetLastError (ERROR_INVALID_HANDLE);
2324                 return(FILE_TYPE_UNKNOWN);
2325         }
2326
2327         type = _wapi_handle_type (handle);
2328         
2329         if (io_ops[type].getfiletype == NULL) {
2330                 SetLastError (ERROR_INVALID_HANDLE);
2331                 return(FILE_TYPE_UNKNOWN);
2332         }
2333         
2334         return(io_ops[type].getfiletype ());
2335 }
2336
2337 /**
2338  * GetFileSize:
2339  * @handle: The file handle to query.  The handle must have
2340  * %GENERIC_READ or %GENERIC_WRITE access.
2341  * @highsize: If non-%NULL, the high 32 bits of the file size are
2342  * stored here.
2343  *
2344  * Retrieves the size of the file @handle.
2345  *
2346  * If the library is compiled without large file support, @highsize
2347  * has its value set to zero on a successful return.
2348  *
2349  * Return value: On success, the low 32 bits of the file size.  If
2350  * @highsize is non-%NULL then the high 32 bits of the file size are
2351  * stored here.  On failure %INVALID_FILE_SIZE is returned.
2352  */
2353 guint32 GetFileSize(gpointer handle, guint32 *highsize)
2354 {
2355         WapiHandleType type;
2356
2357         type = _wapi_handle_type (handle);
2358         
2359         if (io_ops[type].getfilesize == NULL) {
2360                 SetLastError (ERROR_INVALID_HANDLE);
2361                 return(INVALID_FILE_SIZE);
2362         }
2363         
2364         return(io_ops[type].getfilesize (handle, highsize));
2365 }
2366
2367 /**
2368  * GetFileTime:
2369  * @handle: The file handle to query.  The handle must have
2370  * %GENERIC_READ access.
2371  * @create_time: Points to a %WapiFileTime structure to receive the
2372  * number of ticks since the epoch that file was created.  May be
2373  * %NULL.
2374  * @last_access: Points to a %WapiFileTime structure to receive the
2375  * number of ticks since the epoch when file was last accessed.  May be
2376  * %NULL.
2377  * @last_write: Points to a %WapiFileTime structure to receive the
2378  * number of ticks since the epoch when file was last written to.  May
2379  * be %NULL.
2380  *
2381  * Finds the number of ticks since the epoch that the file referenced
2382  * by @handle was created, last accessed and last modified.  A tick is
2383  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2384  * GMT.
2385  *
2386  * Create time isn't recorded on POSIX file systems or reported by
2387  * stat(2), so that time is guessed by returning the oldest of the
2388  * other times.
2389  *
2390  * Return value: %TRUE on success, %FALSE otherwise.
2391  */
2392 gboolean GetFileTime(gpointer handle, WapiFileTime *create_time,
2393                      WapiFileTime *last_access, WapiFileTime *last_write)
2394 {
2395         WapiHandleType type;
2396
2397         type = _wapi_handle_type (handle);
2398         
2399         if (io_ops[type].getfiletime == NULL) {
2400                 SetLastError (ERROR_INVALID_HANDLE);
2401                 return(FALSE);
2402         }
2403         
2404         return(io_ops[type].getfiletime (handle, create_time, last_access,
2405                                          last_write));
2406 }
2407
2408 /**
2409  * SetFileTime:
2410  * @handle: The file handle to set.  The handle must have
2411  * %GENERIC_WRITE access.
2412  * @create_time: Points to a %WapiFileTime structure that contains the
2413  * number of ticks since the epoch that the file was created.  May be
2414  * %NULL.
2415  * @last_access: Points to a %WapiFileTime structure that contains the
2416  * number of ticks since the epoch when the file was last accessed.
2417  * May be %NULL.
2418  * @last_write: Points to a %WapiFileTime structure that contains the
2419  * number of ticks since the epoch when the file was last written to.
2420  * May be %NULL.
2421  *
2422  * Sets the number of ticks since the epoch that the file referenced
2423  * by @handle was created, last accessed or last modified.  A tick is
2424  * a 100 nanosecond interval.  The epoch is Midnight, January 1 1601
2425  * GMT.
2426  *
2427  * Create time isn't recorded on POSIX file systems, and is ignored.
2428  *
2429  * Return value: %TRUE on success, %FALSE otherwise.
2430  */
2431 gboolean SetFileTime(gpointer handle, const WapiFileTime *create_time,
2432                      const WapiFileTime *last_access,
2433                      const WapiFileTime *last_write)
2434 {
2435         WapiHandleType type;
2436
2437         type = _wapi_handle_type (handle);
2438         
2439         if (io_ops[type].setfiletime == NULL) {
2440                 SetLastError (ERROR_INVALID_HANDLE);
2441                 return(FALSE);
2442         }
2443         
2444         return(io_ops[type].setfiletime (handle, create_time, last_access,
2445                                          last_write));
2446 }
2447
2448 /* A tick is a 100-nanosecond interval.  File time epoch is Midnight,
2449  * January 1 1601 GMT
2450  */
2451
2452 #define TICKS_PER_MILLISECOND 10000L
2453 #define TICKS_PER_SECOND 10000000L
2454 #define TICKS_PER_MINUTE 600000000L
2455 #define TICKS_PER_HOUR 36000000000LL
2456 #define TICKS_PER_DAY 864000000000LL
2457
2458 #define isleap(y) ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))
2459
2460 static const guint16 mon_yday[2][13]={
2461         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
2462         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
2463 };
2464
2465 /**
2466  * FileTimeToSystemTime:
2467  * @file_time: Points to a %WapiFileTime structure that contains the
2468  * number of ticks to convert.
2469  * @system_time: Points to a %WapiSystemTime structure to receive the
2470  * broken-out time.
2471  *
2472  * Converts a tick count into broken-out time values.
2473  *
2474  * Return value: %TRUE on success, %FALSE otherwise.
2475  */
2476 gboolean FileTimeToSystemTime(const WapiFileTime *file_time,
2477                               WapiSystemTime *system_time)
2478 {
2479         gint64 file_ticks, totaldays, rem, y;
2480         const guint16 *ip;
2481         
2482         if(system_time==NULL) {
2483 #ifdef DEBUG
2484                 g_message("%s: system_time NULL", __func__);
2485 #endif
2486
2487                 SetLastError (ERROR_INVALID_PARAMETER);
2488                 return(FALSE);
2489         }
2490         
2491         file_ticks=((gint64)file_time->dwHighDateTime << 32) +
2492                 file_time->dwLowDateTime;
2493         
2494         /* Really compares if file_ticks>=0x8000000000000000
2495          * (LLONG_MAX+1) but we're working with a signed value for the
2496          * year and day calculation to work later
2497          */
2498         if(file_ticks<0) {
2499 #ifdef DEBUG
2500                 g_message("%s: file_time too big", __func__);
2501 #endif
2502
2503                 SetLastError (ERROR_INVALID_PARAMETER);
2504                 return(FALSE);
2505         }
2506
2507         totaldays=(file_ticks / TICKS_PER_DAY);
2508         rem = file_ticks % TICKS_PER_DAY;
2509 #ifdef DEBUG
2510         g_message("%s: totaldays: %lld rem: %lld", __func__, totaldays, rem);
2511 #endif
2512
2513         system_time->wHour=rem/TICKS_PER_HOUR;
2514         rem %= TICKS_PER_HOUR;
2515 #ifdef DEBUG
2516         g_message("%s: Hour: %d rem: %lld", __func__, system_time->wHour, rem);
2517 #endif
2518         
2519         system_time->wMinute = rem / TICKS_PER_MINUTE;
2520         rem %= TICKS_PER_MINUTE;
2521 #ifdef DEBUG
2522         g_message("%s: Minute: %d rem: %lld", __func__, system_time->wMinute,
2523                   rem);
2524 #endif
2525         
2526         system_time->wSecond = rem / TICKS_PER_SECOND;
2527         rem %= TICKS_PER_SECOND;
2528 #ifdef DEBUG
2529         g_message("%s: Second: %d rem: %lld", __func__, system_time->wSecond,
2530                   rem);
2531 #endif
2532         
2533         system_time->wMilliseconds = rem / TICKS_PER_MILLISECOND;
2534 #ifdef DEBUG
2535         g_message("%s: Milliseconds: %d", __func__,
2536                   system_time->wMilliseconds);
2537 #endif
2538
2539         /* January 1, 1601 was a Monday, according to Emacs calendar */
2540         system_time->wDayOfWeek = ((1 + totaldays) % 7) + 1;
2541 #ifdef DEBUG
2542         g_message("%s: Day of week: %d", __func__, system_time->wDayOfWeek);
2543 #endif
2544         
2545         /* This algorithm to find year and month given days from epoch
2546          * from glibc
2547          */
2548         y=1601;
2549         
2550 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
2551 #define LEAPS_THRU_END_OF(y) (DIV(y, 4) - DIV (y, 100) + DIV (y, 400))
2552
2553         while(totaldays < 0 || totaldays >= (isleap(y)?366:365)) {
2554                 /* Guess a corrected year, assuming 365 days per year */
2555                 gint64 yg = y + totaldays / 365 - (totaldays % 365 < 0);
2556 #ifdef DEBUG
2557                 g_message("%s: totaldays: %lld yg: %lld y: %lld", __func__,
2558                           totaldays, yg,
2559                           y);
2560                 g_message("%s: LEAPS(yg): %lld LEAPS(y): %lld", __func__,
2561                           LEAPS_THRU_END_OF(yg-1), LEAPS_THRU_END_OF(y-1));
2562 #endif
2563                 
2564                 /* Adjust days and y to match the guessed year. */
2565                 totaldays -= ((yg - y) * 365
2566                               + LEAPS_THRU_END_OF (yg - 1)
2567                               - LEAPS_THRU_END_OF (y - 1));
2568 #ifdef DEBUG
2569                 g_message("%s: totaldays: %lld", __func__, totaldays);
2570 #endif
2571                 y = yg;
2572 #ifdef DEBUG
2573                 g_message("%s: y: %lld", __func__, y);
2574 #endif
2575         }
2576         
2577         system_time->wYear = y;
2578 #ifdef DEBUG
2579         g_message("%s: Year: %d", __func__, system_time->wYear);
2580 #endif
2581
2582         ip = mon_yday[isleap(y)];
2583         
2584         for(y=11; totaldays < ip[y]; --y) {
2585                 continue;
2586         }
2587         totaldays-=ip[y];
2588 #ifdef DEBUG
2589         g_message("%s: totaldays: %lld", __func__, totaldays);
2590 #endif
2591         
2592         system_time->wMonth = y + 1;
2593 #ifdef DEBUG
2594         g_message("%s: Month: %d", __func__, system_time->wMonth);
2595 #endif
2596
2597         system_time->wDay = totaldays + 1;
2598 #ifdef DEBUG
2599         g_message("%s: Day: %d", __func__, system_time->wDay);
2600 #endif
2601         
2602         return(TRUE);
2603 }
2604
2605 static gint
2606 file_compare (gconstpointer a, gconstpointer b)
2607 {
2608         gchar *astr = *(gchar **) a;
2609         gchar *bstr = *(gchar **) b;
2610
2611         return strcmp (astr, bstr);
2612 }
2613
2614 static gint
2615 get_errno_from_g_file_error (gint error)
2616 {
2617         switch (error) {
2618 #ifdef EACCESS
2619         case G_FILE_ERROR_ACCES:
2620                 error = EACCES;
2621                 break;
2622 #endif
2623 #ifdef ENAMETOOLONG
2624         case G_FILE_ERROR_NAMETOOLONG:
2625                 error = ENAMETOOLONG;
2626                 break;
2627 #endif
2628 #ifdef ENOENT
2629         case G_FILE_ERROR_NOENT:
2630                 error = ENOENT;
2631                 break;
2632 #endif
2633 #ifdef ENOTDIR
2634         case G_FILE_ERROR_NOTDIR:
2635                 error = ENOTDIR;
2636                 break;
2637 #endif
2638 #ifdef ENXIO
2639         case G_FILE_ERROR_NXIO:
2640                 error = ENXIO;
2641                 break;
2642 #endif
2643 #ifdef ENODEV
2644         case G_FILE_ERROR_NODEV:
2645                 error = ENODEV;
2646                 break;
2647 #endif
2648 #ifdef EROFS
2649         case G_FILE_ERROR_ROFS:
2650                 error = EROFS;
2651                 break;
2652 #endif
2653 #ifdef ETXTBSY
2654         case G_FILE_ERROR_TXTBSY:
2655                 error = ETXTBSY;
2656                 break;
2657 #endif
2658 #ifdef EFAULT
2659         case G_FILE_ERROR_FAULT:
2660                 error = EFAULT;
2661                 break;
2662 #endif
2663 #ifdef ELOOP
2664         case G_FILE_ERROR_LOOP:
2665                 error = ELOOP;
2666                 break;
2667 #endif
2668 #ifdef ENOSPC
2669         case G_FILE_ERROR_NOSPC:
2670                 error = ENOSPC;
2671                 break;
2672 #endif
2673 #ifdef ENOMEM
2674         case G_FILE_ERROR_NOMEM:
2675                 error = ENOMEM;
2676                 break;
2677 #endif
2678 #ifdef EMFILE
2679         case G_FILE_ERROR_MFILE:
2680                 error = EMFILE;
2681                 break;
2682 #endif
2683 #ifdef ENFILE
2684         case G_FILE_ERROR_NFILE:
2685                 error = ENFILE;
2686                 break;
2687 #endif
2688 #ifdef EBADF
2689         case G_FILE_ERROR_BADF:
2690                 error = EBADF;
2691                 break;
2692 #endif
2693 #ifdef EINVAL
2694         case G_FILE_ERROR_INVAL:
2695                 error = EINVAL;
2696                 break;
2697 #endif
2698 #ifdef EPIPE
2699         case G_FILE_ERROR_PIPE:
2700                 error = EPIPE;
2701                 break;
2702 #endif
2703 #ifdef EAGAIN
2704         case G_FILE_ERROR_AGAIN:
2705                 error = EAGAIN;
2706                 break;
2707 #endif
2708 #ifdef EINTR
2709         case G_FILE_ERROR_INTR:
2710                 error = EINTR;
2711                 break;
2712 #endif
2713 #ifdef EWIO
2714         case G_FILE_ERROR_IO:
2715                 error = EIO;
2716                 break;
2717 #endif
2718 #ifdef EPERM
2719         case G_FILE_ERROR_PERM:
2720                 error = EPERM;
2721                 break;
2722 #endif
2723         case G_FILE_ERROR_FAILED:
2724                 error = ERROR_INVALID_PARAMETER;
2725                 break;
2726         }
2727
2728         return error;
2729 }
2730
2731 /* scandir using glib */
2732 static gint
2733 mono_io_scandir (const gchar *dirname, const gchar *pattern, gchar ***namelist)
2734 {
2735         GError *error = NULL;
2736         GDir *dir;
2737         GPtrArray *names;
2738         const gchar *name;
2739         gint result;
2740         GPatternSpec *patspec;
2741
2742         dir = _wapi_g_dir_open (dirname, 0, &error);
2743         if (dir == NULL) {
2744                 /* g_dir_open returns ENOENT on directories on which we don't
2745                  * have read/x permission */
2746                 gint errnum = get_errno_from_g_file_error (error->code);
2747                 g_error_free (error);
2748                 if (errnum == ENOENT &&
2749                     !_wapi_access (dirname, F_OK) &&
2750                     _wapi_access (dirname, R_OK|X_OK)) {
2751                         errnum = EACCES;
2752                 }
2753
2754                 errno = errnum;
2755                 return -1;
2756         }
2757
2758         patspec = g_pattern_spec_new (pattern);
2759         names = g_ptr_array_new ();
2760         while ((name = g_dir_read_name (dir)) != NULL) {
2761                 if (g_pattern_match_string (patspec, name))
2762                         g_ptr_array_add (names, g_strdup (name));
2763         }
2764         
2765         g_pattern_spec_free (patspec);
2766         g_dir_close (dir);
2767         result = names->len;
2768         if (result > 0) {
2769                 g_ptr_array_sort (names, file_compare);
2770                 g_ptr_array_set_size (names, result + 1);
2771
2772                 *namelist = (gchar **) g_ptr_array_free (names, FALSE);
2773         } else {
2774                 g_ptr_array_free (names, TRUE);
2775         }
2776
2777         return result;
2778 }
2779
2780 gpointer FindFirstFile (const gunichar2 *pattern, WapiFindData *find_data)
2781 {
2782         struct _WapiHandle_find find_handle = {0};
2783         gpointer handle;
2784         gchar *utf8_pattern = NULL, *dir_part, *entry_part;
2785         int result;
2786         
2787         if (pattern == NULL) {
2788 #ifdef DEBUG
2789                 g_message ("%s: pattern is NULL", __func__);
2790 #endif
2791
2792                 SetLastError (ERROR_PATH_NOT_FOUND);
2793                 return(INVALID_HANDLE_VALUE);
2794         }
2795
2796         utf8_pattern = mono_unicode_to_external (pattern);
2797         if (utf8_pattern == NULL) {
2798 #ifdef DEBUG
2799                 g_message ("%s: unicode conversion returned NULL", __func__);
2800 #endif
2801                 
2802                 SetLastError (ERROR_INVALID_NAME);
2803                 return(INVALID_HANDLE_VALUE);
2804         }
2805
2806 #ifdef DEBUG
2807         g_message ("%s: looking for [%s]", __func__, utf8_pattern);
2808 #endif
2809         
2810         /* Figure out which bit of the pattern is the directory */
2811         dir_part = _wapi_dirname (utf8_pattern);
2812         entry_part = _wapi_basename (utf8_pattern);
2813
2814 #if 0
2815         /* Don't do this check for now, it breaks if directories
2816          * really do have metachars in their names (see bug 58116).
2817          * FIXME: Figure out a better solution to keep some checks...
2818          */
2819         if (strchr (dir_part, '*') || strchr (dir_part, '?')) {
2820                 SetLastError (ERROR_INVALID_NAME);
2821                 g_free (dir_part);
2822                 g_free (entry_part);
2823                 g_free (utf8_pattern);
2824                 return(INVALID_HANDLE_VALUE);
2825         }
2826 #endif
2827
2828         /* The pattern can specify a directory or a set of files.
2829          *
2830          * The pattern can have wildcard characters ? and *, but only
2831          * in the section after the last directory delimiter.  (Return
2832          * ERROR_INVALID_NAME if there are wildcards in earlier path
2833          * sections.)  "*" has the usual 0-or-more chars meaning.  "?" 
2834          * means "match one character", "??" seems to mean "match one
2835          * or two characters", "???" seems to mean "match one, two or
2836          * three characters", etc.  Windows will also try and match
2837          * the mangled "short name" of files, so 8 character patterns
2838          * with wildcards will show some surprising results.
2839          *
2840          * All the written documentation I can find says that '?' 
2841          * should only match one character, and doesn't mention '??',
2842          * '???' etc.  I'm going to assume that the strict behaviour
2843          * (ie '???' means three and only three characters) is the
2844          * correct one, because that lets me use fnmatch(3) rather
2845          * than mess around with regexes.
2846          */
2847
2848         find_handle.namelist = NULL;
2849         result = mono_io_scandir (dir_part, entry_part, &find_handle.namelist);
2850         
2851         if (result == 0) {
2852                 /* No files, which windows seems to call
2853                  * FILE_NOT_FOUND
2854                  */
2855                 SetLastError (ERROR_FILE_NOT_FOUND);
2856                 g_free (utf8_pattern);
2857                 g_free (entry_part);
2858                 g_free (dir_part);
2859                 return (INVALID_HANDLE_VALUE);
2860         }
2861         
2862         if (result < 0) {
2863 #ifdef DEBUG
2864                 gint errnum = errno;
2865 #endif
2866                 _wapi_set_last_path_error_from_errno (dir_part, NULL);
2867 #ifdef DEBUG
2868                 g_message ("%s: scandir error: %s", __func__,
2869                            g_strerror (errnum));
2870 #endif
2871                 g_free (utf8_pattern);
2872                 g_free (entry_part);
2873                 g_free (dir_part);
2874                 return (INVALID_HANDLE_VALUE);
2875         }
2876
2877         g_free (utf8_pattern);
2878         g_free (entry_part);
2879         
2880 #ifdef DEBUG
2881         g_message ("%s: Got %d matches", __func__, result);
2882 #endif
2883
2884         find_handle.dir_part = dir_part;
2885         find_handle.num = result;
2886         find_handle.count = 0;
2887         
2888         handle = _wapi_handle_new (WAPI_HANDLE_FIND, &find_handle);
2889         if (handle == _WAPI_HANDLE_INVALID) {
2890                 g_warning ("%s: error creating find handle", __func__);
2891                 g_free (dir_part);
2892                 g_free (entry_part);
2893                 g_free (utf8_pattern);
2894                 SetLastError (ERROR_GEN_FAILURE);
2895                 
2896                 return(INVALID_HANDLE_VALUE);
2897         }
2898
2899         if (handle != INVALID_HANDLE_VALUE &&
2900             !FindNextFile (handle, find_data)) {
2901                 FindClose (handle);
2902                 SetLastError (ERROR_NO_MORE_FILES);
2903                 handle = INVALID_HANDLE_VALUE;
2904         }
2905
2906         return (handle);
2907 }
2908
2909 gboolean FindNextFile (gpointer handle, WapiFindData *find_data)
2910 {
2911         struct _WapiHandle_find *find_handle;
2912         gboolean ok;
2913         struct stat buf;
2914         gchar *filename;
2915         gchar *utf8_filename, *utf8_basename;
2916         gunichar2 *utf16_basename;
2917         time_t create_time;
2918         glong bytes;
2919         int thr_ret;
2920         gboolean ret = FALSE;
2921         
2922         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
2923                                 (gpointer *)&find_handle);
2924         if(ok==FALSE) {
2925                 g_warning ("%s: error looking up find handle %p", __func__,
2926                            handle);
2927                 SetLastError (ERROR_INVALID_HANDLE);
2928                 return(FALSE);
2929         }
2930
2931         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
2932                               handle);
2933         thr_ret = _wapi_handle_lock_handle (handle);
2934         g_assert (thr_ret == 0);
2935         
2936 retry:
2937         if (find_handle->count >= find_handle->num) {
2938                 SetLastError (ERROR_NO_MORE_FILES);
2939                 goto cleanup;
2940         }
2941
2942         /* stat next match */
2943
2944         filename = g_build_filename (find_handle->dir_part, find_handle->namelist[find_handle->count ++], NULL);
2945         if (_wapi_lstat (filename, &buf) != 0) {
2946 #ifdef DEBUG
2947                 g_message ("%s: stat failed: %s", __func__, filename);
2948 #endif
2949
2950                 g_free (filename);
2951                 goto retry;
2952         }
2953
2954         utf8_filename = mono_utf8_from_external (filename);
2955         if (utf8_filename == NULL) {
2956                 /* We couldn't turn this filename into utf8 (eg the
2957                  * encoding of the name wasn't convertible), so just
2958                  * ignore it.
2959                  */
2960                 g_free (filename);
2961                 goto retry;
2962         }
2963         g_free (filename);
2964         
2965 #ifdef DEBUG
2966         g_message ("%s: Found [%s]", __func__, utf8_filename);
2967 #endif
2968         
2969         /* fill data block */
2970
2971         if (buf.st_mtime < buf.st_ctime)
2972                 create_time = buf.st_mtime;
2973         else
2974                 create_time = buf.st_ctime;
2975         
2976         find_data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_filename, &buf, &buf);
2977
2978         _wapi_time_t_to_filetime (create_time, &find_data->ftCreationTime);
2979         _wapi_time_t_to_filetime (buf.st_atime, &find_data->ftLastAccessTime);
2980         _wapi_time_t_to_filetime (buf.st_mtime, &find_data->ftLastWriteTime);
2981
2982         if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2983                 find_data->nFileSizeHigh = 0;
2984                 find_data->nFileSizeLow = 0;
2985         } else {
2986                 find_data->nFileSizeHigh = buf.st_size >> 32;
2987                 find_data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
2988         }
2989
2990         find_data->dwReserved0 = 0;
2991         find_data->dwReserved1 = 0;
2992
2993         utf8_basename = _wapi_basename (utf8_filename);
2994         utf16_basename = g_utf8_to_utf16 (utf8_basename, -1, NULL, &bytes,
2995                                           NULL);
2996         if(utf16_basename==NULL) {
2997                 g_free (utf8_basename);
2998                 g_free (utf8_filename);
2999                 goto retry;
3000         }
3001         ret = TRUE;
3002         
3003         /* utf16 is 2 * utf8 */
3004         bytes *= 2;
3005
3006         memset (find_data->cFileName, '\0', (MAX_PATH*2));
3007
3008         /* Truncating a utf16 string like this might leave the last
3009          * char incomplete
3010          */
3011         memcpy (find_data->cFileName, utf16_basename,
3012                 bytes<(MAX_PATH*2)-2?bytes:(MAX_PATH*2)-2);
3013
3014         find_data->cAlternateFileName [0] = 0;  /* not used */
3015
3016         g_free (utf8_basename);
3017         g_free (utf8_filename);
3018         g_free (utf16_basename);
3019
3020 cleanup:
3021         thr_ret = _wapi_handle_unlock_handle (handle);
3022         g_assert (thr_ret == 0);
3023         pthread_cleanup_pop (0);
3024         
3025         return(ret);
3026 }
3027
3028 /**
3029  * FindClose:
3030  * @wapi_handle: the find handle to close.
3031  *
3032  * Closes find handle @wapi_handle
3033  *
3034  * Return value: %TRUE on success, %FALSE otherwise.
3035  */
3036 gboolean FindClose (gpointer handle)
3037 {
3038         struct _WapiHandle_find *find_handle;
3039         gboolean ok;
3040         int thr_ret;
3041
3042         if (handle == NULL) {
3043                 SetLastError (ERROR_INVALID_HANDLE);
3044                 return(FALSE);
3045         }
3046         
3047         ok=_wapi_lookup_handle (handle, WAPI_HANDLE_FIND,
3048                                 (gpointer *)&find_handle);
3049         if(ok==FALSE) {
3050                 g_warning ("%s: error looking up find handle %p", __func__,
3051                            handle);
3052                 SetLastError (ERROR_INVALID_HANDLE);
3053                 return(FALSE);
3054         }
3055
3056         pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
3057                               handle);
3058         thr_ret = _wapi_handle_lock_handle (handle);
3059         g_assert (thr_ret == 0);
3060         
3061         g_strfreev (find_handle->namelist);
3062         g_free (find_handle->dir_part);
3063
3064         thr_ret = _wapi_handle_unlock_handle (handle);
3065         g_assert (thr_ret == 0);
3066         pthread_cleanup_pop (0);
3067         
3068         _wapi_handle_unref (handle);
3069         
3070         return(TRUE);
3071 }
3072
3073 /**
3074  * CreateDirectory:
3075  * @name: a pointer to a NULL-terminated unicode string, that names
3076  * the directory to be created.
3077  * @security: ignored for now
3078  *
3079  * Creates directory @name
3080  *
3081  * Return value: %TRUE on success, %FALSE otherwise.
3082  */
3083 gboolean CreateDirectory (const gunichar2 *name,
3084                           WapiSecurityAttributes *security)
3085 {
3086         gchar *utf8_name;
3087         int result;
3088         
3089         if (name == NULL) {
3090 #ifdef DEBUG
3091                 g_message("%s: name is NULL", __func__);
3092 #endif
3093
3094                 SetLastError (ERROR_INVALID_NAME);
3095                 return(FALSE);
3096         }
3097         
3098         utf8_name = mono_unicode_to_external (name);
3099         if (utf8_name == NULL) {
3100 #ifdef DEBUG
3101                 g_message ("%s: unicode conversion returned NULL", __func__);
3102 #endif
3103         
3104                 SetLastError (ERROR_INVALID_NAME);
3105                 return FALSE;
3106         }
3107
3108         result = _wapi_mkdir (utf8_name, 0777);
3109
3110         if (result == 0) {
3111                 g_free (utf8_name);
3112                 return TRUE;
3113         }
3114
3115         _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3116         g_free (utf8_name);
3117         return FALSE;
3118 }
3119
3120 /**
3121  * RemoveDirectory:
3122  * @name: a pointer to a NULL-terminated unicode string, that names
3123  * the directory to be removed.
3124  *
3125  * Removes directory @name
3126  *
3127  * Return value: %TRUE on success, %FALSE otherwise.
3128  */
3129 gboolean RemoveDirectory (const gunichar2 *name)
3130 {
3131         gchar *utf8_name;
3132         int result;
3133         
3134         if (name == NULL) {
3135 #ifdef DEBUG
3136                 g_message("%s: name is NULL", __func__);
3137 #endif
3138
3139                 SetLastError (ERROR_INVALID_NAME);
3140                 return(FALSE);
3141         }
3142
3143         utf8_name = mono_unicode_to_external (name);
3144         if (utf8_name == NULL) {
3145 #ifdef DEBUG
3146                 g_message ("%s: unicode conversion returned NULL", __func__);
3147 #endif
3148                 
3149                 SetLastError (ERROR_INVALID_NAME);
3150                 return FALSE;
3151         }
3152
3153         result = _wapi_rmdir (utf8_name);
3154         if (result == -1) {
3155                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3156                 g_free (utf8_name);
3157                 
3158                 return(FALSE);
3159         }
3160         g_free (utf8_name);
3161
3162         return(TRUE);
3163 }
3164
3165 /**
3166  * GetFileAttributes:
3167  * @name: a pointer to a NULL-terminated unicode filename.
3168  *
3169  * Gets the attributes for @name;
3170  *
3171  * Return value: %INVALID_FILE_ATTRIBUTES on failure
3172  */
3173 guint32 GetFileAttributes (const gunichar2 *name)
3174 {
3175         gchar *utf8_name;
3176         struct stat buf, linkbuf;
3177         int result;
3178         guint32 ret;
3179         
3180         if (name == NULL) {
3181 #ifdef DEBUG
3182                 g_message("%s: name is NULL", __func__);
3183 #endif
3184
3185                 SetLastError (ERROR_INVALID_NAME);
3186                 return(FALSE);
3187         }
3188         
3189         utf8_name = mono_unicode_to_external (name);
3190         if (utf8_name == NULL) {
3191 #ifdef DEBUG
3192                 g_message ("%s: unicode conversion returned NULL", __func__);
3193 #endif
3194
3195                 SetLastError (ERROR_INVALID_PARAMETER);
3196                 return (INVALID_FILE_ATTRIBUTES);
3197         }
3198
3199         result = _wapi_stat (utf8_name, &buf);
3200         if (result == -1 && errno == ENOENT) {
3201                 /* Might be a dangling symlink... */
3202                 result = _wapi_lstat (utf8_name, &buf);
3203         }
3204
3205         if (result != 0) {
3206                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3207                 g_free (utf8_name);
3208                 return (INVALID_FILE_ATTRIBUTES);
3209         }
3210
3211         result = _wapi_lstat (utf8_name, &linkbuf);
3212         if (result != 0) {
3213                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3214                 g_free (utf8_name);
3215                 return (INVALID_FILE_ATTRIBUTES);
3216         }
3217         
3218         ret = _wapi_stat_to_file_attributes (utf8_name, &buf, &linkbuf);
3219         
3220         g_free (utf8_name);
3221
3222         return(ret);
3223 }
3224
3225 /**
3226  * GetFileAttributesEx:
3227  * @name: a pointer to a NULL-terminated unicode filename.
3228  * @level: must be GetFileExInfoStandard
3229  * @info: pointer to a WapiFileAttributesData structure
3230  *
3231  * Gets attributes, size and filetimes for @name;
3232  *
3233  * Return value: %TRUE on success, %FALSE on failure
3234  */
3235 gboolean GetFileAttributesEx (const gunichar2 *name, WapiGetFileExInfoLevels level, gpointer info)
3236 {
3237         gchar *utf8_name;
3238         WapiFileAttributesData *data;
3239
3240         struct stat buf, linkbuf;
3241         time_t create_time;
3242         int result;
3243         
3244         if (level != GetFileExInfoStandard) {
3245 #ifdef DEBUG
3246                 g_message ("%s: info level %d not supported.", __func__,
3247                            level);
3248 #endif
3249
3250                 SetLastError (ERROR_INVALID_PARAMETER);
3251                 return FALSE;
3252         }
3253         
3254         if (name == NULL) {
3255 #ifdef DEBUG
3256                 g_message("%s: name is NULL", __func__);
3257 #endif
3258
3259                 SetLastError (ERROR_INVALID_NAME);
3260                 return(FALSE);
3261         }
3262
3263         utf8_name = mono_unicode_to_external (name);
3264         if (utf8_name == NULL) {
3265 #ifdef DEBUG
3266                 g_message ("%s: unicode conversion returned NULL", __func__);
3267 #endif
3268
3269                 SetLastError (ERROR_INVALID_PARAMETER);
3270                 return FALSE;
3271         }
3272
3273         result = _wapi_stat (utf8_name, &buf);
3274         if (result == -1 && errno == ENOENT) {
3275                 /* Might be a dangling symlink... */
3276                 result = _wapi_lstat (utf8_name, &buf);
3277         }
3278         
3279         if (result != 0) {
3280                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3281                 g_free (utf8_name);
3282                 return FALSE;
3283         }
3284
3285         result = _wapi_lstat (utf8_name, &linkbuf);
3286         if (result != 0) {
3287                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3288                 g_free (utf8_name);
3289                 return(FALSE);
3290         }
3291
3292         /* fill data block */
3293
3294         data = (WapiFileAttributesData *)info;
3295
3296         if (buf.st_mtime < buf.st_ctime)
3297                 create_time = buf.st_mtime;
3298         else
3299                 create_time = buf.st_ctime;
3300         
3301         data->dwFileAttributes = _wapi_stat_to_file_attributes (utf8_name,
3302                                                                 &buf,
3303                                                                 &linkbuf);
3304
3305         g_free (utf8_name);
3306
3307         _wapi_time_t_to_filetime (create_time, &data->ftCreationTime);
3308         _wapi_time_t_to_filetime (buf.st_atime, &data->ftLastAccessTime);
3309         _wapi_time_t_to_filetime (buf.st_mtime, &data->ftLastWriteTime);
3310
3311         if (data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
3312                 data->nFileSizeHigh = 0;
3313                 data->nFileSizeLow = 0;
3314         }
3315         else {
3316                 data->nFileSizeHigh = buf.st_size >> 32;
3317                 data->nFileSizeLow = buf.st_size & 0xFFFFFFFF;
3318         }
3319
3320         return TRUE;
3321 }
3322
3323 /**
3324  * SetFileAttributes
3325  * @name: name of file
3326  * @attrs: attributes to set
3327  *
3328  * Changes the attributes on a named file.
3329  *
3330  * Return value: %TRUE on success, %FALSE on failure.
3331  */
3332 extern gboolean SetFileAttributes (const gunichar2 *name, guint32 attrs)
3333 {
3334         /* FIXME: think of something clever to do on unix */
3335         gchar *utf8_name;
3336         struct stat buf;
3337         int result;
3338
3339         /*
3340          * Currently we only handle one *internal* case, with a value that is
3341          * not standard: 0x80000000, which means `set executable bit'
3342          */
3343         
3344         if (name == NULL) {
3345 #ifdef DEBUG
3346                 g_message("%s: name is NULL", __func__);
3347 #endif
3348
3349                 SetLastError (ERROR_INVALID_NAME);
3350                 return(FALSE);
3351         }
3352
3353         utf8_name = mono_unicode_to_external (name);
3354         if (utf8_name == NULL) {
3355 #ifdef DEBUG
3356                 g_message ("%s: unicode conversion returned NULL", __func__);
3357 #endif
3358
3359                 SetLastError (ERROR_INVALID_NAME);
3360                 return FALSE;
3361         }
3362
3363         result = _wapi_stat (utf8_name, &buf);
3364         if (result != 0) {
3365                 _wapi_set_last_path_error_from_errno (NULL, utf8_name);
3366                 g_free (utf8_name);
3367                 return FALSE;
3368         }
3369
3370         /* Contrary to the documentation, ms allows NORMAL to be
3371          * specified along with other attributes, so dont bother to
3372          * catch that case here.
3373          */
3374         if (attrs & FILE_ATTRIBUTE_READONLY) {
3375                 result = _wapi_chmod (utf8_name, buf.st_mode & ~(S_IWRITE | S_IWOTH | S_IWGRP));
3376         } else {
3377                 result = _wapi_chmod (utf8_name, buf.st_mode | S_IWRITE);
3378         }
3379
3380         /* Ignore the other attributes for now */
3381
3382         if (attrs & 0x80000000){
3383                 mode_t exec_mask = 0;
3384
3385                 if ((buf.st_mode & S_IRUSR) != 0)
3386                         exec_mask |= S_IXUSR;
3387
3388                 if ((buf.st_mode & S_IRGRP) != 0)
3389                         exec_mask |= S_IXGRP;
3390
3391                 if ((buf.st_mode & S_IROTH) != 0)
3392                         exec_mask |= S_IXOTH;
3393
3394                 result = chmod (utf8_name, buf.st_mode | exec_mask);
3395         }
3396         /* Don't bother to reset executable (might need to change this
3397          * policy)
3398          */
3399         
3400         g_free (utf8_name);
3401
3402         return(TRUE);
3403 }
3404
3405 /**
3406  * GetCurrentDirectory
3407  * @length: size of the buffer
3408  * @buffer: pointer to buffer that recieves path
3409  *
3410  * Retrieves the current directory for the current process.
3411  *
3412  * Return value: number of characters in buffer on success, zero on failure
3413  */
3414 extern guint32 GetCurrentDirectory (guint32 length, gunichar2 *buffer)
3415 {
3416         gchar *path;
3417         gunichar2 *utf16_path;
3418         glong count;
3419         gsize bytes;
3420         
3421         path = g_get_current_dir ();
3422         if (path == NULL)
3423                 return 0;
3424
3425         utf16_path=mono_unicode_from_external (path, &bytes);
3426         
3427         /* if buffer too small, return number of characters required.
3428          * this is plain dumb.
3429          */
3430         
3431         count = (bytes/2)+1;
3432         if (count > length) {
3433                 g_free(path);
3434                 g_free (utf16_path);
3435                 
3436                 return (count);
3437         }
3438
3439         /* Add the terminator */
3440         memset (buffer, '\0', bytes+2);
3441         memcpy (buffer, utf16_path, bytes);
3442         
3443         g_free (utf16_path);
3444         g_free (path);
3445
3446         return count;
3447 }
3448
3449 /**
3450  * SetCurrentDirectory
3451  * @path: path to new directory
3452  *
3453  * Changes the directory path for the current process.
3454  *
3455  * Return value: %TRUE on success, %FALSE on failure.
3456  */
3457 extern gboolean SetCurrentDirectory (const gunichar2 *path)
3458 {
3459         gchar *utf8_path;
3460         gboolean result;
3461
3462         if (path == NULL) {
3463                 SetLastError (ERROR_INVALID_PARAMETER);
3464                 return(FALSE);
3465         }
3466         
3467         utf8_path = mono_unicode_to_external (path);
3468         if (_wapi_chdir (utf8_path) != 0) {
3469                 _wapi_set_last_error_from_errno ();
3470                 result = FALSE;
3471         }
3472         else
3473                 result = TRUE;
3474
3475         g_free (utf8_path);
3476         return result;
3477 }
3478
3479 gboolean CreatePipe (gpointer *readpipe, gpointer *writepipe,
3480                      WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 size)
3481 {
3482         struct _WapiHandle_file pipe_read_handle = {0};
3483         struct _WapiHandle_file pipe_write_handle = {0};
3484         gpointer read_handle;
3485         gpointer write_handle;
3486         int filedes[2];
3487         int ret;
3488         
3489         mono_once (&io_ops_once, io_ops_init);
3490         
3491 #ifdef DEBUG
3492         g_message ("%s: Creating pipe", __func__);
3493 #endif
3494
3495         ret=pipe (filedes);
3496         if(ret==-1) {
3497 #ifdef DEBUG
3498                 g_message ("%s: Error creating pipe: %s", __func__,
3499                            strerror (errno));
3500 #endif
3501                 
3502                 _wapi_set_last_error_from_errno ();
3503                 return(FALSE);
3504         }
3505
3506         if (filedes[0] >= _wapi_fd_reserve ||
3507             filedes[1] >= _wapi_fd_reserve) {
3508 #ifdef DEBUG
3509                 g_message ("%s: File descriptor is too big", __func__);
3510 #endif
3511
3512                 SetLastError (ERROR_TOO_MANY_OPEN_FILES);
3513                 
3514                 close (filedes[0]);
3515                 close (filedes[1]);
3516                 
3517                 return(FALSE);
3518         }
3519         
3520         /* filedes[0] is open for reading, filedes[1] for writing */
3521
3522         pipe_read_handle.fileaccess = GENERIC_READ;
3523         read_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[0],
3524                                            &pipe_read_handle);
3525         if (read_handle == _WAPI_HANDLE_INVALID) {
3526                 g_warning ("%s: error creating pipe read handle", __func__);
3527                 close (filedes[0]);
3528                 close (filedes[1]);
3529                 SetLastError (ERROR_GEN_FAILURE);
3530                 
3531                 return(FALSE);
3532         }
3533         
3534         pipe_write_handle.fileaccess = GENERIC_WRITE;
3535         write_handle = _wapi_handle_new_fd (WAPI_HANDLE_PIPE, filedes[1],
3536                                             &pipe_write_handle);
3537         if (write_handle == _WAPI_HANDLE_INVALID) {
3538                 g_warning ("%s: error creating pipe write handle", __func__);
3539                 _wapi_handle_unref (read_handle);
3540                 
3541                 close (filedes[0]);
3542                 close (filedes[1]);
3543                 SetLastError (ERROR_GEN_FAILURE);
3544                 
3545                 return(FALSE);
3546         }
3547         
3548         *readpipe = read_handle;
3549         *writepipe = write_handle;
3550
3551 #ifdef DEBUG
3552         g_message ("%s: Returning pipe: read handle %p, write handle %p",
3553                    __func__, read_handle, write_handle);
3554 #endif
3555
3556         return(TRUE);
3557 }
3558
3559 guint32 GetTempPath (guint32 len, gunichar2 *buf)
3560 {
3561         gchar *tmpdir=g_strdup (g_get_tmp_dir ());
3562         gunichar2 *tmpdir16=NULL;
3563         glong dirlen;
3564         gsize bytes;
3565         guint32 ret;
3566         
3567         if(tmpdir[strlen (tmpdir)]!='/') {
3568                 g_free (tmpdir);
3569                 tmpdir=g_strdup_printf ("%s/", g_get_tmp_dir ());
3570         }
3571         
3572         tmpdir16=mono_unicode_from_external (tmpdir, &bytes);
3573         if(tmpdir16==NULL) {
3574                 g_free (tmpdir);
3575                 return(0);
3576         } else {
3577                 dirlen=(bytes/2);
3578                 
3579                 if(dirlen+1>len) {
3580 #ifdef DEBUG
3581                         g_message ("%s: Size %d smaller than needed (%ld)",
3582                                    __func__, len, dirlen+1);
3583 #endif
3584                 
3585                         ret=dirlen+1;
3586                 } else {
3587                         /* Add the terminator */
3588                         memset (buf, '\0', bytes+2);
3589                         memcpy (buf, tmpdir16, bytes);
3590                 
3591                         ret=dirlen;
3592                 }
3593         }
3594
3595         if(tmpdir16!=NULL) {
3596                 g_free (tmpdir16);
3597         }
3598         g_free (tmpdir);
3599         
3600         return(ret);
3601 }
3602
3603 gint32
3604 GetLogicalDriveStrings (guint32 len, gunichar2 *buf)
3605 {
3606         FILE *fp;
3607         gunichar2 *ptr, *dir;
3608         glong length, total = 0;
3609         gchar buffer [512];
3610         gchar **splitted;
3611
3612         memset (buf, 0, sizeof (gunichar2) * (len + 1)); 
3613         buf [0] = '/';
3614         buf [1] = 0;
3615         buf [2] = 0;
3616
3617         /* Sigh, mntent and friends don't work well.
3618          * It stops on the first line that doesn't begin with a '/'.
3619          * (linux 2.6.5, libc 2.3.2.ds1-12) - Gonz */
3620         fp = fopen ("/etc/mtab", "rt");
3621         if (fp == NULL) {
3622                 fp = fopen ("/etc/mnttab", "rt");
3623                 if (fp == NULL)
3624                         return 1;
3625         }
3626
3627         ptr = buf;
3628         while (fgets (buffer, 512, fp) != NULL) {
3629                 if (*buffer != '/')
3630                         continue;
3631
3632                 splitted = g_strsplit (buffer, " ", 0);
3633                 if (!*splitted || !*(splitted + 1)) {
3634                         g_strfreev (splitted);
3635                         continue;
3636                 }
3637
3638                 dir = g_utf8_to_utf16 (*(splitted + 1), -1, &length, NULL, NULL);
3639                 g_strfreev (splitted);
3640                 if (total + length + 1 > len) {
3641                         fclose (fp);
3642                         return len * 2; /* guess */
3643                 }
3644
3645                 memcpy (ptr + total, dir, sizeof (gunichar2) * length);
3646                 g_free (dir);
3647                 total += length + 1;
3648         }
3649
3650         fclose (fp);
3651         return total;
3652 /* Commented out, does not work with my mtab!!! - Gonz */
3653 #ifdef NOTENABLED /* HAVE_MNTENT_H */
3654 {
3655         FILE *fp;
3656         struct mntent *mnt;
3657         gunichar2 *ptr, *dir;
3658         glong len, total = 0;
3659         
3660
3661         fp = setmntent ("/etc/mtab", "rt");
3662         if (fp == NULL) {
3663                 fp = setmntent ("/etc/mnttab", "rt");
3664                 if (fp == NULL)
3665                         return;
3666         }
3667
3668         ptr = buf;
3669         while ((mnt = getmntent (fp)) != NULL) {
3670                 g_print ("GOT %s\n", mnt->mnt_dir);
3671                 dir = g_utf8_to_utf16 (mnt->mnt_dir, &len, NULL, NULL, NULL);
3672                 if (total + len + 1 > len) {
3673                         return len * 2; /* guess */
3674                 }
3675
3676                 memcpy (ptr + total, dir, sizeof (gunichar2) * len);
3677                 g_free (dir);
3678                 total += len + 1;
3679         }
3680
3681         endmntent (fp);
3682         return total;
3683 }
3684 #endif
3685 }
3686
3687 static gboolean _wapi_lock_file_region (int fd, off_t offset, off_t length)
3688 {
3689         struct flock lock_data;
3690         int ret;
3691
3692         lock_data.l_type = F_WRLCK;
3693         lock_data.l_whence = SEEK_SET;
3694         lock_data.l_start = offset;
3695         lock_data.l_len = length;
3696         
3697         do {
3698                 ret = fcntl (fd, F_SETLK, &lock_data);
3699         } while(ret == -1 && errno == EINTR);
3700         
3701 #ifdef DEBUG
3702         g_message ("%s: fcntl returns %d", __func__, ret);
3703 #endif
3704
3705         if (ret == -1) {
3706                 /*
3707                  * if locks are not available (NFS for example),
3708                  * ignore the error
3709                  */
3710                 if (errno == ENOLCK
3711 #ifdef EOPNOTSUPP
3712                     || errno == EOPNOTSUPP
3713 #endif
3714 #ifdef ENOTSUP
3715                     || errno == ENOTSUP
3716 #endif
3717                    ) {
3718                         return (TRUE);
3719                 }
3720                 
3721                 SetLastError (ERROR_LOCK_VIOLATION);
3722                 return(FALSE);
3723         }
3724
3725         return(TRUE);
3726 }
3727
3728 static gboolean _wapi_unlock_file_region (int fd, off_t offset, off_t length)
3729 {
3730         struct flock lock_data;
3731         int ret;
3732
3733         lock_data.l_type = F_UNLCK;
3734         lock_data.l_whence = SEEK_SET;
3735         lock_data.l_start = offset;
3736         lock_data.l_len = length;
3737         
3738         do {
3739                 ret = fcntl (fd, F_SETLK, &lock_data);
3740         } while(ret == -1 && errno == EINTR);
3741         
3742 #ifdef DEBUG
3743         g_message ("%s: fcntl returns %d", __func__, ret);
3744 #endif
3745         
3746         if (ret == -1) {
3747                 /*
3748                  * if locks are not available (NFS for example),
3749                  * ignore the error
3750                  */
3751                 if (errno == ENOLCK
3752 #ifdef EOPNOTSUPP
3753                     || errno == EOPNOTSUPP
3754 #endif
3755 #ifdef ENOTSUP
3756                     || errno == ENOTSUP
3757 #endif
3758                    ) {
3759                         return (TRUE);
3760                 }
3761                 
3762                 SetLastError (ERROR_LOCK_VIOLATION);
3763                 return(FALSE);
3764         }
3765
3766         return(TRUE);
3767 }
3768
3769 gboolean LockFile (gpointer handle, guint32 offset_low, guint32 offset_high,
3770                    guint32 length_low, guint32 length_high)
3771 {
3772         struct _WapiHandle_file *file_handle;
3773         gboolean ok;
3774         off_t offset, length;
3775         int fd = GPOINTER_TO_UINT(handle);
3776         
3777         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3778                                   (gpointer *)&file_handle);
3779         if (ok == FALSE) {
3780                 g_warning ("%s: error looking up file handle %p", __func__,
3781                            handle);
3782                 SetLastError (ERROR_INVALID_HANDLE);
3783                 return(FALSE);
3784         }
3785
3786         if (!(file_handle->fileaccess & GENERIC_READ) &&
3787             !(file_handle->fileaccess & GENERIC_WRITE) &&
3788             !(file_handle->fileaccess & GENERIC_ALL)) {
3789 #ifdef DEBUG
3790                 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3791 #endif
3792                 SetLastError (ERROR_ACCESS_DENIED);
3793                 return(FALSE);
3794         }
3795
3796 #ifdef HAVE_LARGE_FILE_SUPPORT
3797         offset = ((gint64)offset_high << 32) | offset_low;
3798         length = ((gint64)length_high << 32) | length_low;
3799
3800 #ifdef DEBUG
3801         g_message ("%s: Locking handle %p, offset %lld, length %lld", __func__,
3802                    handle, offset, length);
3803 #endif
3804 #else
3805         offset = offset_low;
3806         length = length_low;
3807
3808 #ifdef DEBUG
3809         g_message ("%s: Locking handle %p, offset %ld, length %ld", __func__,
3810                    handle, offset, length);
3811 #endif
3812 #endif
3813
3814         return(_wapi_lock_file_region (fd, offset, length));
3815 }
3816
3817 gboolean UnlockFile (gpointer handle, guint32 offset_low,
3818                      guint32 offset_high, guint32 length_low,
3819                      guint32 length_high)
3820 {
3821         struct _WapiHandle_file *file_handle;
3822         gboolean ok;
3823         off_t offset, length;
3824         int fd = GPOINTER_TO_UINT(handle);
3825         
3826         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
3827                                   (gpointer *)&file_handle);
3828         if (ok == FALSE) {
3829                 g_warning ("%s: error looking up file handle %p", __func__,
3830                            handle);
3831                 SetLastError (ERROR_INVALID_HANDLE);
3832                 return(FALSE);
3833         }
3834         
3835         if (!(file_handle->fileaccess & GENERIC_READ) &&
3836             !(file_handle->fileaccess & GENERIC_WRITE) &&
3837             !(file_handle->fileaccess & GENERIC_ALL)) {
3838 #ifdef DEBUG
3839                 g_message ("%s: handle %p doesn't have GENERIC_READ or GENERIC_WRITE access: %u", __func__, handle, file_handle->fileaccess);
3840 #endif
3841                 SetLastError (ERROR_ACCESS_DENIED);
3842                 return(FALSE);
3843         }
3844
3845 #ifdef HAVE_LARGE_FILE_SUPPORT
3846         offset = ((gint64)offset_high << 32) | offset_low;
3847         length = ((gint64)length_high << 32) | length_low;
3848
3849 #ifdef DEBUG
3850         g_message ("%s: Unlocking handle %p, offset %lld, length %lld",
3851                    __func__, handle, offset, length);
3852 #endif
3853 #else
3854         offset = offset_low;
3855         length = length_low;
3856
3857 #ifdef DEBUG
3858         g_message ("%s: Unlocking handle %p, offset %ld, length %ld", __func__,
3859                    handle, offset, length);
3860 #endif
3861 #endif
3862
3863         return(_wapi_unlock_file_region (fd, offset, length));
3864 }