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